Search code examples
pythonserial-portuart

receive Data via UART with python


I'm trying to send and receive via UART with Python Data. The sending is working but the reading is still faulty. Could anyone please help?

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

and when I run it I am getting the following error:

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

Solution

  • Change:

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

    To:

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

    The return from ser.read() (and any file read) is a string. %x expects an integer. ord(r) converts a character to its integer value.

    Read the documentation here https://docs.python.org/3.5/library/functions.html#ord