通过PySerial向Arduino发送整数值

1 投票
3 回答
15345 浏览
提问于 2025-04-16 02:56

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

3 个回答

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

不需要联合,代码也短!

3

用Python的struct模块把它们编码成二进制字符串。我不太确定Arduino需要的是小端格式还是大端格式,不过如果它的文档没有说明清楚,做个小实验就能轻松搞明白了;-).

5

这是方法(感谢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

撰写回答