I'm working on some code to read serial data from an Arduino. I'd like to wait for a serial data to come in, give an input in the terminal, then continue waiting for the next serial input or for the user to exit loop.
def assign_values(name, serial_connection):
print(f"Waiting for signal from {name}...")
try:
dict = {}
while True:
key = serial_connection.readline().decode("utf-8").strip()
if key and key not in dict:
value = input(f"Detected {key}: ")
dict[key] = value
except KeyboardInterrupt as k:
return dict
The above code works but has some problems that I'd like to clean up. First off, if I give multiple serial inputs before a user input, they get backed up. I'd rather it just ignore anything coming in while the user is typing their own input. The same problem also happens in reverse. Any user input is tracked while waiting for the serial data and immedietly populates the terminal when calling input()
. Also I feel like the try -> while True
isn't the best way to do this, but I can't find any other way to achieve my goal.
In case it is relevant, here is the Arduino code:
#include <IRremote.h>
#define IR_RECEIVE_PIN 7
void setup() {
Serial.begin(9600);
IrReceiver.begin(IR_RECEIVE_PIN);
}
void loop() {
if (IrReceiver.decode()) {
IrReceiver.resume();
int cmd = IrReceiver.decodedIRData.command;
Serial.println(cmd);
}
}