python - 阿杜诺和 python

标签 python arduino

我正在尝试通过串行通信从 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/

相关文章:

python - 如何用纯 Python 从 PDF 中提取图像?

python - 使用 python 2.7 构建 Conda noarch 包

c - Arduino 处理开放网络套接字

tcp - Arduino + ESP8266,如何发送连续获取请求?

c++ - 数组损坏其字符 C++

python - 使用 pythonplotly 绘制动画线图

python - 当只有某些变量需要多个值时,如何将多个值传递给函数 - python 3

c++ - Arduino 中带有构造函数的对象组合

c - 转换为C代码时如何导入.h文件?

python - 错误 : The truth value of a Series is ambiguous