0

I'm trying to send an array of numbers from python to Arduino over the serial connection. I can reliably read a small incoming set of numbers (for example 123435678) from python, which I can then parse since I know how many digits are supposed to be in each number (for example, 1, 23456, 78). I do this with my Arduino code:

void getInput() {
 char buff[9];
 int field1;
 char field2[6];
 char field3[3];
 Serial.readBytes(buff, 8); //read 8 bytes from the Serial port
 buff[9] = '0円'; //null terminate the string we just read
 Serial.println(buff); //check that we got it
 for(int i=0; i<buff_len;i++) { //now we divide up the string into separate numbers
 if(i==0) {
 field1 = buff[0] - 48; //turn it into an int using ASCII 
 }
 if(i>=1 && i<6) {
 field2[i-1] = buff[i];
 field2[5] = '0円';
 }
 if(i>=6) {
 field3[i-6]=buff[i];
 field3[2] = '0円';
 }
 }
 for(int i=0;i<buff_len;i++) { //clear the buffer
 buff[i]=0;
 }
}

But if I wanted to send a whole array whose contents I don't know in advance, for example like this:

for i in range(200):
 ser.write(i)

What's the best way to get these numbers to Arduino and file them away in an int array? Should I make the array in python first as a numpy.linspace() and send that?

VE7JRO
2,51519 gold badges27 silver badges29 bronze badges
asked Jul 12, 2017 at 18:41
1
  • 1
    While it's probably not your only issue, you invoke undefined behavior when you write to the 10th element (index 9) of the 9-element buff[9]. Commented Jul 12, 2017 at 23:30

1 Answer 1

2

If you don't know the length of the data then you need to be sending start and end markers so your other code can tell where the transmission starts and ends. I usually use < and>, so the data packet might look like <12345678>. You don't have to use those particular characters, just pick something that you know won't show up in your data.

answered Jul 12, 2017 at 20:31
1
  • 3
    Yes. Putting a newline at the end of each is even more common, and plays well with many traditional computing tools. Since there seem to be multiple fields in each entry, putting a space or comma between them would also help. Commented Jul 12, 2017 at 23:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.