Skip to main content
 首页 » 编程设计

python之从 PySerial 向 Arduino 发送整数值

2025年05月04日33shangdawei

我需要发送大于 255 的整数吗?有谁知道如何做到这一点?

请您参考如下方法:

方法如下(感谢 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 

阿杜伊诺:

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