我正在尝试通过串行通信从 Python 控制连接到 Arduino 的 LED。我在 Arduino 和 python 中附加了这两个代码。但是当我在 Python 中运行代码时,我没有从 LED 得到任何响应,尽管我没有收到任何错误。也许我在语法上犯了一些错误?
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 控制 LED 的代码。 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);
}
}
}
最佳答案
我不懂 Python,但问题似乎如下:arduino.write(b'c')
。您继续发送“c”字符。它不应该发送 c 变量中的任何内容吗?
关于python - 阿杜诺和 python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34855146/