Mutila: Mouse's Utilities for Arduino
Oft-used utilities: debouncing buttons, averaging samples, and so on.
SonicRanger.cpp
1 #include <Arduino.h>
2 #include <Millis.h>
3 #include "SonicRanger.h"
4 
5 #ifdef ARDUINO_AVR_DIGISPARK
6 // Implementation missing when building for DigiSpark, so I copy-pasted it from:
7 // https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c#L63
8 uint32_t pulseInLong(uint8_t pin, uint8_t state, uint32_t timeout)
9 {
10  // cache the port and bit of the pin in order to speed up the
11  // pulse width measuring loop and achieve finer resolution. calling
12  // digitalRead() instead yields much coarser resolution.
13  uint8_t bit = digitalPinToBitMask(pin);
14  uint8_t port = digitalPinToPort(pin);
15  uint8_t stateMask = (state ? bit : 0);
16 
17  uint32_t startMicros = micros();
18 
19  // wait for any previous pulse to end
20  while ((*portInputRegister(port) & bit) == stateMask) {
21  if (micros() - startMicros > timeout)
22  return 0;
23  }
24 
25  // wait for the pulse to start
26  while ((*portInputRegister(port) & bit) != stateMask) {
27  if (micros() - startMicros > timeout)
28  return 0;
29  }
30 
31  uint32_t start = micros();
32  // wait for the pulse to stop
33  while ((*portInputRegister(port) & bit) == stateMask) {
34  if (micros() - startMicros > timeout)
35  return 0;
36  }
37  return micros() - start;
38 }
39 #endif // ARDUINO_AVR_DIGISPARK
40 
41 SonicRanger::SonicRanger(const uint8_t trigPin, const uint8_t echoPin) :
42  _trigPin(trigPin),
43  _echoPin(echoPin),
44  _maxCm(DefaultMaxRangeCm),
45  _timeoutMs(DefaultTimeoutMs)
46 {
47 }
48 
50 {
51  pinMode(_trigPin, OUTPUT);
52  pinMode(_echoPin, INPUT);
53 }
54 
56 {
57  digitalWrite(_trigPin, LOW);
58  delayMicroseconds(2);
59  digitalWrite(_trigPin, HIGH);
60  delayMicroseconds(10);
61  uint32_t b4 = Millis();
62  digitalWrite(_trigPin, LOW);
63  uint32_t time = pulseInLong(_echoPin, HIGH, _timeoutMs*1000UL);
64  uint32_t after = Millis();
65  //if (after - b4 >= _timeoutMs) {
66  if (MillisSince(b4, after) >= _timeoutMs) {
67  return _maxCm;
68  } else {
69  return time*0.034/2;
70  }
71 }
72 
uint16_t getRange()
Definition: SonicRanger.cpp:55
SonicRanger(const uint8_t trigPin, const uint8_t echoPin)
Definition: SonicRanger.cpp:41
void begin()
Definition: SonicRanger.cpp:49