Advertisement
Anatom

Sensor class

Feb 19th, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. class SensorInput {
  2. public:
  3.     byte inputPin;
  4.     int sensorState;             // the current reading from the input pin
  5.     int lastSensorState;   // the previous reading from the input pin
  6.  
  7.     // the following variables are unsigned longs because the time, measured in
  8.     // milliseconds, will quickly become a bigger number than can be stored in an int.
  9.     unsigned long lastDebounceTimeSensor;  // the last time the output pin was toggled
  10.     unsigned long debounceDelaySensor;    // the debounce time; increase if the output flickers
  11.  
  12.     SensorInput(byte inputPin) {
  13.         lastSensorState = HIGH;
  14.         lastDebounceTimeSensor = 0;
  15.         debounceDelaySensor = 50;
  16.  
  17.         this->inputPin = inputPin;
  18.         pinMode(inputPin, INPUT_PULLUP);  // sets the pin as input
  19.     };
  20.  
  21.     bool checkState() {
  22.  
  23.         int reading = digitalRead(inputPin);
  24.         DBGV("Sensor read: ", reading);
  25.  
  26.         // check to see if you just pressed the button
  27.         // (i.e. the input went from LOW to HIGH), and you've waited long enough
  28.         // since the last press to ignore any noise:
  29.  
  30.         // If the switch changed, due to noise or pressing:
  31.         if (reading != lastSensorState) {
  32.             // reset the debouncing timer
  33.             lastDebounceTimeSensor = millis();
  34.         }
  35.  
  36.         if ((millis() - lastDebounceTimeSensor) > debounceDelaySensor) {
  37.             // whatever the reading is at, it's been there for longer than the debounce
  38.             // delay, so take it as the actual current state:
  39.  
  40.             // if the button state has changed:
  41.             if (reading != sensorState) {
  42.             sensorState = reading;
  43.  
  44.                 // only toggle the LED if the new button state is HIGH
  45.                 if (sensorState == LOW) {
  46.                     return 1;
  47.                 }
  48.             }
  49.         }
  50.  
  51.         // set the LED:
  52.         //digitalWrite(ledPin, ledState);
  53.  
  54.         // save the reading. Next time through the loop, it'll be the lastButtonState:
  55.         lastSensorState = reading;
  56.         return 0;
  57.     }
  58.  
  59.  
  60. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement