问题使用Arduino串行结合python



我试图让我的python代码从我的arduino串行连接读取,我得到这个错误消息。

File "C:UsersIRONSERVITORPycharmProjectsMore pygame 231122venvlibsite-packagesserialserialwin32.py", line 64, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': PermissionError(13, 'Access is denied.', None, 5)
我的arduino代码:
#include <ezButton.h>
#define VRX_PIN  A0 // Arduino pin connected to VRX pin
#define VRY_PIN  A1 // Arduino pin connected to VRY pin
#define SW_PIN   2  // Arduino pin connected to SW  pin
ezButton button(SW_PIN);
int xVal = 0; // To store value of the X axis
int yVal = 0; // To store value of the Y axis
int bVal = 0; // To store value of the button
void setup() {
Serial.begin(9600) ;
button.setDebounceTime(50); // set debounce time to 50 milliseconds
}
void loop() {
// reading the analog X and Y analog values
xVal = analogRead(VRX_PIN);
yVal = analogRead(VRY_PIN);
// Read the button value
bVal = button.getState();

// print data to Serial
if (xVal == 1023){
Serial.println(" ");
Serial.print('1');
delay(100);
}
if (xVal == 0){
Serial.println(" ");
Serial.print("2");
delay(100);
}
if (yVal == 1023){
Serial.println(" ");
Serial.print("down ");
}
if (yVal == 0){
Serial.println(" ");
Serial.print("up ");
}
if (bVal == 0){
Serial.println(" ");
Serial.print("hide ");
}
}

My python code

import serial

ard = serial.Serial(port='COM4', baudrate=9600, timeout=0.1)
while True:
command = ard.read()
if command:
ard.flushInput()
if str(command) == '1':
print('right')
elif str(command) == '2':
print('left')
ard.close()

每段代码都是独立工作的,只有当我同时使用它们时才会有问题。

问题是有if命令== 1,正确的版本是if命令== b'1':

最新更新