我正在研究python通过USB向Arduino Mega发送电机命令的项目。我一直在玩几种变体,如何使代码健壮,以便python程序等待,直到arduino准备好接收。这是该问题的超级基本版本。
有问题的是,arduino println正在成功发送值,以便在arduino IDE的串行监视器中读取。但是python没有成功读取它以将值打印到命令行。
我的python读取代码出了什么问题?
Arduino的
//++++++++++++++++++++Initializations+++++++++++++++++++++
int command = 0;
int control = 0;
boolean newInput = 0;
int myCount = 0;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void setup() {
Serial.begin(9600); // set the baud rate
Serial.println(1); // initial "ready" signal
}
void loop() {
// read sent command and return it
if(Serial.available() > 0){ // only send data back if data has been sent
command = Serial.read();
delay(10);
Serial.println(1); // send "ready" signal
delay (50); //alternatively Serial.flush();
myCount++;
}
}
以下是我的计划的精简版,突出了这个问题。
的Python
import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1)
import time
controlBit = True
n = 0
charsWait = 0 #chars waiting from arduino
print "Starting up"
connected = False
while True:
n = n+1
print n
print "Writing"
ser.write(str(2))
time.sleep(1)
while True:
try:
print "reading"
charsWait = ser.readline()
time.sleep(1)
print " = value recieved", charsWait
break
except:
pass
print "restart"
ser.flush() #flush the buffer
答案 0 :(得分:0)
<pre>Arduino code:
//++++++++++++++++++++Initializations+++++++++++++++++++++
int command = 0;
int control = 0;
boolean newInput = 0;
int myCount = 0;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void setup() {
Serial.begin(9600); # set the baud rate
Serial.println("1"); # initial "ready" signal
}
void loop()
{
# read sent command and return it
if(Serial.available() > 0)
{
command = Serial.read();
Serial.println(command);
}
}
#Python Code for is waiting for Arduino listening state.
import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1)
import time
controlBit = True
n = 0
charsWait = 0 #chars waiting from Arduino
print "Starting up"
connected = False
while True:
charsWait = ser.read() #ser.read data in ASCII
print " = value recieved", charsWait
if charsWait == 49: #ASCII of 1=49**strong text**
while True:
ser.write("As per you")
#表示当 Arduino 设置运行时(Arduino 初始化时间),当 Arduino 发送“1”时,python 正在等待在 1 之后接收“1”,他们可以工作。