我正在研究对象跟踪机器人。我正在使用python和OpenCV来检测对象并将正确的数据发送到控制两个伺服电机的arduino。 应当发送到arduino的数据是伺服电机角度在0-180之间。我正在使用示例代码来了解python和arduino如何使用串行总线进行通信。当我发送一个数字时,arduino会接收它并按预期工作,但是当我发送一个以上的数字时则什么也没有发生。 这是arduino代码:
#include <Servo.h>
int data;
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
Serial.begin(9600); //initialize serial COM at 9600 baudrate
pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
digitalWrite (LED_BUILTIN, LOW);
myservo.attach(9);
Serial.println("Hi!, I am Arduino");
}
void loop() {
while (Serial.available()){
//to receive more than one character
char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
while (!Serial.available()); // Wait for characters
Serial.readBytesUntil('n', buffer, 7);
data = atoi(buffer);
}
myservo.write(data);
}
这是python代码:
import serial
import time # Required to use delay functions
arduinoSerialData = serial.Serial('com14', 9600) # Create Serial port
object called arduinoSerialData
time.sleep(2) # wait for 2 secounds for the communication to get
established
print arduinoSerialData.readline() # read the serial data and print it as
line
print ("Enter 1 to turn ON LED and 0 to turn OFF LED")
while 1: # Do this forever
var = raw_input() # get input from user
print "you entered", var # print the intput for confirmation
arduinoSerialData.write(var)
答案 0 :(得分:0)
'n'应该为'\ n'。
readBytesUntil()在一个字节后终止,因为串行缓冲区将为空。 如果您希望readBytesUntil()读取整个串行缓冲区,请添加Serial.setTimeout(),其默认值为1000毫秒以等待数据。这给了填充串行缓冲区的时间。 1秒钟不必要很长,但是readBytesUntil()将在找到'\ n'之后终止。
while(!Serial.available());可以删除。