gpt4 book ai didi

python - Python(OpenCV)与Arduino之间的串行通信结束

转载 作者:行者123 更新时间:2023-12-02 17:41:41 26 4
gpt4 key购买 nike

我试图检查我的OpenCV代码是否与Arduino通信。

OpenCV代码:

import numpy as np
import cv2
import serial
import time
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
detect=x
print(detect)

cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff

if 0 < detect < 100:
ser = serial.Serial("COM1", 19200, timeout=5)
time.sleep(2)
ser.write("\x35")
print "RECIEVED BACK:", repr(ser.read(5000))

if k == 27:
break

Arduino代码:
int incomingByte = 0;   // for incoming serial data

void setup() {
Serial.begin(19200);
}

void loop() {

// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();

// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}

我得到以下“检测”值:
'301
71
RECIEVED BACK: 'I received: 53\r\n'
299
301
301
302
302
301
303
300
306
72'

在detect = 71处,一个信号被发送到Arduino,它返回一个值,此后它会工作一点,然后所有通信中断,并且出现以下错误:
Traceback (most recent call last):
File "C:/Users/khan1/Desktop/python
project/tennis_ball_vid/tennis_vid.py", line 40, in <module>
ser = serial.Serial('COM1', 19200,timeout=5)
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 38, in
__init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\serial\serialutil.py", line 282, in
__init__
self.open()
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in
open
raise SerialException("could not open port %r: %r" % (self.portstr,
ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM1':
WindowsError(5, 'Access is denied.')

Process finished with exit code 1

这是我的原始帖子:
Serial comunication between opencv (python) and arduino

如何保持沟通畅通?

最佳答案

Comment: I did not understand your question. Can you explain a bit



您的 loop应该看起来像这样,例如:
ser = serial.Serial("COM1", 19200, timeout=5)
time.sleep(2)
while True:
ret, img = cap.read()
# ... img processing

for (x, y, w, h) in faces:
# ... faces processing

if 0 < detect < 100:
print('ser.is_open=%s' % ser.is_open() )
ser.write("\x35")
print("RECIEVED BACK:", repr(ser.read(5000)) )

Question: How to keep the communication open?



将这行代码移到 while ...循环之外
ser = serial.Serial('COM1', 19200,timeout=5)
time.sleep(6)
print(ser)

关于python - Python(OpenCV)与Arduino之间的串行通信结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com