Sending integer values to Arduino from PySerial

2019-04-15 16:28发布

问题:

I need to send integers greater than 255? Does anyone know how to do this?

回答1:

Here's how (Thanks for the idea, Alex!):

Python:

def packIntegerAsULong(value):
    """Packs a python 4 byte unsigned integer to an arduino unsigned long"""
    return struct.pack('I', value)    #should check bounds

# To see what it looks like on python side
val = 15000
print binascii.hexlify(port.packIntegerAsULong(val))

# send and receive via pyserial
ser = serial.Serial(serialport, bps, timeout=1)
ser.write(packIntegerAsULong(val))
line = ser.readLine()
print line

Arduino:

unsigned long readULongFromBytes() {
  union u_tag {
    byte b[4];
    unsigned long ulval;
  } u;
  u.b[0] = Serial.read();
  u.b[1] = Serial.read();
  u.b[2] = Serial.read();
  u.b[3] = Serial.read();
  return u.ulval;
}
unsigned long val = readULongFromBytes();
Serial.print(val, DEC); // send to python to check


回答2:

Encode them into binary strings with Python's struct module. I don't know if arduino wants them little-endian or big-endian, but, if its docs aren't clear about this, a little experiment should easily settle the question;-).



回答3:

Way easier :

  crc_out = binascii.crc32(data_out) & 0xffffffff   # create unsigned long
  print "crc bytes written",arduino.write(struct.pack('<L', crc_out)) #L, I whatever u like to use just use 4 bytes value

  unsigned long crc_python = 0;
  for(uint8_t i=0;i<4;i++){        
    crc_python |= ((long) Serial.read() << (i*8));
  }

No union needed and short !