I have this code to format the received data from Serial port to 2 variables
it receives 'v=220f=50' and format it to
reads = ser.readline() # data received is 'v=220f=50'
voltage = int('{2}{3}{4}'.format(*reads))
freq = '{7}{8}'.format(*reads)
so voltage = 220 and freq = 50 but i get voltage = 505048 and freq = 5348 instead!, I tried casting them to int() but nothing changed. maybe it's some sort of encoding.
ps: I want to store them into a file so no need to cast them to integers:
fw.write('Voltage is: {0};\t Frequency is: {1}\n'.format(voltage, freq))
You have a bytes object from ser.readline(). You should first convert to string with .decode:
>>> reads = b'v=220f=50'
>>> voltage = int('{2}{3}{4}'.format(*reads))
>>> voltage
505048
>>> voltage = int('{2}{3}{4}'.format(*reads.decode()))
>>> voltage
220
I would also suggest you look into parsing the values using regex. The current approach would easily break when the length of any of the values change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With