如何使用 PySerial 将整数写入端口 [英] How to write integers to port using PySerial

查看:72
本文介绍了如何使用 PySerial 将整数写入端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PySerial 将数据写入第一个串行端口 COM1.

I am trying to write data to the first serial port, COM1, using PySerial.

import serial
ser = serial.Serial(0)
print (ser.name)
ser.baudrate = 56700
ser.write("abcdefg")
ser.close()

应该可以工作.但是,我需要不断发送 28 个字节的整数;在表格中

ought to work. However, I need to send 28 bytes of integers constantly; in the form

255 255 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000

循环,每个整数使用一个字节的数据.

on loop, with each integer using one byte of data.

尝试:

import serial
ser = serial.Serial(0)
print (ser.name)
ser.baudrate = 56700
while True:
    ser.write(255 255 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000)
ser.close()

引发语法错误.

如果write<,你如何将整数写入串行端口/code> 只发送字符串?如何确保每个数字都以 8 位发送?

How can you write integers to a serial port if write only sends strings? How can I ensure that each number is sent as 8-bits?

serial 类的文档很少,所以任何帮助将不胜感激.

There is very little in the documentation for the class serial, so any help will be appreciated.

推荐答案

首先,写 123 12 123 123 123 不是有效的 Python 语法.

First of all, writing 123 12 123 123 123 is not a valid Python syntax.

使用整数创建列表或元组:values = (1,2,3,4,5)

Create a list or a tuple with your integers: values = (1,2,3,4,5)

现在,我们需要将该数据转换为表示我们的值的二进制字符串.

Now, we need to convert that data into a binary string that represents our values.

这里我们是怎么做的

import struct

values = (1,2,3,4,5)

string = b''

for i in values:
    string += struct.pack('!B',i)

# Now send the string to the serial port

根据每个数字要使用多少字节,您需要对它们进行不同的打包.请参阅此处的文档:https://docs.python.org/3/library/struct.html

Depending on how many bytes you want to use per number, you need to pack them differently. See the documentation here: https://docs.python.org/3/library/struct.html

这篇关于如何使用 PySerial 将整数写入端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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