Home:ALL Converter>Reading a serial port in python with unknown data length

Reading a serial port in python with unknown data length

Ask Time:2016-07-11T20:56:37         Author:raccess

Json Formatter

Hello I am trying to read data from a pic32 microcontroller configured as a serial port.

The pic32 sends "binary" data variable in length (14 to 26 bytes long). I want to read in the data and separate the bits then convert them to their decimal equivalent.

import serial
import csv

#open the configuartion file
with open('config.txt') as configFile:
   #save the config parameters to an array called parameters
   parameters = configFile.read().split()

#Function to Initialize the Serial Port
def init_serial():
    global ser
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = 'COM7'
    ser.timeout = 10
    ser.open()
    if ser.isOpen():
        print ('Open: ' + ser.portstr)

#call the serial initilization function
init_serial()

#writes the lines from the config file to the serial port
counter = 0
while counter<4:
    ser.write(chr(int(parameters[counter])).encode('utf-8') + chr(int(parameters[counter+1])).encode('utf-8'))
    counter = counter + 2

#opens the csv file to append to 
resultsFile = open('results.csv', 'wt')

#writes the titles of the four columns to the csv file
resultsFile.write("{} {} {} {}\n".format('ChannelAI', 'ChannelAQ', 'ChannelBI', 'ChannelBQ')) 


count=0
while count < 10:    

    #read from serial port
    incoming = ser.read(26)

    #decodes incoming bytes to a string
    incoming = incoming.decode('cp1252')


    #will select element 4, 5 & 6 from incoming data
    channelAIstr = incoming[4:6]
    #converts slected elements to an integer
    channelAI=int(channelAIstr, 16)

    channelAQstr = incoming[7:10]
    #channelAQ=int(channelAQstr, 16)

    channelBIstr = incoming[10:13]
    #channelBI=int(channelBIstr, 16)

    channelBQstr = incoming[13:16]
    #channelBQ=int(channelBQstr, 16)

    #writes to csv file
    resultsFile.write("{} {} {} {}\n".format(str(channelAI), str(channelAQ), str(channelBI), str(channelBQ)))             

    count = count + 1

#close the file to save memory
resultsFile.close()

I am having some trouble properly reading and converting the bits from the serial port. Any help on how to do this would be appreciated.

I know I am reading the serial port correctly and am getting data that looks something like this "\x00\x7f\x7f" as an example. I then want to convert this 3 byte long string to an integer.

Author:raccess,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/38307550/reading-a-serial-port-in-python-with-unknown-data-length
yy