I'm using an Arduino Mega to send serial commands to a device that supports RS485 or RS422 half-duplex. To do this, I'm using the following code:
bool foo(int A, int B)
//...
//Const global int to byte 1&2
//Math on int A and int B to make bytes 3-8
//...
unsigned char cmd[8]={[byte1],[byte2],[byte3],[byte4],[byte5],[byte6],[byte7],[byte8]};
while(rep)
{
for (int i=0; i< 8; i++)
{
Serial2.write(cmd[i]); // Send C string
}
if(Serial2.available())
{
//device echoed == command recieved
rep=false;
}
}
The odd thing is that sometimes the loop gets it right on the first try, other times it takes 50+ tries to receive a command. This makes me think that there is something in my code that is making the data transmission unreliable. I believe it could be one of the following three things.
- I still need an RS485 module
In a previous version of my software, I was using the software serial library and used an RS485 module similar to the one shown here:
As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?
- Looping the
Serial2.write()
Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++)
loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?
- I'm Not supporting a tri-state the transmit buffer
I was rereading the device's manual and found this line:
The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.
Honestly, I have no idea what this means. Does Arduino do this? If not, how can I make this happen?
Additional things of note:
- I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be
\0
(or any other termchar) which would stop the loop prematurely. Is there a way to avoid this? - I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?