从PySerial向Arduino发送整数值

时间:2010-08-17 23:20:14

标签: python arduino

我需要发送大于255的整数?有谁知道怎么做?

3 个答案:

答案 0 :(得分:4)

这是怎么回事(谢谢你的想法,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

答案 1 :(得分:3)

使用Python的struct模块将它们编码为二进制字符串。我不知道arduino是否想要他们的小端或大端,但是,如果它的文档不清楚这一点,一个小实验应该很容易解决这个问题; - )。

答案 2 :(得分:0)

更容易:

  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));
  }

不需要工会,简短!