在 Python 3.3 中使用 pySerial

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16017288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:36:41  来源:igfitidea点击:

Using pySerial with Python 3.3

pythonpyserialpython-3.3

提问by P_Rein

I've seen many code samples using the serial port and people say they are working codes too. The thing is, when I try the code it doesn't work.

我已经看到许多使用串行端口的代码示例,人们说他们也在工作代码。问题是,当我尝试代码时,它不起作用。

import serial

ser = serial.Serial(
    port=0,
    baudrate=9600
    # parity=serial.PARITY_ODD,
    # stopbits=serial.STOPBITS_TWO,
    # bytesize=serial.SEVENBITS
)

ser.open()
ser.isOpen()

print(ser.write(0xAA))

The error it gives me is : "SerialException: Port is already opened". Is it me using python3.3 the problem or is there something additional I need to instal ? Is there any other way to use COM ports with Python3.3 ?

它给我的错误是:“SerialException:端口已打开”。是我使用 python3.3 的问题还是我需要安装一些额外的东西?有没有其他方法可以在 Python3.3 中使用 COM 端口?

采纳答案by P_Rein

So the moral of the story is.. the port is opened when initialized. ser.open()fails because the serial port is already opened by the ser = serial.Serial(.....). And that is one thing.

所以这个故事的寓意是..端口在初始化时打开。ser.open()失败,因为串口已经被ser = serial.Serial(.....). 这是一回事。

The other problem up there is ser.write(0xAA)- I expected this to mean "send one byte 0xAA", what it actually did was send 170(0xAA) zeros. In function write, I saw the following : data = bytes(data)where data is the argument you pass. it seems the function bytes() doesn't take strings as arguments so one cannot send strings directly with: serial.write(), but ser.write(bytearray(TheString,'ascii'))does the job.

另一个问题是ser.write(0xAA)- 我预计这意味着“发送一个字节 0xAA”,它实际上做的是发送 170(0xAA) 个零。在函数中write,我看到了以下内容: data = bytes(data)其中 data 是您传递的参数。似乎函数 bytes() 不接受字符串作为参数,因此不能直接使用: 发送字符串serial.write(),但可以ser.write(bytearray(TheString,'ascii'))完成这项工作。

Although I am considering adding:

虽然我正在考虑添加:

if(type(data) == type('String')):
    data = bytearray(data,'ascii')

in ser.write(), although that would make my code not work on other PCs.

in ser.write(),尽管这会使我的代码无法在其他 PC 上运行。