我试图将数据从Arduino上的超声波测距仪传输到我的笔记本电脑上。我似乎遇到了从Arduino获取新值的问题。当我启动Python脚本时,它就像我希望的那样开始打印数据。但是,当我改变传感器看到的距离时,这些数据不会改变,它几乎就像serial.readline()
卡在第一个值之一上一样。我是这个串口通讯的新手,所以非常感谢任何帮助!
代码如下,为了理智,我确实检查了传感器是否正在使用Arduino IDE中的串行监视器。
import numpy
import serial
import time
import sys
import cv2
import pickle
#set up the camera stuff
cap = cv2.VideoCapture(0)
#container for images
images=[]
#container for distances
distances=[]
#first frame number
frame_num=1
#setup the serial connection and pause to establish it
ser = serial.Serial('/dev/cu.usbmodem1421', 9600,timeout=1)
time.sleep(5)
while True:
try:
#grab and image
ret,frame=cap.read()
#grab the distance
distance=ser.readline()
print(distance)
#process the image to a gray and 1241,376
#gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#gray_resized=cv2.resize(gray,(1241,376))
#cv2.imshow("FRAME",gray_resized)
#print(distance)
#images.append([frame_num,gray_resized])
#distances.append([frame_num,distance])
#ser.flush()
except KeyboardInterrupt:
#pickle.dump( images, open( "save.p", "wb" ) )
#pickle.dump( distances, open( "save.p", "wb" ) )
sys.exit()
Arduino代码:
// defines pins numbers
const int trigPin = 7;
const int echoPin = 8;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
delayMicroseconds(50);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance in CM
distance= duration*0.034/2;
String distance_out=String(distance);
// Prints the distance on the Serial Monitor in CM
Serial.println(distance);
Serial.flush();
//Serial.print("Distance: ");
//Serial.println(distance);
}
答案 0 :(得分:1)
实际上,python的serial.readline()
阻塞直到它获得EOL,所以如果你没有锁定问题意味着Arduino写入缓冲区的速度比你的python脚本读得快。
您应该在阅读后刷新缓冲区,以确保(接近)使用serial.flushInput()
或serial.reset_input_buffer()
进行实时阅读,具体取决于您的版本