import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *
data = serial.Serial('com3',115200)
while True:
while (data.inWaiting() == 0):
pass
ardstr = data.readline()
print (ardstr)
Here I am trying to get data from arduino but it is coming in the format b'29.20\r\n'
. I want to have the data in the format "29.20"
so I can plot it.
I tried ardstr = str(ardstr).strip('\r\n')
and ardstr.decode('UTF-8')
but none of them is working. My python version is 3.4.3.
What can I do to get the result as "29.40"
rather than "b'29.20\r\n'"
?
One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.
The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();
I tried
ardstr = str(ardstr).strip('\r\n')
andardstr.decode('UTF-8')
You were close! As with the .strip()
call, using the .decode()
method returns the new value.
ardstr = ardstr.strip()
ardstr = ardstr.decode('UTF-8')
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