COSA
An Object-Oriented Platform for Arduino Programming
HCSR04.cpp
Go to the documentation of this file.
1 
21 #include "HCSR04.hh"
22 
23 bool
24 HCSR04::read(uint16_t& distance)
25 {
26  distance = 0;
27 
28  // Give the device a trigger pulse
29  m_trigger.pulse(10);
30  uint16_t timeout = TIMEOUT;
31 
32  // Wait for the response
33  while (m_echo.is_clear() && timeout--) DELAY(1);
34  if (timeout == 0) return (false);
35 
36  // Measure the lenght of the return pulse
37  uint16_t count = 0;
38  synchronized {
39  while (m_echo.is_set() && timeout--) count++;
40  }
41  if (timeout == 0) return (false);
42 
43  // And calculate the distance in milli-meters
44  distance = (count * 100L) / COUNT_PER_DM;
45  return (true);
46 }
47 
48 void
49 HCSR04::on_event(uint8_t type, uint16_t value)
50 {
51  UNUSED(type);
52  UNUSED(value);
53  uint16_t distance;
54 
55  // Read the distance and check if there was a change
56  if (!read(distance) || (m_distance == distance)) return;
57 
58  // Save the new distance and call the change handler
59  m_distance = distance;
60  on_change(distance);
61 }
virtual void on_change(uint16_t distance)
Definition: HCSR04.hh:105
bool read(uint16_t &distance)
Definition: HCSR04.cpp:24
void pulse(uint16_t us) const
Definition: OutputPin.hh:378
#define DELAY(us)
Definition: Types.h:280
bool is_set() const
Definition: Pin.hh:112
#define UNUSED(x)
Definition: ATmega328P.hh:31
bool is_clear() const
Definition: Pin.hh:142
uint16_t distance() const
Definition: HCSR04.hh:72