我試圖檢查我的OpenCV代碼是否與Arduino通信。Python(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'
在檢測= 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
如何保持通訊暢通?
請解決您的壓痕。你向Arduino發送信號的地方,它從哪裏獲得價值? 'serial.Serial('COM1',19200,timeout = 5)'行創建一個端口對象,但不發送或接收任何東西。 –
您不斷打開序列號,但從不關閉它。爲什麼不在開始時打開它。 –
我編輯了我的帖子。對不起,溝通不暢。 @PaulCornelius – sayem48