首页 > 解决方案 > 使用 python3 将 arduino 串行读数转换为树莓派上的浮点数或整数

问题描述

我的树莓派和我的arduino之间有串行连接。我可以将数据从arduino发送到pi,但是当我尝试将接收数据转换为intfloat时,我收到一条错误消息。

假设我尝试将数字35发送到pi,并尝试在python端转换它,我收到以下消息:

基数为 10 的 int() 的无效文字:''

当我尝试将其转换为浮动时,我收到以下消息:

无法将字符串转换为浮点数。

我在raspberry pi上使用Idle 3.5.3。我尝试了很多我在这个论坛上看到的东西:喜欢但似乎没有任何效果。有什么问题?strip()

Arduino代码:

void setup() {
  Serial.begin(9600);

}

void loop() {

  Serial.println(35);

  delay(5000);


}

蟒蛇代码:

#!/usr/bin/env python3
import time
import serial
from array import array
import csv

arduino = serial.Serial(
        port='/dev/ttyACM0',
        baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=1
)
arduino.flushInput()


print("test")

while 1:
       incoming = arduino.readline().decode('ascii').strip()
       float(incoming)
       print(incoming)

我希望强制转换为intfloat但我只收到错误消息

标签: python-3.xcastingarduinopyserial

解决方案


我知道了。

incoming = arduino.readline().decode('ascii')
    if not incoming is "":

            if int(incoming.strip()) == 1:
                    data.append(float(arduino.readline().decode('ascii').strip())/100)

推荐阅读