sonar_trigger_echo.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import time
4 
5 import pigpio
6 
7 class ranger:
8  """
9  This class encapsulates a type of acoustic ranger. In particular
10  the type of ranger with separate trigger and echo pins.
11 
12  A pulse on the trigger initiates the sonar ping and shortly
13  afterwards a sonar pulse is transmitted and the echo pin
14  goes high. The echo pins stays high until a sonar echo is
15  received (or the response times-out). The time between
16  the high and low edges indicates the sonar round trip time.
17  """
18 
19  def __init__(self, pi, trigger, echo):
20  """
21  The class is instantiated with the Pi to use and the
22  gpios connected to the trigger and echo pins.
23  """
24  self.pi = pi
25  self._trig = trigger
26  self._echo = echo
27 
28  self._ping = False
29  self._high = None
30  self._time = None
31 
32  self._triggered = False
33 
34  self._trig_mode = pi.get_mode(self._trig)
35  self._echo_mode = pi.get_mode(self._echo)
36 
37  pi.set_mode(self._trig, pigpio.OUTPUT)
38  pi.set_mode(self._echo, pigpio.INPUT)
39 
40  self._cb = pi.callback(self._trig, pigpio.EITHER_EDGE, self._cbf)
41  self._cb = pi.callback(self._echo, pigpio.EITHER_EDGE, self._cbf)
42 
43  self._inited = True
44 
45  def _cbf(self, gpio, level, tick):
46  if gpio == self._trig:
47  if level == 0: # trigger sent
48  self._triggered = True
49  self._high = None
50  else:
51  if self._triggered:
52  if level == 1:
53  self._high = tick
54  else:
55  if self._high is not None:
56  self._time = tick - self._high
57  self._high = None
58  self._ping = True
59 
60  def read(self):
61  """
62  Triggers a reading. The returned reading is the number
63  of microseconds for the sonar round-trip.
64 
65  round trip cms = round trip time / 1000000.0 * 34030
66  """
67  if self._inited:
68  self._ping = False
69  self.pi.gpio_trigger(self._trig)
70  start = time.time()
71  while not self._ping:
72  if (time.time()-start) > 5.0:
73  return 20000
74  time.sleep(0.001)
75  return self._time
76  else:
77  return None
78 
79  def cancel(self):
80  """
81  Cancels the ranger and returns the gpios to their
82  original mode.
83  """
84  if self._inited:
85  self._inited = False
86  self._cb.cancel()
87  self.pi.set_mode(self._trig, self._trig_mode)
88  self.pi.set_mode(self._echo, self._echo_mode)
89 
90 if __name__ == "__main__":
91 
92  import time
93 
94  import pigpio
95 
96  import sonar_trigger_echo
97 
98  pi = pigpio.pi()
99 
100  sonar = sonar_trigger_echo.ranger(pi, 23, 18)
101 
102  end = time.time() + 600.0
103 
104  r = 1
105  while time.time() < end:
106 
107  print("{} {}".format(r, sonar.read()))
108  r += 1
109  time.sleep(0.03)
110 
111  sonar.cancel()
112 
113  pi.stop()
114 
def __init__(self, pi, trigger, echo)
def _cbf(self, gpio, level, tick)


cob_hand_bridge
Author(s): Mathias Lüdtke
autogenerated on Tue Oct 20 2020 03:35:57