FastLED 3.9.12
Loading...
Searching...
No Matches
pir.cpp
1#define FASTLED_INTERNAL
2#include "FastLED.h"
3
4#include "sensors/pir.h"
5#include "fl/strstream.h"
6#include "fastpin.h"
7#include "fl/warn.h"
8
9
10namespace fl {
11
12namespace {
13 int g_counter = 0;
14 Str getButtonName(const char* button_name) {
15 if (button_name) {
16 return Str(button_name);
17 }
18 int count = g_counter++;
19 if (count == 0) {
20 return Str("PIR");
21 }
22 StrStream s;
23 s << "Pir " << g_counter++;
24 return s.str();
25 }
26}
27
28
29Pir::Pir(int pin, const char* button_name): mButton(getButtonName(button_name).c_str()), mPin(pin) {
30 mPin.setPinMode(DigitalPin::kInput);
31}
32
33bool Pir::detect() {
34 return mPin.high() || mButton.clicked();
35}
36
37PirAdvanced::PirAdvanced(int pin, uint32_t latchMs, uint32_t risingTime, uint32_t fallingTime)
38 : mPir(pin)
39 , mLatchMs(latchMs)
40 , mRisingTime(risingTime)
41 , mFallingTime(fallingTime)
42 , mLastTrigger(0)
43 , mLastState(false) {
44
45 if (mRisingTime + mFallingTime > mLatchMs) {
46 FASTLED_WARN("PirAdvanced: risingTime + fallingTime must be less than latchMs");
47 mRisingTime = mLatchMs / 2;
48 mFallingTime = mLatchMs / 2;
49 }
50}
51
52bool PirAdvanced::detect(uint32_t now) {
53 bool currentState = mPir.detect();
54
55 if (currentState && !mLastState) {
56 mLastTrigger = now;
57 }
58
59 mLastState = currentState;
60 return (now - mLastTrigger) < mLatchMs;
61}
62
63uint8_t PirAdvanced::transition(uint32_t now) {
64 detect(now);
65 uint32_t elapsed = now - mLastTrigger;
66
67 uint8_t out = 0;
68 if (elapsed < mRisingTime) {
69 // Rising phase - alpha goes from 0 to 255
70 out = MAX(mLastTransition, (elapsed * 255) / mRisingTime);
71 }
72 else if (elapsed >= mLatchMs - mFallingTime && elapsed < mLatchMs) {
73 // Falling phase - alpha goes from 255 to 0
74 uint32_t fallingElapsed = elapsed - (mLatchMs - mFallingTime);
75 out = 255 - ((fallingElapsed * 255) / mFallingTime);
76 }
77 else if (elapsed >= mRisingTime && elapsed < mLatchMs - mFallingTime) {
78 // Fully on
79 out = 255;
80 }
81 mLastTransition = out;
82 // Outside latch period
83 return out;
84}
85
86} // namespace fl
central include file for FastLED, defines the CFastLED class/object
Class base definitions for defining fast pin access.
Implements a simple red square effect for 2D LED grids.
Definition crgb.h:16