我想通過串行通信控制從Python連接到Arduino的LED。我在Arduino和Python中附加了兩個代碼。但是當我使用Python運行代碼時,我沒有收到來自LED的響應,儘管我沒有收到任何錯誤。也許我在語法上犯了一些錯誤?Arduino和Python
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
這是在Arduino中控制Python的代碼。 Arduino的代碼如下
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);
}
}
}
是啊,應該發送的數據無論在變量c –