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?
1 Answer 1
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.
-
3Yes. 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.Chris Stratton– Chris Stratton2017年07月12日 23:28:45 +00:00Commented Jul 12, 2017 at 23:28
buff[9]
.