简体   繁体   English

从 Python+Pyserial 向 Arduino 发送串行数据时出错

[英]Error Sending Serial Data from Python+Pyserial to Arduino

For all this, I am using Windows 7, Python 2.7.3 and Pyserial 2.6.对于所有这些,我使用的是 Windows 7、Python 2.7.3 和 Pyserial 2.6。 I am using COM6 for my Arduino.我的 Arduino 使用 COM6。

I am trying to send data from a Python program, to the Arduino to read, and it keeps returning a "SerialException error.我试图将数据从 Python 程序发送到 Arduino 进行读取,但它不断返回“SerialException 错误。

Here is the Python code:这是Python代码:

import serial
import time
ser = serial.Serial('COM6', 9600, timeout=0)
var = raw_input("Enter something: ")
ser.write(var)
while 1:
    try:
        print ser.readline()
        time.sleep(1)
    except ser.SerialTimeoutException:
        print('Data could not be read')

Here is the Arduino code:这是Arduino代码:

int incomingByte = 0;

void setup(){
// Open serial connection.
Serial.begin(9600);

}

void loop(){
if (Serial.available() > 0) {
 // read the incoming byte:
 incomingByte = Serial.read();

 // say what you got:
 Serial.print("I got: "); // ASCII printable characters
 Serial.println(incomingByte, DEC);
}

}

Here is the error I am getting in Python when I run the script:这是我在运行脚本时在 Python 中遇到的错误:

Traceback (most recent call last):
  File "C:/Users/admin/Desktop/test", line 3, in <module>
    ser = serial.Serial('COM6', 9600, timeout=0)
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 34, in __init__
    SerialBase.__init__(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\serial\serialutil.py", line 261, in __init__
    self.open()
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 62, in open
    raise SerialException("could not open port %s: %s" % (self.portstr, ctypes.WinError()))
SerialException: could not open port COM6: [Error 5] Access is denied.

How can I resolve that error?我该如何解决该错误? Python will read from the Arduino just fine, but not write to it. Python 可以很好地从 Arduino 读取,但不会写入。

Besides ensuring that the port is closed, a couple of additional things to note...除了确保端口关闭之外,还有一些需要注意的事项......

  • Data sent using PySerial can only be of type byte (or bytestream for more than 1 byte data).使用 PySerial 发送的数据只能是byte类型(或超过 1 字节数据的bytestream )。 You can't send user input as it is.您不能按原样发送用户输入。

  • flush() the data after writing写入后刷新数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM