FastLED 3.9.7
Loading...
Searching...
No Matches
pir.cpp
1#define FASTLED_INTERNAL
2#include "FastLED.h"
3
4#include "sensors/pir.h"
5#include "fastpin.h"
6#include "fl/warn.h"
7
8
9namespace fl {
10
11namespace {
12 int g_counter = 0;
13 Str buttonName() {
14 int count = g_counter++;
15 if (count == 0) {
16 return Str("PIR");
17 }
18 return Str("Pir ").append(g_counter++);
19 }
20}
21
22
23Pir::Pir(int pin): mButton(buttonName().c_str()), mPin(pin) {
24 mPin.setPinMode(DigitalPin::kInput);
25}
26
27bool Pir::detect() {
28 return mPin.high() || mButton.clicked();
29}
30
31PirAdvanced::PirAdvanced(int pin, uint32_t latchMs, uint32_t risingTime, uint32_t fallingTime)
32 : mPir(pin)
33 , mLatchMs(latchMs)
34 , mRisingTime(risingTime)
35 , mFallingTime(fallingTime)
36 , mLastTrigger(0)
37 , mLastState(false) {
38
39 if (mRisingTime + mFallingTime > mLatchMs) {
40 FASTLED_WARN("PirAdvanced: risingTime + fallingTime must be less than latchMs");
41 mRisingTime = mLatchMs / 2;
42 mFallingTime = mLatchMs / 2;
43 }
44}
45
46bool PirAdvanced::detect(uint32_t now) {
47 bool currentState = mPir.detect();
48
49 if (currentState && !mLastState) {
50 mLastTrigger = now;
51 }
52
53 mLastState = currentState;
54 return (now - mLastTrigger) < mLatchMs;
55}
56
57uint8_t PirAdvanced::transition(uint32_t now) {
58 detect(now);
59 uint32_t elapsed = now - mLastTrigger;
60
61 uint8_t out = 0;
62 if (elapsed < mRisingTime) {
63 // Rising phase - alpha goes from 0 to 255
64 out = MAX(mLastTransition, (elapsed * 255) / mRisingTime);
65 }
66 else if (elapsed >= mLatchMs - mFallingTime && elapsed < mLatchMs) {
67 // Falling phase - alpha goes from 255 to 0
68 uint32_t fallingElapsed = elapsed - (mLatchMs - mFallingTime);
69 out = 255 - ((fallingElapsed * 255) / mFallingTime);
70 }
71 else if (elapsed >= mRisingTime && elapsed < mLatchMs - mFallingTime) {
72 // Fully on
73 out = 255;
74 }
75 mLastTransition = out;
76 // Outside latch period
77 return out;
78}
79
80} // 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