如何通过arduino通过python读取串行端口?

问题描述

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代码

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代码时,当他从arduino获取值0时,它停止了。 这是python的报告:

    Zustand = float(Value_from_Arduino)
ValueError: Could not convert string to float: b'\x000\r\n'

Python立即停止,但是他打开了LED。 如果Python的值为0,则LED应当亮起,如果确实如此,则LED才结束运行。 如果值为0或值为1,则LED应当点亮。

解决方法

您需要从串行端口解码串行字节。

在代码中替换Zustand =行

Value_from_arduino = ser.readline()
Zustand = float(ser_bytes[0:len(Value_from_arduino )-2].decode("utf-8"))

请在此处检查https://makersportal.com/blog/2018/2/25/python-datalogger-reading-the-serial-output-from-arduino-to-analyze-data-using-pyserial

如果编码效果不佳,也可以尝试

import struct
Zustand,= struct.unpack('<f',Value_from_arduino )
,

最后我发现请替换这些代码行

步骤->读取,解码为字符串,剥离/ n和/ r,转换为浮点 请在此处检查https://problemsolvingwithpython.com/11-Python-and-External-Hardware/11.04-Reading-a-Sensor-with-Python/

Value_from_arduino = ser.readline()
Value_from_arduino = Value_from_arduino.decode()
Value_from_arduino = Value_from_arduino.rstrip()
Zustand = float(Value_from_arduino)

希望这个作品..