Python Serial: How to use the read or readline function to read more than 1 character at a time

前端 未结 4 564
谎友^
谎友^ 2020-12-14 08:00

I\'m having trouble to read more than one character using my program, I can\'t seem to figure out what went wrong with my program.

import serial

ser = seria         


        
4条回答
  •  醉梦人生
    2020-12-14 08:50

    I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:

    import serial
    import time
    
    ser = serial.Serial(
        port='COM4',\
        baudrate=9600,\
        parity=serial.PARITY_NONE,\
        stopbits=serial.STOPBITS_ONE,\
        bytesize=serial.EIGHTBITS,\
            timeout=0)
    
    print("connected to: " + ser.portstr)
    
    #this will store the line
    seq = []
    count = 1
    
    while True:
        for c in ser.read():
            seq.append(chr(c)) #convert from ANSII
            joined_seq = ''.join(str(v) for v in seq) #Make a string from array
    
            if chr(c) == '\n':
                print("Line " + str(count) + ': ' + joined_seq)
                seq = []
                count += 1
                break
    
    
    ser.close()
    

提交回复
热议问题