Passing a command between two arduino via serial

Hi all. I’m trying to set up an arrangement by which arduinos talk to one another via a soft serial. Eventually, four arduinos will cascade commands in a chain. For now, just as a proof of concept I’m trying to get two arduinos to ping-pong a 12-char command between each other. Here’s the code I’m using…

#include <SoftwareSerial.h>
SoftwareSerial ss(5, 6);

int count = 0;

char commandString[12] = “A1234567890A”;

void setup() {
Serial.begin(9600);
ss.begin(9600);
}

void loop() {

if (Serial.available() > 0) { // SENDING ANY SINGLE CHARACTER TRIGGERS THE TEST
Serial.read();
Serial.println(“GO!”);
transmit();
}

if(ss.available()) {

for(int i=0;i<12;i++) {
commandString*=ss.read();*

  • }*

  • Serial.print("received: ");*

  • Serial.println(commandString);*

  • transmit();*

  • }*

}
void transmit() {

  • count++;*

  • if(count<9) { *

  • //sprintf (commandString, “A123456789%01iA”, count);*

  • ss.print(commandString);*

  • Serial.print("transmitted: ");*

  • Serial.println(commandString);*

  • }*

}
[/quote]
But what I’m getting back is garbled…
> GO!
> transmitted: A1234567890A
> received: Ansmitted: A
> transmitted: Aived: 81234567eceived: 90A
> tran90A
> transmitted: 890A
> 567890A
> received: Ansmi
> tratted: A1234567890
> transmitted: 7890
> received: AAansmitted: AAd: received: : 9
Any clues?

Any clues?

Don't try to read data that isn't there (yet)

Gotcha - thanks (and doh). Code below works a treat…

#include <SoftwareSerial.h>
SoftwareSerial ss(5, 6);

int count = 0;

char commandString[12] = “A1234567890A”;

void setup() {
Serial.begin(9600);
ss.begin(9600);
}

void loop() {

if (Serial.available() > 0) { // SENDING ANY SINGLE CHARACTER TRIGGERS THE TEST
Serial.read();
Serial.println(“GO!”);
transmit();
}

int i=0;

if(ss.available()) {
while(i<12) {
if(ss.available()){
commandString*=ss.read();*

  • i++;*
  • }*
  • }*
  • Serial.print("received: ");*
  • Serial.println(commandString);*
  • transmit();*
  • }*

}
void transmit() {

  • count++;*

  • if(count<9) { *

  • sprintf (commandString, “A123456789%01iA”, count);*

  • ss.print(commandString);*

  • Serial.print("transmitted: ");*

  • Serial.println(commandString);*

  • }*

}
[/quote]

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

The technique in the 3rd example will be the most reliable.

You can send data in a compatible format with code like this

Serial.print('<'); // start marker
Serial.print(value1);
Serial.print(','); // comma separator
Serial.print(value2);
Serial.println('>'); // end marker

…R