我正在尝试通过Pyserial lib从Arduino读取数据。我遇到了拒绝访问COM端口以读取数据的问题。
Python脚本是一个OpenCV程序,用于跟踪对象,它要求一个边界框,然后在相机流中跟踪此框。它还将在屏幕上输出连接到Arduino的红外传感器读取的距离。
我曾尝试清除Arduino代码并再次刷新,但这并没有帮助。我关闭了似乎曾经帮助过的串行监视器,但是由于某种原因它无法再次工作。
arduino代码为:
#include <SharpIR.h>
SharpIR DETECTORsensor( SharpIR::GP2Y0A21YK0F, A0 );
void setup()
{
Serial.begin( 9600 );
}
void loop()
{
int distance = DETECTORsensor.getDistance();
Serial.println( distance );
delay(500);
}
Python代码如下:
import cv2
import sys
import serial
if __name__ == '__main__' :
# Set up tracker.
tracker = cv2.TrackerMIL_create()
# Read video
video = cv2.VideoCapture(0)
# Exit if video not opened.
if not video.isOpened():
print ("Could not open video")
sys.exit()
# Read first frame.
ok, frame = video.read()
if not ok:
print ('Cannot read video file')
sys.exit()
#Define ROI
bbox = cv2.selectROI(frame, False)
# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)
while True:
# Read a new frame
ok, frame = video.read()
if not ok:
break
# Start timer, FPS only
timer = cv2.getTickCount()
# Update tracker
ok, bbox = tracker.update(frame)
# Calculate Frames per second (FPS)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);
#calculate Distance from Raspi
focallength = 480.20
knownwidth = 30.480 #Almost the same size as A4 paper
perwidth = bbox[2] #This is what will update every frame, unable to update for now
RaspiDist = (knownwidth*focallength)/perwidth
#Calculate distance from IR sensor
ser_data = serial.Serial("COM3",9600)
# Draw bounding box
if ok:
# Tracking success
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, (0,255,255), 2, 1)
else :
# Tracking failure
cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
#Display tracker type on frame
cv2.putText(frame, "MIL Tracker", (0,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,255,255), 2);
#Display FPS on frame
cv2.putText(frame, "FPS : " + str(int(fps)), (0,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,255,255), 2);
#Display Distance on frame
cv2.putText(frame, "RaspiDistance : " + str(int(RaspiDist))+" cms", (0,75), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,255,255), 2);
cv2.putText(frame, "IRDistance : " + str(int(ser_data)), (0,100), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,255,255), 2);
# Display result [2]
cv2.imshow("Tracking", frame)
# Exit if ESC pressed
k = cv2.waitKey(1) & 0xff
# Destroy all windows
cv2.destroyAllWindows()
错误是:
文件“ C:\ Users \ XXX \ Anaconda3 \ envs \ py36 \ lib \ site-packages \ serial \ serialwin32.py”,62行,处于打开状态引发SerialException(“无法打开端口{!r}:{!r}”。format(self.portstr,ctypes.WinError())]
SerialException:无法打开端口'COM3':PermissionError(13,“访问被拒绝。”,无,5)
with serial.Serial() as ser:
[loop here]
您还应该知道当前您的代码没有从串行连接中读取任何数据。为此,您必须使用read()
x = ser.read() # read one byte
s = ser.read(10) # read up to ten bytes (timeout)
我建议您首先创建一个小的脚本,该脚本可以读取IR数据,所以您知道这是可行的。该文档非常有帮助,请阅读here。
void setup()
{
Serial.begin(9600);
}
void loop()
{
int distance = 123;
Serial.println(distance);
delay(500);
}
和Python脚本
from serial import Serial
port = "COM3"
baudrate = 9600
with Serial(port=port, baudrate=baudrate, timeout=1) as port_serie:
if port_serie.isOpen():
port_serie.flush()
for i in range(20):
try:
ligne = port_serie.readline()
print(str(ligne))
except:
print("Exception")
port_serie.close()
此最小代码仅可运行20次迭代。我删除了while True
,因为我不喜欢调试的可能无限循环。如果脚本有效,则可以使用while
,包括所有视频内容和Arduino上的距离检测