简体   繁体   中英

How to read only the number from serial port in python?

I am currently trying to read from the serial port in order to graph accelerometer angle values. The accelerometer is programmed with C and outputs values to the serial monitor like this:

x angle = 20

x angle = 25

I just wanted to pull the number value from this line in python so I can graph it, how would I go about doing this so I can exclude the string part. This is how I am currently reading from the serial port. This method works only if I write integers to the serial port and nothing else.

  angle = ser.readline()
  x = int(angle)
angle = ser.readline()
print(angle)
print(angle[10:])
x = int(angle[10:])

Use a regular expression to extract the integer. It has the advantage of skipping any other data coming from the input source. I assume the data is input as a bytes object so I'm using a bytes regular expression with a capture group for just the decimals at the end.

import re

angle = ser.readline()
match = re.match(br"x angle = (\d+)", angle)
if match:
    x = int(match.group(1))
else:
    # any reason to handle different data?
    pass

Split string on space:

angle = ser.readline().split(' ')

This approach not only makes working with any angle possible (1 has less characters than 23 and 112 for example) but also give you information about axis.

So after splitting your angle variable is a list which consists of elements: ['x', 'angle', '=', '20'] . So angle[0] is x and angle[3] is 20. So last step to integer is:

integer_angle = int(angle[3])

You'll need to decode the serial data, it should look something along the lines of

x = angle.decode('utf-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM