Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # maxSonarTTY.py
- import serial
- import re
- class MaxSonar( serial.Serial ):
- def __init__( self, port ):
- super().__init__( port=port, baudrate=9600, timeout=0.5 )
- def measure( self ):
- self.reset_input_buffer()
- data = self.read_until( b'\r', size=5 )
- if re.fullmatch( rb'\d*\r', data ):
- # partial line received, wait for next one
- data = self.read_until( b'\r', size=5 )
- if len( data ) < 5 and not data.endswith( b'\r' ):
- raise RuntimeError( "Timeout while waiting for data" )
- m = re.fullmatch( rb'R(\d+)\r', data )
- if not m:
- raise RuntimeError( "Garbage data received: %r" % data )
- data = m.group( 1 )
- return int( data ) # measurement in inches (0-255)
- # maxSonarTTY-example.py
- from time import sleep
- from maxSonarTTY import MaxSonar
- sonar = MaxSonar( "/dev/ttyS2" )
- try:
- while True:
- distance = sonar.measure()
- print( "distance =", distance, "inch" )
- sleep( 1 )
- except KeyboardInterrupt:
- pass
Add Comment
Please, Sign In to add comment