Reputation: 101
I tried to check if my OpenCV code is communicating with Arduino or not.
OpenCV code:
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 code:
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);
}
}
I get following 'detect' value:
'301
71
RECIEVED BACK: 'I received: 53\r\n'
299
301
301
302
302
301
303
300
306
72'
At detect=71, a signal is sent to Arduino, it returns a value, it works a bit after that, then all communication breaks down and I get the following errors:
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
Here is my original post: Serial comunication between opencv (python) and arduino
How to keep the communication open?
Upvotes: 1
Views: 3388
Reputation: 15513
Comment: I did not understand your question. Can you explain a bit
Your loop
should look like this, for instance:
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?
Move this lines of code outside the while ...
loop
ser = serial.Serial('COM1', 19200,timeout=5)
time.sleep(6)
print(ser)
Upvotes: 1