[英]Hanging python script with arduino. Need help simplifying things
好的,所以我想做的是使用一个python脚本打开一个LED,然后使用另一个python脚本关闭。 现在我面临的问题是我的python脚本必须保持挂起状态才能保持LED亮起。 我不知道如何从串行中读取内容,在保持LED亮起的同时关闭com。
“ g”是我从on python脚本发送的内容,“ h”将从off python脚本发送。
arduino:
void setup(){
Serial.begin(9600);
pinMode(13, OUTPUT);
Serial.write('g');
Serial.write('h');
}
void loop(){
if(Serial.read() == 'g' ){
digitalWrite(13, HIGH);
Serial.end();
}
if(Serial.read() == 'h' ){
digitalWrite(13, LOW);
Serial.end();
}
}
和蟒蛇
#! /usr/bin/python
## import the serial library
import serial
## Boolean variable that will represent
## whether or not the arduino is connected
connected = False
## open the serial port that your ardiono
## is connected to.
ser = serial.Serial("/dev/cu.wchusbserial1410", 9600)
## loop until the arduino is ready
while not connected:
serin = ser.read()
connected = True
ser.write("g")
while ser.read() == 'g':
ser.read()
## close the port
ser.close()
底部的while.ser.read()部分只是让我迷惑不解,想弄清楚自己需要什么,但到目前为止还没有这种运气。
提前致谢!
在python代码中,而不是使用此串行命令,只需使用print命令。 假设您想在串行端口上发送字符g,然后简单地写:
打印“ g”
它将被发送到串行端口。 在使用Arduino YUN时为我工作。
感谢您的反馈。 我使用了一种不同的方法,并认为共享代码是一个好主意,以防任何人有兴趣这样做。
蟒蛇:
import serial
import time
arduino = serial.Serial('/dev/tty.wchusbserial1410', 9600)
time.sleep(0.1) # wait
print("initialising")
arduino.write('off') # turns LED off
print("LED OFF")
time.sleep(0.1) # wait
arduino.close() # close serial
这是用于关闭灯的代码。 如果要打开它,则使用相同的步骤,但是创建另一个脚本,将arduino.write('off')替换为arduino.write('on')
和Arduino:
int led = 13; // Pin 13
void setup()
{
pinMode(led, OUTPUT); // Set pin 13 as digital out
// Start up serial connection
Serial.begin(9600);
Serial.flush();
}
void loop()
{
String input = "";
// Read any serial input
while (Serial.available() > 0)
{
input += (char) Serial.read(); // Read in one char at a time
delay(5); // Delay for 5 ms so the next char has time to be received
}
if (input == "on")
{
digitalWrite(led, HIGH); // on
}
else if (input == "off")
{
digitalWrite(led, LOW); // off
}
}
此脚本的一个问题是在串行coms关闭后,指示灯熄灭。 为了解决这个问题,我在接地和复位引脚之间使用了一个10uF电解电容,以保持串行端口打开。 (请注意:仅在对Arduino进行编程之后,才将其盖上。如果需要重新编程,请先将其拉出。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.