I use a RPi 3b to request and receive float values over serial from an Arduino Nano (fake). For that I use python and pyserial
.
Arduino Loop:
if (Serial.available() > 0) {
String req = Serial.readStringUntil('\n');
if (req == "co2") {
double adjustedCO2 = myMHZ19.getCO2Raw();
Serial.println(adjustedCO2, 2);}
else if (req == "hum") {
Serial.println(bme.humidity);}
}
RPi Request:
def read_data(command):
req = command + "\n"
ser.write(req.encode())
line = ser.readline(100).decode('utf-8').rstrip()
return float(line)
#main
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
ser.flush()
time.sleep(2) #time to open up the serial connection
co2 = read_data("co2")
humidity = read_data("hum")
It works well for some time, but after a while (days/hours) my read_data()
function returns only None
. A reboot helps but I want to avoid that.
What am I missing? Do I need some timeouts? Is there a way to reset my serial port without rebooting?