missing messages on serial port with RS-485

I have a simple protocol without handshaking.
It works for the most part but now and then, my Arduino will miss a whole message.

I'm using a Nano with a MAX485. The MAX485 is connected to a VkTech USB-to-RS485 adapter.
So this is a 2 wire half-duplex setup I believe... There are 4 wires between the Nano and the MAX485.
But only 2 wires (plus ground) between the MAX485 and the USB adapter.

If the Nano is in 'transmit' mode (DE enabled, RE disabled), and bytes happen to be written to the Nano at that time - then they are lost?

Which would explain why I'm missing bytes. But not why I'd miss a whole message. At least it doesn't seem likely. But this is new to me so maybe.

This code has the Nano sending data regularly and when it's not sending, (or waiting after a send), it's listening for data. If I run it and send a message to the Nano about once every second it will "drop" that message about once a minute.

I suppose if I ran it for an extended time then maybe I'd see error message from partial commands received.

I can easily make a work-around by adding some handshaking. But I'm trying to understand what's happening here first.

forumVersion.ino (10.4 KB)

I'm thinking you might be better of using a proven data protocol, say like Modbus.
Have you considered this at all?
If you have, was there a reason not to use it?

I found it quite simple to implement both the RTU library (async) and TCP library (ethernet) in projects, in my case, between an Arduino and GNU/linux systems.


My reasoning was that I needed communication that was fast enough to update our sensor data - and that the simplest way to achieve that would be to "roll my own".
Now that I'm almost done I can create an interface where I could drop in a Modbus library and do some comparisons.

Not sure on how much work it would be to use a Modbus library though. Glad to hear that it was "simple".

Did you use the Modbus Master library (playground.arduino.cc), 'simple-modbus' (code.google.com) or some other Modbus library?

Put some debugging in, to echo or otherwise display what the error codes from your receive routine are.

 byte byteIn = Serial.read();

 if (byteIn == (byte)(-1))

This is a convoluted way of testing for Serial.available.

Better is:

if (Serial.available ())
  byte byteIn = Serial.read();

  // ... blah blah

In fact, I think your method will actually fail if you want to transmit 0xFF, because in a byte you won't be able to tell the difference between data 0xFF and "no data".

Thanks, Nick, for pointing that out. That block of code has a couple of ridiculous bugs! :-[
Always good to have someone else take a look.