简体   繁体   English

Python pyserial变量

[英]Python pyserial variable

I am sending one byte ("\\x2b") to a device and will be receiving 1 echo byte plus 3 bytes of data("\\x2b\\x??\\x??\\x??").I am using .replace("2b","",4) to get rid of the echo byte.I need to change the 3 bytes of hex received to int(16) and name them 3 different variables that I can call separately one at a time in a calculation. 我正在向设备发送一个字节(“ \\ x2b”),并且将接收1个回显字节和3个字节的数据(“ \\ x2b \\ x ?? \\ x ?? \\ x ??”)。我正在使用.replace (“ 2b”,“”,4)来摆脱回显字节。我需要将收到的十六进制的3个字节更改为int(16),并将它们命名为3个不同的变量,我可以一次在一个变量中分别调用它们计算。 Here is what I have so far. 这是我到目前为止所拥有的。

    import serial
    import os

    ser = serial.Serial(port="COM17", baudrate=9600)
    ser.open()
    ser.write("\x2b")
    print int(ser.readline(4).encode("hex").replace("2b", "", 4), 16)
    ser.close()

    os.system("pause")

Use the struct module to retrieve arbitrary binary data from Byte strings: 使用struct模块从Byte字符串中检索任意二进制数据:

import serial
import os
import struct

ser = serial.Serial(port="COM17", baudrate=9600)
ser.open()
ser.write("\x2b")
response = ser.readline(4)
echo, a, b, c = struct.unpack("4B", response)
print ("Response numbers: {:02x}, {:02x}, {:02x}".format(a, b, c))
ser.close()

On a side note: avoid using os.system("pause") as part of the program. 附带说明:避免在程序中使用os.system("pause") That is a terrible habit of some so that the Windows DOS prompt stays open when the program is done running, but it is (1) WIndows only, for a program that otherwise would work on Mac OS X and Linux, and (2) involves creating an entire other process for an ordinary operation. 这是一种可怕的习惯,因此当程序完成运行时,Windows DOS提示符仍然保持打开状态,但是(1)仅Windows,对于在Mac OS X和Linux上可以运行的程序,以及(2)涉及为普通操作创建整个其他过程。

You can add a simple input call in Python, asking the user to press <enter> instead: 您可以在Python中添加一个简单的input调用,要求用户按<enter>代替:

(last line): (最后一行):

 input("Press <enter> to close terminal")

There is no "natural" conversion to convert a stream of 3 bytes into 3(?) int16 (aka short ) numbers. 没有将3个字节的流转换为3(?) int16 (也称为short )数字的“自然”转换。

So you have to be more specific: 因此,您必须更具体:

  • do you want to convert the bytes to int8 instead? 您想将字节转换为int8吗? it is of course entirely valid to regard the resulting numbers as int16 (as they will fit in) 将结果数字视为int16当然是完全有效的(因为它们将适合)
  • do you want signed/unsigned output? 您是否需要签名/未签名的输出?
  • if you indeed have multibyte numbers (eg int16 ), are you using BIG_ENDIAN or LITTLE_ENDIAN? 如果您确实有多字节数字(例如int16 ),那么您正在使用BIG_ENDIAN还是LITTLE_ENDIAN?

in any case, the struct package can do the conversion for you: 在任何情况下, struct包都可以为您完成转换:

import struct

# read 4 bytes, discard the first one, so we get a list of 3 bytes
inputdata = ser.readline(4)[1:]

# the following parses 'inputdata' as 3 `uint8` numbers
a,b,c = struct.unpack('BBB', inputdata)

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

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