【发布时间】:2017-06-26 02:51:01
【问题描述】:
我正在 python 中测试这个简单的 arduino 代码,但它在 arduino 序列中工作,而不是在 python 中。 用户定义 LED 上的闪烁次数。 这适用于 arduino 串行监视器。但是当我在 python 中使用它时它不起作用。谁能帮忙? 谢谢
Arduino 代码:
int ledPin = 13; // select the pin for the LED
int val = 0; // variable to store the data from the serial port
void setup() {
pinMode(ledPin,OUTPUT); // declare the LED's pin as output
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect (USB)
}
establishContact();
}
void establishContact(){
while (Serial.available() <= 0){
val = Serial.parseInt();
Serial.flush();
// Serial.println("Est");
}
}
void loop () {
if (val>0) {
for(int i=0; i<val; i++) {
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin, LOW);
delay(150);
}
val=0;
}
}
Python 代码:
import serial
import time
ser = serial.Serial('/dev/tty.usbmodem1421', baudrate=9600,timeout =None)
def blinkLED(x):
ser.write(x)
return;
【问题讨论】:
-
你怎么知道它不起作用?预期产出和实际产出?你试过什么?
-
您的
python代码什么都不做,并且确实没有发生任何事情:似乎工作正常。 也许您在脚本中的某处错过了对blinkLED()的调用.. -
在python shell中我调用了那个函数..blinkLED('10'),让它闪烁10次。
-
@WhatsThePoint 当我在 python shell 中调用函数 blinkLED('10') 时,LED 不会闪烁 10 次。但在 arduino IDE 串行监视器中它工作得很好。当我输入 10 时,它会相应地闪烁
-
不在 PC 上,因此无法格式化代码。但是,blinkLED() 函数需要整数而不是字符串吗?
标签: python interface arduino pyserial