来自python的arduino自动LED开/关信号

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (134)

下面的代码是python,如果我键入'1',它会打开我的LED,如果我输入'0'则关闭,如果我键入'0'这部分有效:

import serial
import time 

arduinoData = serial.Serial('com3',9600) 


while True:        
number = raw_input()

if (number == '1'):
    arduinoData.write('1')

if (number == '0'):
    arduinoData.write('0')

现在,以下内容包括随机化数字1和0,并希望自动LED开/关......但下一部分不起作用!

import serial
import time
import random

arduinoData = serial.Serial('com3',9600)     
while True:
    low = 0; high = 1
    ran_number = random.randint(low, high)
    print ran_number
    time.sleep(1)

    if (ran_number == '1'):
        arduinoData.write('1') 
        time.sleep(1)

    if (ran_number == '0'): 
        arduinoData.write('0')
        time.sleep(1)

arduino端代码是:

int data;
int pin=9;


void setup() { 
  pinMode(pin, OUTPUT); 
  digitalWrite (pin, LOW);
  Serial.begin(9600);
}

void loop() {
while (Serial.available()){
  data = Serial.read();
}

if (data == '1')
digitalWrite (pin, HIGH);

else if (data == '0')
digitalWrite (pin, LOW);

}
提问于
用户回答回答于

您正在生成一个int值,ran_number但之后您将其与str值进行比较。这肯定会false。你应该做的是ran_numberint值进行比较:

import serial
import time
import random

arduinoData = serial.Serial('com3',9600)     
while True:
    low = 0; high = 1
    ran_number = random.randint(low, high)
    print ran_number
    time.sleep(1)

    # please note the int here
    if (ran_number == 1):
        arduinoData.write('1') 
        time.sleep(1)

    # please note the int here
    if (ran_number == 0): 
        arduinoData.write('0')
        print ("LED turned OFF")
        time.sleep(1)

扫码关注云+社区

领取腾讯云代金券