Question

I have one XBee router (XB-X) connected to an ultrasonic range sensor and the other XBee coordinator (XB-Y) connected to my PC. XB-X will send the sensor reading to XB-Y. I am trying to extract the bytes from ser.read() on my PC using Python.

I got a weird bytes of string consist of ">>~}3@zi167.89" on output, may I know how to extract only the floating point number (167.89 in this example)? The number of bytes are specified by setting ser.read(size=xx). Is there any alternative way of doing it?

import serial
import zigbee
from xbee import ZigBee
import re

ser = serial.Serial("COM4", 9600)

while True:
   try:
      input = ser.read(20)
      m = re.search(r'(\d+\.\d+)', input)
      if m:
          num = m.group()
   # statements...

It is working now, carelessly typed 'group' as 'groups'.

Was it helpful?

Solution

Just use a regular expression:

import re
input = ser.read()
m = re.search(r'(?P<num>\d+\.\d+)', input)
if m:
    num = float(m.group('num'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top