使用python通过UART接收数据

时间:2019-08-18 11:06:10

标签: python serial-port uart

我正在尝试通过UART使用Python数据发送和接收。发送正常,但读数仍然有问题。谁能帮忙吗?

import time, os, re, urllib
import msvcrt
import sys     
import serial
import struct

port="COM38"
def getAndSend1(test,type):
    global port
    if type=='int' :
            value=int(test)                    ##casting string to int
            ba=bytearray(struct.pack("i",value))
    elif type=='float' :
            value=float(test)                    ##casting string to float
            ba=bytearray(struct.pack("f",value))
    else:
            print("undefined type")
            return 0

    ba= b'\x7E\x7E'+ba+b'\x01\x01'                  ##adding header and tail to the byte array

    print("sent: "+str([ "0x%02x" % b for b in ba]))              ##print the packet before sending it

    ser = serial.Serial(port, 115200)            ##open serial port
    while ser.isOpen()==0:                          ##waiting till port get open
            1==1
    time.sleep(2)

    ser.write(ba)                                   ##sending the packet
        result = ser.read(8)                    ##reading the serial port
        print("recieved: "+str([ "0x%02x" % r for r in result]))
        resVal=struct.unpack("f",result[2:6]);
        print(str(resVal[0])+"\n")

getAndSend1(1,'int')

当我运行它时,出现以下错误:

sent: ['0x7e', '0x7e', '0x01', '0x00', '0x00', '0x00', '0x01', '0x01']

   Traceback (most recent call last):
     File "C:\Users\User\Desktop\V4(1).py", line 35, in <module>
       getAndSend1(1,'int')
      File "C:\Users\User\Desktop\V4(1).py", line 31, in getAndSend1
       print("recieved: "+str([ "0x%02x" % r for r in result]))
    TypeError: %x format: a number is required, not str
>>> 

1 个答案:

答案 0 :(得分:0)

更改:

print("recieved: "+str([ "0x%02x" % r for r in result]))

收件人:

print("recieved: "+str([ "0x%02x" % ord(r) for r in result]))

ser.read()(以及任何读取的文件)的返回值是一个字符串。 %x需要一个整数。 ord(r)将字符转换为其整数值。

https://docs.python.org/3.5/library/functions.html#ord

中阅读文档