silver2row

range lib. MaxBotix.com/@zmatt

Sep 25th, 2020
1,269
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import serial
  2. import re
  3.  
  4. class Range(serial.Serial):
  5.     def __init__(self, port):
  6.         super().__init__(port=port, baudrate=9600, timeout=1)
  7.  
  8.     def measure( self ):
  9.         self.reset_input_buffer()
  10.  
  11.         data = self.read_until(b'\r', size=5)
  12.  
  13.         if re.fullmatch(rb'\d*\r', data):
  14.             # partial line received, wait for next one
  15.             data = self.read_until(b'\r', size=5)
  16.  
  17.         if len(data) < 5 and not data.endswith(b'\r'):
  18.             raise RuntimeError("Timeout while waiting for data")
  19.  
  20.         m = re.fullmatch(rb'R(\d+)\r', data)
  21.         if not m:
  22.             raise RuntimeError("Garbage data received: %r" % data)
  23.         data = m.group(1)
  24.  
  25.         return int(data)  # measurement in inches (0-255)
  26.  
RAW Paste Data