简体   繁体   中英

serial port interfacing in python

i have written a code in which i need to receive 3 bytes of code in which a receive a 2`s Complement Number of 24bits and i process the number , i am trying to receive the same in a list and try to initialise it after receiving a set of data here is the code i have written for the above

Received_Data=[] --- initialising the list 
while cnt<=18:    
  input_data = ser.read(3)
  Received_Data.append(input_data.encode("hex"))
  cnt = cnt+1
  cnt=0

after this my code continues for processing the 2`s complement received now the problem here is the if there is no data received the code should not come out the line input_data = ser.read(3) could anybody throw some light on the same if i have done it correctly or is there any other better way to code

You don't know how much data you will get from the port. Sometimes there will be data, but maybe more or less than exactly 3 bytes. I also don't quite understand your question, but I assume you don't want to process any commands until you get them, correct? And you want to get 18 commands of 3 bytes each stored in the list? Then may I suggest something like this?

received_data = [] --- initialising the list
cnt = 0
inbytes = ""
while cnt <= 18:
    while len(inbytes) < 3:
        inbytes += ser.read(3)
    while len(inbytes) >= 3:
        received_data.append(inbytes[:3].encode("hex"))
        inbytes = inbytes[3:]
        cnt += 1

I have not run this code myself, but I hope it helps you with the concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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