[Python] denied access to com port 5

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write a python script that receives serial input from an Arduino (with servo and ultrasonic sensor) on com5 to plot a radar like graph. I have done everything I have found on forums making sure (the best I can) that nothing else like Arduino IDE is using the port (the serial monitor is closed) I've tried running it as administrator, I have restarted the computer. I have unistalled and reinstalled pyserial.

    No Matter what i get this error:

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


    My Python code is:

    from matplotlib import pyplot as plt
    import matplotlib
    matplotlib.use('TkAgg')
    import numpy as np
    import time
    import serial
    import keyboard

    ser = serial.Serial('COM5', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2)

    # setup the basic display window
    fig = plt.figure(facecolor='k')
    fig.canvas.toolbar.pack_forget()
    fig.canvas.manager.set_window_title('Radar')
    mng = plt.get_current_fig_manager()
    mng.window.state('zoomed')

    #setup the sub plot (the radar screen)
    ax = fig.add_subplot(1,1,1, polar=True, facecolor='green')
    ax.tick_params(axis='both', colors='white' )
    ax.xaxis.grid(True, color='grey', linestyle='--')
    ax.yaxis.grid(True, color='grey', linestyle='--')
    rmax = 100
    ax.set_ylim([0.0, rmax])
    ax.set_xlim([0.0, np.pi])
    ax.set_position([0.1, 0.1, 0.8, 0.8 ])
    ax.set_rticks(np.linspace(0.0, rmax, 5))
    ax.set_rlabel_position(0)
    ax.set_thetagrids(np.linspace(0.0, 360, 17))

    angles = np.arange(0, 360, 1)

    #convert angles to radians
    theta = angles * (np.pi / 180)

    pols = ax.plot([], linestyle='', marker='o', markerfacecolor='r', markeredgecolor='w',
    markeredgewidth=1.0, markersize=3.0, alpha=0.5)
    line1 = ax.plot([], color='w', linewidth=3.0)

    fig.canvas.draw()
    dists = np.ones((len(angles),))
    axbbackground = fig.canvas.copy_from_bbox(ax.bbox)

    while True:

    try:
    data = ser.readline()
    decoded = data.decode()
    data = (decoded.replace('\r','')).replace('\n','')
    #split data values (one distance, one angle) where there is a comma
    vals = [float(ii) for ii in data.split(',')]
    #check that there is in fact 2 values and it doesnt try plot an incomplete graph
    if len(vals) < 2:
    continue
    angle, dist = vals
    # can test working by adding
    #print(angle, dist)

    #Create all angles into a list to plot all at once
    dists[int(angle)] = dist

    pols.set_data(theta, dists)
    #plot background
    fig.canvas.restore_region(axbbackground)
    ax.draw_artist(pols)

    #create sweeping line
    line1.set_data(np.repeat((angle*(np.pi/180)), 2),np.linspace(0.0, r_max, 2))
    ax.draw_artist(line1)
    fig.canvas.blit(ax.bbox)
    fig.canvas.flush_events()

    if keyboard.is_pressed('q'):
    plt.close('all')
    print('User to quit the application')
    break

    except KeyboardInterrupt:
    plt.close('all')
    ser.close() # Always close the port after usage
    print("Keyboard interrupt")
    break

    exit



    My Arduino code is:

    #include <Servo.h>

    Servo micro_servo;

    int pos = 0;

    const int servo_pin = 7;
    const int trig_echo_pin = 3;

    float duration, distance;

    void setup() {
    pinMode (servo_pin, OUTPUT);
    pinMode (trig_echo_pin, OUTPUT);
    Serial.begin(9600);
    micro_servo.attach(servo_pin);
    }

    void loop() {
    // Sweep the servo from 0 to 180 degrees
    for (pos = 0; pos <= 180; pos++)
    {
    micro_servo.write(pos);
    delay(50);
    read_ultrasonic_distance(pos);
    }
    // Sweep the servo back from 180 to 0 degrees
    for (pos = 180;pos>=180; pos--)
    {
    micro_servo.write(pos);
    delay(50);
    read_ultrasonic_distance(pos);
    }
    delay(200);
    }

    void read_ultrasonic_distance(int angle)
    {
    pinMode(trig_echo_pin, OUTPUT);
    digitalWrite(trig_echo_pin, LOW);
    delayMicroseconds(2);
    digitalWrite(trig_echo_pin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig_echo_pin, LOW);

    // Set the pin to input mode to receive the echo
    pinMode(trig_echo_pin, INPUT);
    duration = pulseIn(trig_echo_pin, HIGH); // Measure the duration of the echo pulse

    // Calculate the distance based on the duration
    distance = (duration * 0.0343) / 2;

    // Send the angle and distance to the Python program via serial
    Serial.print(angle);
    Serial.print(",");
    Serial.println(distance);
    }

    Continue reading...

Compartilhe esta Página