i want to send an array of int to another arduino by serial.
To garantie a better robust during the transmission, i added < and> with endMarker and startMarker.
The receiver wait until the Hardware Serial is open, and read the data from the Software Serial from the sender.
Code for the sender:
int test[] = {1, 2, 3, 4, 5, 6, 7};
void setup() {
Serial.begin(9600); // Hardware Serial
}
void loop() {
for (byte i = 0; i < 7; i++) {
Serial.write("<");
Serial.write(test[i]);
Serial.write(">");
delay(500);
}
}
Code for the reader, i edited the code from here: http://forum.arduino.cc/index.php?topic=396450
// Example 3 - Receive with start- and end-markers
include <SoftwareSerial.h>
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
SoftwareSerial mySerial(10, 11); // RX, TX Software Serial
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
recvWithStartEndMarkers();
showNewData();
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = mySerial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '0円'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
newData = false;
}
}
I don't know if the problem is the serial.write, that send bytes, or i need to use serial.print to send string.
1 Answer 1
You are attempting to use an 8-bit binary protocol to transmit 16 bit values, and then wrapping it in ASCII characters. There is:
- No way to differentiate the ASCII characters from the 8 bit binary data, and
- No way to fit 16 bits into an 8 bit protocol.
The simplest way is to use Serial.print
to make the whole protocol ASCII:
Serial.print("<");
for (byte i = 0; i < 7; i++) {
Serial.print(test[i]);
if (i < 6) {
Serial.print(",");
}
}
Serial.println(">");
Which would send out:
<1,2,3,4,5,6,7>
-
Thx Majenko, can i use the example 5 ( forum.arduino.cc/index.php?topic=396450) to read that output with other arduino?MarkCalaway– MarkCalaway2018年09月10日 19:59:58 +00:00Commented Sep 10, 2018 at 19:59
-
You can use a variation of it, sure.Majenko– Majenko2018年09月10日 20:01:06 +00:00Commented Sep 10, 2018 at 20:01