-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLDR.cpp
More file actions
84 lines (76 loc) · 1.91 KB
/
Copy pathLDR.cpp
File metadata and controls
84 lines (76 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <Arduino.h>
#include "CFG.h"
#include "LDR.h"
namespace LDR {
// Treats the LDR as two-state -- Bright or Dim.
// Logic is like a debounced button, rather than a rolling average.
int _pin = 0;
bool _PrevReading;
bool _PrevState;
bool _CurrentState;
unsigned long _TransitionTimeMS;
#define READING_COUNTER_START 200
uint8_t readingCounter = 0;
OverrideMode overrideMode = NoOverride;
bool Read()
{
// Return true if the LDR/Ambient is "bright" right now
if (!_pin)
return false;
int reading = analogRead(_pin);
return reading > CFG_LDR_DAY_THRESHOLD;
}
void Init(int pin)
{
// Init the readings
_pin = pin;
Reset();
}
void Reset()
{
// Reset the "debounce"
readingCounter = 0;
_PrevReading = _PrevState = _CurrentState = Read();
_TransitionTimeMS = millis();
}
bool IsBright()
{
// Return true if the LDR/Ambient is consistently "bright"
if (!readingCounter) // only do an analog read occasionally
{
readingCounter = READING_COUNTER_START;
bool ThisReading = Read();
if (ThisReading != _PrevReading)
{
// state change, reset the timer
_PrevReading = ThisReading;
_TransitionTimeMS = millis();
}
else if (ThisReading != _PrevState &&
(millis() - _TransitionTimeMS) >= CFG_LDR_HOLD_TIME_MS)
{
// a state other than the last one and held for long enough
_CurrentState = _PrevState = ThisReading;
}
}
readingCounter++;
if (overrideMode == OverrideOff)
{
if (_CurrentState) // if on, force off
return false;
overrideMode = NoOverride; // if off, cancel override
}
else if (overrideMode == OverrideOn)
{
if (!_CurrentState) // if off, force on
return true;
overrideMode = NoOverride; // if on, cancel override
}
return _CurrentState;
}
int Raw()
{
// return raw reading
return analogRead(_pin);
}
}