python-3.x - 使用 python3 将 arduino 串行读数转换为树莓派上的浮点数或整数
问题描述
我的树莓派和我的arduino之间有串行连接。我可以将数据从arduino发送到pi,但是当我尝试将接收数据转换为int或float时,我收到一条错误消息。
假设我尝试将数字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)
我希望强制转换为int或float但我只收到错误消息
解决方案
我知道了。
incoming = arduino.readline().decode('ascii')
if not incoming is "":
if int(incoming.strip()) == 1:
data.append(float(arduino.readline().decode('ascii').strip())/100)
推荐阅读
- java - 确保所有线程更新 Java 映射中的单个条目
- javascript - 无法使用 Array.sort 在 JavaScript 中实现正确的排序
- mysql - rails - 我错误地运行了“rake db:drop”。我怎样才能恢复我的所有数据?
- amazon-web-services - AWS s3 将多个文件夹同步到不同的目的地
- macros - 如何检测应用程序何时在 Bluestacks 上崩溃
- java - 匿名 AsyncTask 中的构造函数,例如“new AsyncTask
()”? - c# - 如何从选中的列表框中检索数据并在 datagrideview 中显示数据?
- c# - OxyPlot - 光标
- r - 计算列表中每个 data.frame 中的行数
- shell - 如何使用if循环比较两个文件?