View difference between Paste ID: VpcLebzD and RbDjLFjM
SHOW: | | - or go back to the newest paste.
1
# maxSonarTTY.py
2
3
import serial
4
import re
5
6
class MaxSonar( serial.Serial ):
7
    def __init__( self, port ):
8
        super().__init__( port=port, baudrate=9600, timeout=0.5 )
9
10
    def measure( self ):
11
        self.reset_input_buffer()
12
13-
        data = self.read_until( b'\r', size=5 )
13+
        data = self.read_until( expected=b'\r', size=5 )
14
15
        if re.fullmatch( rb'\d*\r', data ):
16
            # partial line received, wait for next one
17-
            data = self.read_until( b'\r', size=5 )
17+
            data = self.read_until( expected=b'\r', size=5 )
18
19
        if len( data ) < 5 and not data.endswith( b'\r' ):
20
            raise RuntimeError( "Timeout while waiting for data" )
21
22-
        m = re.fullmatch( rb'R(\d+)\r', data )
22+
        m = re.fullmatch( rb'R(0|[1-9]\d*)\r', data )
23
        if not m:
24
            raise RuntimeError( "Garbage data received: %r" % data )
25
        data = m.group( 1 )
26
27
        return int( data )  # measurement in inches (0-255)
28
29
30
# maxSonarTTY-example.py
31
32
from time import sleep
33
from maxSonarTTY import MaxSonar
34
35
sonar = MaxSonar( "/dev/ttyS2" )
36
37
try:
38
    while True:
39
        distance = sonar.measure()
40
        print( "distance =", distance, "inch" )
41
42
        sleep( 1 )
43
44
except KeyboardInterrupt:
45
    pass