1
votes

I am trying to send six integers at a time through Serial.write() on arduino and send them to python. so far, I have managed to turn the Integers into byte pointers (I think thats the name) and send them over serial. however, when I try to reassemble them on the python side, I get some strange numbers that I did not intend to see.

Arduino Code:

int myInts[6]= {1455, 1446, 6766, 974, 365, 455};

void setup()
{
  Serial.begin(9600);
}
void loop()
{  

  byte *p = (byte)myInts;
  for(byte i = 0; i < sizeof(myInts); i++){
    Serial.write(p[i]);
  }
}

Python Code

import argparse
import numpy
import time
import serial 
import struct

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
    b = ser.read(4)

    i = struct.unpack('i' ,b)
    print(i)

Output:

(-1090650113,) (285341695,) (10683141,) (-1090650177,) (285341695,) (10683141,)

Thanks!

Vik

1

1 Answers

1
votes

I will offer several alternatives. Easiest one is listed last.

First thing you should realize is that int is a different size on the two platforms. Arduino int is a signed 16-bit int, -32768 -> 32767. Your python int is a 32-bit int. Certainly the numbers being returned are far outside the range of any 16-bit number.

I would recommend changing your int in the Arduino to unsigned int and then change your python unpack format string to H (unsigned short). Or, leave the Arduino as int and change your python unpack format string to 'h' (short) and see if that makes a difference for you. Oh and of course you should change to b = ser.read(2) because these are now all 2-byte integers.

Next, Arduino's Serial.write() method supports a single byte, a string, or a buffer with a length. Not a byte pointer. So while I don't have an Arduino here in front of me to test, I think you should be using the Serial.write(buf,len) form of the command and get rid of the "byte pointers", which I've never seen mentioned in any Arduino documentation:

Serial.write(myInts, 12);

Finally, the easiest thing to do is simply to use Serial.print(str) or Serial.println(str) and send a string across. Then on the python side simply convert the string to an integer type of your choosing.