Search code examples
serializationarduinoserial-communication

Trying to improve Arduino to Arduino communication via Serial


my current project requires an Arduino Uno to communicate via serial with an Arduino Mega and I would like to improve the data transfer rate.

This Arduino Uno is extracting information from a strain gauge through a bridge circuit using analogRead() (which I have already tested). It then sends this information through Serial to the Mega, which then sends it to a computer using a USB cable and serial communications.

This Mega board is required because the Uno is placed on a rotating axis, and the communication between it and the Mega is done through a circular optocoupler, which I have tested and is also working.

With this out of the way, I'm currently reading data from the rotating Uno at 190Hz. I believe most of the problem is due to a delay(5); present in the code, but even lowering it to 3ms is enough for the data to arrive with missing characters.

The Uno code:

void setup() {
  Serial.begin(19200);
}

void loop() {
  Serial.println(analogRead(A0));
  delay(5);
}

The Mega code:

char t;
void setup() {
Serial.begin(9600);
Serial1.begin(19200);
}

void loop() {
  if (Serial1.available()>0)
    {
      t = Serial1.read();
      Serial.print(t);
    }
}

The data being sent is always an integer from 0 to 1023, since it comes from analogRead(), so maybe I could encode it better, but I'm not sure how to do it or if that would fix the bigger problem of the necessary delay(5);

Thank you very much


Solution

  • Consider the data transfer rates you have configured on the Mega: 19200 bps input and 9600 bps output. Also consider that Serial.print() is a blocking call, so your program has to wait for the entire transfer to finish before looping around for another read. This will effectively limit your transfer rates to 9600 bps (and actually lower because of the overhead of Serial1.read()). As a first step see if you can increase this rate to at least match the input rate (19200 bps).

    If you are confident that that works and the optocoupler connection is not missing pulses, you can try to increase your serial rate further and/or investigate an interrupt driven design that will allow reading and writing in parallel.