我无法让python与我的Arduino对话,每次我尝试初始化连接时,它都会给我这个错误消息:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 322, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM0'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
ser1 = serial.Serial('/dev/ttyACM0', 9600)
File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 244, in __init__
self.open()
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 325, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 16] could not open port /dev/ttyACM0: [Errno 16] Device or resource busy: '/dev/ttyACM0'
从这行开始:
ser1 = serial。串行("/dev/ttyACM0 9600)
消息提示错误发生在实际函数中。我不确定是什么导致了这个,所以我将显示我的代码:
Python:
import serial
import time
s = serial.Serial('/dev/ttyACM0', 9600)
s.close()
s.open()
time.sleep(5)
s.write("test")
try:
while True:
response = s.readline()
print (response)
except KeyboardInterrupt:
s.close()
Arduino:
void setup() {
Serial.begin(9600);
Serial.println("running");
}
void loop() {
if(Serial.available()){
byte recieved = Serial.read();
Serial.print("recieved:");
Serial.println(recieved, DEC);
}
}
我弄清楚了,我正在使用的树莓派在运行时打开一个端口到arduino:
s = serial。串行(/dev/ttyACM0, 9600)
因此,如果您在终止程序之前没有关闭端口,树莓派将把端口分类为打开,并且在关闭之前不让您与之交互,并且由于需要使用s.close()函数打开端口并返回错误,因此您只能通过重新启动pi来解决这个问题。
TLDR:在终止程序之前使用s.f close(),否则您将不得不重新启动系统