Here is example code to send the ranges from one Uno to another with SoftwareSerial. The received values are written to an array of bytes named ranges[]. The receive code is modified from the example #6 of the serial input basics tutorial. Code successfully tested with my 2 Unos and 4 rangefinders.
Sender
#include <NewPing.h>
#include <SoftwareSerial.h>
#define SONAR_NUM 4 // Number of sensors.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
NewPing sonar[SONAR_NUM] = // Sensor object array.
{
NewPing(7, 6, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
NewPing(3, 2, MAX_DISTANCE),
NewPing(5, 4, MAX_DISTANCE),
NewPing(9, 8, MAX_DISTANCE)
};
#define SERIAL_RX 11
#define SERIAL_TX 10
SoftwareSerial mySerial(SERIAL_RX, SERIAL_TX);
byte ranges[SONAR_NUM];
void setup()
{
Serial.begin(9600);
Serial.println("SDM-T3 Arduino Sender");
mySerial.begin(9600);
}
void loop()
{
// if (Serial.available())
for (uint8_t i = 0; i < SONAR_NUM; i++) // Loop through each sensor and display results.
{
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
Serial.print(i);
Serial.print("=");
byte thisRange = (sonar[i].ping_cm());
Serial.print(thisRange);
Serial.print("cm ");
ranges[i] = thisRange;
}
Serial.println();
mySerial.write(0x3C); // start marker
mySerial.write(ranges, SONAR_NUM); // binary data
mySerial.write(0x3E); // end marker
}
Receiver
// Example 6 - Receiving binary data
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
const byte numBytes = 16;
byte receivedBytes[numBytes];
byte numReceived = 0;
boolean newData = false;
byte ranges[4];
void setup()
{
Serial.begin(9600);
Serial.println("<Arduino is ready>");
mySerial.begin(9600);
}
void loop()
{
recvBytesWithStartEndMarkers();
showNewData();
}
void recvBytesWithStartEndMarkers()
{
static boolean recvInProgress = false;
static byte ndx = 0;
byte startMarker = 0x3C;
byte endMarker = 0x3E;
byte rb;
while (mySerial.available() > 0 && newData == false)
{
rb = mySerial.read();
//Serial.print(char(rb));
if (recvInProgress == true)
{
if (rb != endMarker)
{
receivedBytes[ndx] = rb;
ndx++;
if (ndx >= numBytes)
{
ndx = numBytes - 1;
}
}
else
{
receivedBytes[ndx] = '\0'; // terminate the string
recvInProgress = false;
numReceived = ndx; // save the number for use when printing
ndx = 0;
newData = true;
}
}
else if (rb == startMarker)
{
recvInProgress = true;
}
}
}
void showNewData()
{
if (newData == true)
{
Serial.print("This just in (DEC values)... ");
for (byte n = 0; n < numReceived; n++)
{
ranges[n] = receivedBytes[n];
Serial.print(ranges[n], DEC);
Serial.print(' ');
}
Serial.println();
newData = false;
}
}
code formatted with the IDE autoformat tool and posted in code tags. See the the forum guidelines.