Pololu3piPlus32U4 library
Pololu3piPlus32U4BumpSensors.cpp
1 // Copyright (C) Pololu Corporation. See www.pololu.com for details.
2 
4 #include <FastGPIO.h>
5 
6 namespace Pololu3piPlus32U4
7 {
8 
9 void BumpSensors::readRaw()
10 {
11  FastGPIO::Pin<emitterPin>::setOutputLow(); // Turn on the emitters.
12 
13  FastGPIO::Pin<bumpLeftPin>::setOutputHigh();
14  FastGPIO::Pin<bumpRightPin>::setOutputHigh();
15  _delay_us(10);
16 
17  sensorValues[0] = timeout;
18  sensorValues[1] = timeout;
19 
20  noInterrupts();
21  uint16_t startTime = micros();
22  FastGPIO::Pin<bumpLeftPin>::setInput();
23  FastGPIO::Pin<bumpRightPin>::setInput();
24  interrupts();
25 
26  while (true)
27  {
28  noInterrupts();
29  uint16_t time = micros() - startTime;
30  if (time >= timeout)
31  {
32  interrupts();
33  break;
34  }
35  if (!FastGPIO::Pin<bumpLeftPin>::isInputHigh() && time < sensorValues[0]) { sensorValues[0] = time; }
36  if (!FastGPIO::Pin<bumpRightPin>::isInputHigh() && time < sensorValues[1]) { sensorValues[1] = time; }
37  interrupts();
38  __builtin_avr_delay_cycles(4); // allow interrupts to run
39  }
40 
41  FastGPIO::Pin<emitterPin>::setInput(); // turn off the emitters
42 }
43 
44 void BumpSensors::calibrate(uint8_t count)
45 {
46  uint32_t sum[2] = {0, 0};
47 
48  for (uint8_t i = 0; i < count; i++)
49  {
50  readRaw();
53  }
54 
55  for (uint8_t s = BumpLeft; s <= BumpRight; s++)
56  {
57  baseline[s] = (sum[s] + count / 2) / count;
58 
59  // Calculate threshold to compare readings to by adding margin to baseline,
60  // but make sure it is no larger than the QTR sensor timeout (i.e. if the
61  // reading timed out, consider the bump sensor pressed).
62  threshold[s] = baseline[s] + baseline[s] * (uint32_t)marginPercentage / 100;
63  if (threshold[s] > timeout) { threshold[s] = timeout; }
64  }
65 }
66 
68 {
69  readRaw();
70 
71  uint8_t bitField = 0;
72  for (uint8_t s = BumpLeft; s <= BumpRight; s++)
73  {
74  last[s] = pressed[s];
75  pressed[s] = (sensorValues[s] >= threshold[s]);
76  bitField |= pressed[s] << s;
77  }
78  return bitField;
79 }
80 
81 }
uint16_t sensorValues[2]
Raw reflectance sensor readings.
uint16_t threshold[2]
Thresholds for bump sensor press detection.
uint16_t marginPercentage
The amount, as a percentage, that will be added to the measured baseline to get the threshold.
uint16_t baseline[2]
Baseline readings obtained from calibration.
uint8_t read()
Reads both bump sensors.
uint16_t timeout
Timeout for bump sensor readings (in microseconds).
void calibrate(uint8_t count=50)
Calibrates the bump sensors.
Top-level namespace for the Pololu3piPlus32U4 library.
@ BumpRight
Right bump sensor.