1

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?

4
  • 1
    Please fix your indentation. Where do you send a signal to the Arduino, and where does it get back a value? The line serial.Serial('COM1', 19200,timeout=5) creates a port object but doesn't send or receive anything. Commented May 8, 2017 at 20:01
  • You keep opening the serial but never close it. Why not just open it at start. Commented May 8, 2017 at 20:26
  • I have edited my post. Sorry for the miscommunication. @PaulCornelius Commented May 9, 2017 at 17:40
  • Seems moving ser port out of while loop did the trick! thanks @gre_gor Commented May 9, 2017 at 17:47

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

The port keeps open until you call ser.close(). What gives print(ser.is_open) inside if 0<detect<100?
I did not understand your question. Can you explain a bit?
why do I need (ser.is_open)? I am new to this.
@sayem48: You don't need it. It's only for tracing your code. It seems we have overlapped comunication. Does it work now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.