Я пытаюсь написать скрипт Python, который получает последовательный входной сигнал от Arduino (с сервоприводом и ультразвуковым датчиком) на com5, чтобы построить график, подобный радару. Я сделал все, что нашел на форумах, убедившись (насколько мог), что ничто иное, как Arduino IDE, не использует этот порт (последовательный монитор закрыт). Я попробовал запустить его от имени администратора и перезагрузил компьютер. Я удалил и переустановил pyserial.
Независимо от того, что я получаю эту ошибку:
serial.serialutil.SerialException: could not open port 'COM5': PermissionError(13, 'Access is denied.', None, 5)
Мой код Python:
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
Мой код Arduino:
#include
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);
}
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);
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... com-port-5
Запрещен доступ к com-порту 5 ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Невозможно подключиться к порту Arduino с помощью Visual Studio (Доступ к порту COM4 запрещен)
Anonymous » » в форуме C# - 0 Ответы
- 104 Просмотры
-
Последнее сообщение Anonymous
-