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 !