0

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

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>

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.