在 Python 3.3 中使用 pySerial [英] Using pySerial with Python 3.3

查看:64
本文介绍了在 Python 3.3 中使用 pySerial的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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))

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

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 ?

推荐答案

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

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.write(0xAA) - 我希望这意味着发送一个字节 0xAA",它实际上做的是发送 170(0xAA) 个零.在函数 write 中,我看到了以下内容:data = bytes(data) 其中 data 是您传递的参数.似乎函数 bytes() 不接受字符串作为参数,因此不能直接使用以下命令发送字符串:serial.write(),但是 ser.write(bytearray(TheString,'ascii'))) 完成这项工作.

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.

虽然我正在考虑添加:

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

ser.write() 中,虽然这会使我的代码无法在其他 PC 上运行.

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

这篇关于在 Python 3.3 中使用 pySerial的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆