Search code examples
python-2.7hexbitpyserialbinascii

Pyserial reading does not respect the number of bites


I am trying to read-out a serial port. The problem is that the script works but the read command seems to not respect the argument (2 bytes to read).

The typical output of the script (the ans variable in return function "readPosValue") is:

print(currTime,readPosValue(serPort))
(1517909247.176, '0b11000010110111001110011')

They are clearly more than 16 bits. The used script:

import time
import struct
import binascii
import serial

ser = serial.Serial(
port='COM2',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS

)

def inficonAcquisition(serPort):  

        try:

        while True:
            position = readPosValue(serPort)

            currTime = time.time()

            print(currTime,position)


    except KeyboardInterrupt:
        serPort.close()

        exit()

def readPosValue(serPort):       
    ans = ''
    while serPort.inWaiting() > 0:
        ans += serPort.read(2)    
    return bin(int(binascii.hexlify('ans'), 16))

Solution

  • The problem was in the inWaiting() function. It was not required in this kind of readout.