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

时间:2018-07-14 10:25:12

标签: python arduino-uno

以下代码是python,如果我输入“ 1”,它会打开我的LED;如果我输入“ 0”,它会关闭我的LED:

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);

}

1 个答案:

答案 0 :(得分:1)

您正在为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)