Need some help on creating a RS485 library on NXC
Posted: 30 Jun 2011, 20:41
Hi,
For a next robot build, I'd like to use RS485 connection, but I can't get it to work. I have never used RS485 before, so it seemed me the best to make a library so I can use it very often and easy.
Here's my Lib I created:
When I try it out with my test programs, nothing happens.
Master code:
Slave code:
It should turn motor A, but it doesn't do anything!!!
Does somebody know my mistake(s)?
Thanks,
Robbe
For a next robot build, I'd like to use RS485 connection, but I can't get it to work. I have never used RS485 before, so it seemed me the best to make a library so I can use it very often and easy.
Here's my Lib I created:
Code: Select all
// Lego NXT RS-485 Library
// Made by Robbe D
void WaitForMessageToBeSent() //Wait till the message arrives
{
while(HSOutputBufferOutPtr() < HSOutputBufferInPtr())
Wait(1);
}
void SendBoolRS485(const bool value)
{
SendRS485Bool(value);
WaitForMessageToBeSent();
}
void SendNumberRS485(const int value)
{
SendRS485Number(value);
WaitForMessageToBeSent();
}
void SendStringRS485(const string value)
{
SendRS485String(value);
WaitForMessageToBeSent();
}
string GetStringRS485()
{
byte mlen;
string buffer;
// wait for a message to arrive.
mlen = 0;
while (mlen == 0)
mlen = HSInputBufferInPtr();
// read it.
GetHSInputBuffer(0, mlen, buffer);
// clear the incoming buffer
SetHSInputBufferInPtr(0);
return buffer;
}
int GetNumberRS485()
{
byte mlen;
int buffer;
// wait for a message to arrive.
mlen = 0;
while (mlen == 0)
mlen = HSInputBufferInPtr();
// read it.
GetHSInputBuffer(0, mlen, buffer);
// clear the incoming buffer
SetHSInputBufferInPtr(0);
return buffer;
}
bool GetBoolRS485()
{
byte mlen;
bool buffer;
// wait for a message to arrive.
mlen = 0;
while (mlen == 0)
mlen = HSInputBufferInPtr();
// read it.
GetHSInputBuffer(0, mlen, buffer);
// clear the incoming buffer
SetHSInputBufferInPtr(0);
return buffer;
}
sub SetupRS485()
{
SetSensorType(IN_4, SENSOR_TYPE_HIGHSPEED);
SetHSState(HS_INITIALISE);
SetHSFlags(HS_UPDATE);
SetHSInputBufferInPtr(0);
SetHSInputBufferOutPtr(0);
}
Master code:
Code: Select all
#include "RS485Lib.nxc"
task main()
{
int num;
string str;
bool boolean;
SetupRS485();
SendNumberRS485(1);
num = GetNumberRS485();
if (num == 1)
{OnFwd(OUT_A, 50);}
Wait(2000);
SendStringRS485("test");
str = GetStringRS485();
if (str == "test")
{OnFwd(OUT_A, -50);}
Wait(2000);
SendBoolRS485(true);
boolean = GetBoolRS485();
if (boolean == true)
{OnFwd(OUT_A, 50);}
Wait(2000);
}
Code: Select all
#include "RS485Lib.h"
task main()
{
int num;
string str;
bool boolean;
SetupRS485();
num = GetNumberRS485();
SendNumberRS485(num);
str = GetStringRS485();
SendStringRS485(str);
boolean = GetBoolRS485();
SendBoolRS485(boolean);
}
Does somebody know my mistake(s)?
Thanks,
Robbe