如何通过python使用arduino读取串行端口?
这是Python代码,现在是arduino代码如何通过python使用arduino读取串行端口?,python,serial-port,arduino-uno,Python,Serial Port,Arduino Uno,这是Python代码,现在是arduino代码 import serial ser= serial.Serial('com5',9600) while 1: Value_from_arduino = ser.readline() Zustand = float(Value_from_arduino) print(Zustand) if Zustand == 1: ser.write(0) print('off') elif Zustand == 0: ser.
import serial
ser= serial.Serial('com5',9600)
while 1:
Value_from_arduino = ser.readline()
Zustand = float(Value_from_arduino)
print(Zustand)
if Zustand == 1:
ser.write(0)
print('off')
elif Zustand == 0:
ser.write(1)
print(on)
我的问题是,当我运行python代码时,当他从我的arduino获得值0时,代码停止。
以下是python的报告:
char serialData;
int pin=12;
int pin2 = 5;
int Value;
void setup(){
pinMode(pin,OUTPUT);
pinMode(pin2,INPUT);
Serial.begin(9600);
}
void loop(){
Value = digitalRead(pin2);
Serial.println(Value);
delay(250);
while(Serial.available()){
serialData = Serial.read();
Serial.print(serialData);
if(serialData = '1'){
digitalWrite(pin,HIGH);
}
else if(serialData = '0'){
digitalWrite(pin,LOW);
}
}
}
Python立即停止,但他打开了LED。
如果Python得到0的值,指示灯应该亮起,但他只是结束运行。
如果值为0且值为1,则LED应亮起。您需要从串行端口解码串行字节 替换代码中的Zustand=行
Zustand = float(Value_from_Arduino)
ValueError: could not convert string to float: b'\x000\r\n'
请在这里查一下
如果编码效果不好,也可以尝试
Value_from_arduino = ser.readline()
Zustand = float(ser_bytes[0:len(Value_from_arduino )-2].decode("utf-8"))
导入结构
Zustand,=struct.unpack('最后我发现请替换这些代码行
步骤->读取、解码为字符串、带/n和/r、转换为浮点
请在这里查一下
希望这能起作用。谢谢您的快速回复。您的线路不起作用,无论如何您是对的。我可以解码值,但他只是给我值,忽略我的算法。是的,对不起,所以我的问题是,如果我解码我的值,那么我的代码不起作用。如果我使用浮点,那么我的代码起作用,向我的arduino发送信号,然后代码刚刚中断。您看到了什么错误?是否可以更新打印语句Traceback(最近一次调用上次):文件“C:/Users/Radiochemie/PycharmProjects/pythonProject/main.py”,第7行,在Zustand=float中(值来自于arduino.decode(“utf-8”))ValueError:无法将字符串转换为float:'\x001\r\n'此错误与float一起出现。如果我使用解码,则我的If函数不起作用回溯(上次最新调用):文件“C:/Users/Radiochemie/PycharmProjects/pythonProject/main.py”,第9行,在Zustand=float中(值\u来自\u arduino)ValueError:无法将字符串转换为浮点:'\x000'您有Instagram吗?您能做最后一件事,在arduino代码中替换arduino代码serial.write而不是serial.print吗?
import struct
Zustand, = struct.unpack('<f',Value_from_arduino )
Value_from_arduino = ser.readline()
Value_from_arduino = Value_from_arduino.decode()
Value_from_arduino = Value_from_arduino.rstrip()
Zustand = float(Value_from_arduino)