0

Im trying to read the data from Arduino through Pyserial lib. Im encountering the issue where it denies access to the COM port to read the data.

The python script is an OpenCV program to track an object, it asks for a bounding box then tracks this box in the camera stream. It will also output to the screen the distance read by the IR sensor attached to Arduino.

Ive tried clearing the Arduino code and flashing it again, that didnt help. I closed the serial monitor that seemed to help once but it wont work again for some reason.

The arduino code is:

#include <SharpIR.h>
SharpIR DETECTORsensor( SharpIR::GP2Y0A21YK0F, A0 );

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

void loop()
{
  int distance = DETECTORsensor.getDistance(); 
  Serial.println( distance );
  delay(500);
}

The Python code is as follows:

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()

The Error is :

File "C:\Users\XXX\Anaconda3\envs\py36\lib\site-packages\serial\serialwin32.py", line 62, in open raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))

SerialException: could not open port 'COM3': PermissionError(13, 'Access is denied.', None, 5)

3
  • Maybe you should try to create a minimal example to help us to see more clearly. For example I am not sure that the video or cv2 parts of the code are of any interest in the issue
    – Romain F
    Oct 30, 2019 at 17:26
  • thank you for the idea @RomainF , I did try a minimal example as you suggested however the port still disconnects after the first turn and the output at the python script is different from the output at the serial monitor. ` import serial ser = serial.Serial("COM3", 9600) data = ser.read() print(data)` This outputs b + some random value Oct 31, 2019 at 14:12
  • Edit: the output is simply a string of various EOL characters and other stuff serial monitor attaches to its display values, that issue is solved. However, the issue with only being able to read once persists, even when tested on a minimal example. Oct 31, 2019 at 14:29

2 Answers 2

1

I suspect it is because you have ser_data = serial.Serial("COM3",9600) inside your main loop. That means on on the second loop it will try to open a connection that is already in use. So it get's denied. You should move that line out of the main loop and properly close it when the script ends.

Alternatively you can use

with serial.Serial() as ser:
    [loop here]

You should also know that currently your code isn't reading any data from the serial connection. To do that you have to use read()

x = ser.read()          # read one byte
s = ser.read(10)        # read up to ten bytes (timeout)

I would advice to first create a small script that can read the IR data, so you know that works. The documentation is very helpfull, read it here.

3
  • Thank you very much for pointing that out J.D., but the issue still persists where I cant read the value more than once and the one time it does read, the output is something completely different comapred to the output in the serial monitor. Oct 31, 2019 at 14:12
  • Edit: the output is simply a string of various EOL characters and other stuff serial monitor attaches to its display values, that issue is solved. However, the issue with only being able to read once persists, even when tested on a minimal example. Oct 31, 2019 at 14:30
  • Yes J.D. I can only read once and then the next time I run the simple script, the error pops up. The only way I can run it again is to disconnect the Arduino and reconnect it, then run the minimal code(simple 4 line code I mentioned in the comment above). Oct 31, 2019 at 16:27
1

Here is a minimal code you might use to test your serial ports. The Arduino code

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

void loop()
{
  int distance = 123;
  Serial.println(distance);
  delay(500);
}

And the Python script

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()

This minimal code runs on 20 iterations only. I removed the while True because I dislike possible infinite loops for debugging. If the script works you can then use the while, include all your video stuff and your distance detection on Arduino

1
  • Thank you Romain, I will try it out this example. Nov 1, 2019 at 12:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.