I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.
Should be pretty basic but I cant seem to get this working.
I have already botched my code trying to get this running:
the jist of my python script is
import serial
import os
import time
os.system('clear')
ser = serial.Serial('/dev/cu.usbmodem1431', 9600)
while True:
led = input("Which LED do you wish to operate? (press x to quit): ")
if led >= '0' and led <= '7':
print("Operating LED # %s" % led)
ser.write(str.encode(led)) # sends the choice of led to arduino'
on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")
if on_or_off == '0':
#send command to arduino to turn off the selected LED
print("Command sent to arduino to turn OFF LED %s" % led)
ser.write(str.encode(on_or_off))
elif on_or_off == '1':
#send command to arduino to turn on the selected LED
print("Command sent to arduino to turn ON LED %s" % led)
ser.write(str.encode(on_or_off))
else:
print("Please enter 0 or 1 to operate the LED. ")
elif led == 'x':
ser.close()
break
else:
continue
For some reason Arduino is only dealing with the first input...
HEre is my loop code on the arduino
void loop() {
if(Serial.available() > 0){
led = Serial.read(); // from python script the led to operate
led = led - '0';
if(led >= '0' && led <= '7'){
if(Serial.available() > 0){
ledState = Serial.read(); // expects the led state next
ledState = ledState - '0';
if(ledState == '0'){
shiftWrite(led,LOW);
}else if(ledState == '1'){
shiftWrite(led,HIGH);
}
}
}
}
}
shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister
update:
I tried the state machine suggestion and it didnt work...
void loop() {
while(Serial.available()){
led = Serial.read();
led = led - '0';
if(led>= 0 && led <= 7){
state = 1; //We've received the LED # go to state 1
Serial.println(led);
Serial.println(state);
Serial.println(ledState);
continue;
}
if(state == 1){
ledState = Serial.read();
ledState = ledState - '0';
if(ledState == '0'){
shiftWrite(led,LOW);
}else if(ledState == '1'){
shiftWrite(led,HIGH);
}
state = 0; //Ended the operation return to state 0
}
}
}
With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1
This is my output on the serial monitor:
4
1
0
1
1
0
Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...
if(ledState == 0)
not'0'
. same for'1'
No Line Ending
. There is nothing wrong with the code, it's just the Serial Monitor, when you press Enter, it sends another character which makes the loop go crazy.