从 PySerial 向 Arduino 发送整数值 [英] Sending integer values to Arduino from PySerial

查看:31
本文介绍了从 PySerial 向 Arduino 发送整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to send integers greater than 255? Does anyone know how to do this?

推荐答案

方法如下(感谢 Alex!):

Here's how (Thanks for the idea, Alex!):

蟒蛇:

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

这篇关于从 PySerial 向 Arduino 发送整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆