[英]Sending integer values to Arduino from PySerial
I need to send integers greater than 255? 我需要发送大于255的整数吗? Does anyone know how to do this?
有谁知道如何做到这一点?
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: 的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
Encode them into binary strings with Python's struct
module. 使用Python的
struct
模块将它们编码为二进制字符串。 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;-). 我不知道arduino是否希望它们为小端或大端,但是,如果其文档尚不清楚,只需进行一些实验即可轻松解决问题;-)。
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 ! 无需工会,时间短!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.