I am trying to control LEDs connected to Arduino from Python through serial communication. I am attaching both codes in Arduino and python. But I am not getting any response from LEDs when I run the code in Python, though I am not getting any errors. Maybe I am making some mistakes in the syntax?
import serial
import time
arduino=serial.Serial('COM3',250000,timeout=5.0)
m=[]
commands=open('1.txt','r')
lines=commands.readlines()
for line in lines:
m.append(line)
commands.close()
s=0
while s!=len(m):
m[s]=float(m[s])
s+=1
s=0
def delay():
x=0
y=0
while x!=y:
x+=1
while s!=len(m):
c=str(m[s])
if m[s]==1:
arduino.write(b'c')
time.sleep(2)
print('1on')
elif m[s]==-1:
arduino.write(b'c')
time.sleep(2)
print('1off')
delay()
elif m[s]==2:
arduino.write(b'c')
time.sleep(2)
print('2on')
elif m[s]==-2:
arduino.write(b'c')
time.sleep(2)
print('2off')
elif m[s]==3:
arduino.write(b'c')
time.sleep(2)
print('3on')
elif m[s]==-3:
arduino.write(b'c')
time.sleep(2)
print('3off')
s+=1
This is the code to control LEDs from Python in Arduino. Arduino code is below
int led1=2;
int led2=3;
int led3=4;
void setup()
{
Serial.begin(250000);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led3,OUTPUT);
}
void loop()
{
if(Serial.available())
{
int v=Serial.parseInt();
if(v==1)
{
digitalWrite(led1,HIGH);
delay(1000);
}
else if(v==-1)
{
digitalWrite(led1,LOW);
delay(1000);
}
else if(v==2)
{
digitalWrite(led2,HIGH);
delay(1000);
}
else if(v==-2)
{
digitalWrite(led2,LOW);
delay(1000);
}
else if(v==3)
{
digitalWrite(led3,HIGH);
delay(1000);
}
else if(v==-3)
{
digitalWrite(led3,LOW);
delay(1000);
}
}
}