【问题标题】:Reading integer from arduino using pyserial使用pyserial从arduino读取整数
【发布时间】:2016-10-14 17:33:34
【问题描述】:

我正在从 arduino 发送整数值并使用 pyserial 在 Python 中读取它 arduino代码是:

Serial.write(integer)

pyserial 是:

ser=serial.Serial ('com3',9600,timeout =1)
X=ser.read(1)
print(X)

但它除了空格不打印任何内容 有谁知道如何在 Python 中读取从 arduino 传递的这个整数?

【问题讨论】:

  • integer 取什么值?它的具体类型是什么?会不会是您传递的字节可能被解释为不可打印的 ASCII 或空格?

标签: python arduino pyserial


【解决方案1】:

您可能需要使用起始位。

问题可能是在 pyserial 运行时 arduino 已经写入了整数?

所以写一个字符从 pyserial 到 arduino 来表示开始像

    ser=serial.Serial ('com3',9600,timeout =1)
    ser.write(b'S')
    X=ser.read(1)
    print(X)

一旦你得到这个起始位,就从 arduino 中写入整数。

【讨论】:

    【解决方案2】:

    这不是从 Arduino 读取 Integer 的正确方法。 Integer 是 32 位类型,而您的串行端口将设置为 EIGHTBITS (在 pyserial 和 Arduino 中。如果我错了,请纠正我) 字节大小,因此您必须从 Arduino 编写 IntegerCharacter 版本,同时通过串行端口传输它,因为 Character 只需要 EIGHTBITS 大小,这也是方便的方法您需要的东西,非常容易。

    长话短说,在传输之前将您的Integer 转换为StringCharacter 数组。 (可能有可用于转换的内置函数)。

    附带说明,这里是您喜欢使用的正确 Python 代码:

    ser = serial.Serial(
            port='COM3',
            baudrate=9600,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS
        )
        #RxTx
        ser.isOpen()
    while 1:
        out = ''
        while ser.inWaiting() > 0:
            out += ser.read(1)
        if out != '':
            print ">>Received String: %s" % out
    

    【讨论】:

    • 甚至不需要检查设置顺便说一句,HardwareSerial::write() 的所有其他整数重载只需对uint8_t 进行 C 样式转换。
    • @IljaEverilä 我不知道 arduino 部分,因为我在 AT Mega AVR 中做过,我不知道你刚才说了什么。
    • @SiHa 已编辑,我尝试手动编写代码,应该只是复制了:)
    • @IljaEverilä 你的意思是说它们会自动转换为 utf-8 格式?
    【解决方案3】:

    我测试过的简单程序:

    阿杜诺:

    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }
    
    void loop() {
      int f1=123;
      // print out the value you read:
      Serial.println(f1);
      delay(1000);    
    }
    

    Python:

    import serial
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = 'COM5'
    
    ser.open()
    while True:
      h1=ser.readline() 
      if h1:
        g3=int(h1); #if you want to convert to float you can use "float" instead of "int"
        g3=g3+5;
        print(g3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多