【问题标题】:receive Data via UART with python使用python通过UART接收数据
【发布时间】:2019-08-18 11:06:10
【问题描述】:

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

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

【问题讨论】:

    标签: python serial-port uart


    【解决方案1】:

    变化:

    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

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 2016-01-11
      • 2021-09-16
      • 2018-05-29
      • 2015-03-07
      • 2018-10-04
      相关资源
      最近更新 更多