ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
gpio_binary_sensor.h
Go to the documentation of this file.
1#pragma once
2
5#include "esphome/core/hal.h"
8
9namespace esphome::gpio {
10
11// Store class for ISR data and configuration (no vtables, ISR-safe)
13 public:
14#ifdef USE_GPIO_BINARY_SENSOR_INTERRUPT
16
17 static void gpio_intr(GPIOBinarySensorStore *arg);
18
19 bool get_state() const {
20 // No lock needed: state_ is atomically updated by ISR
21 // Volatile ensures we read the latest value
22 return this->state_;
23 }
24
25 bool is_changed() const {
26 // Simple read of volatile bool - no clearing here
27 return this->changed_;
28 }
29
31 // Separate method to clear the flag
32 this->changed_ = false;
33 }
34#endif
35
36 protected:
37 friend class GPIOBinarySensor;
38#ifdef USE_GPIO_BINARY_SENSOR_INTERRUPT
40 Component *component_{nullptr}; // Pointer to the component for enable_loop_soon_any_context()
41 volatile bool state_{false};
42 volatile bool changed_{false};
44 bool use_interrupt_{true};
45#endif
46};
47
49 public:
50 // User provided, not "= default": `new(p) GPIOBinarySensor()` would zero-fill .bss that is already zero.
52
53 // No destructor needed: ESPHome components are created at boot and live forever.
54 // Interrupts are only detached on reboot when memory is cleared anyway.
55
56 void set_pin(GPIOPin *pin) { this->pin_ = pin; }
57#ifdef USE_GPIO_BINARY_SENSOR_INTERRUPT
58 void set_use_interrupt(bool use_interrupt) { this->store_.use_interrupt_ = use_interrupt; }
60#else
61 // Polling-only build: codegen still emits set_use_interrupt(false) calls,
62 // so keep the setter as an inlined no-op instead of storing the flag.
63 void set_use_interrupt(bool /*use_interrupt*/) {}
64#endif
65 // ========== INTERNAL METHODS ==========
66 // (In most use cases you won't need these)
68 void setup() override;
69 void dump_config() override;
71 float get_setup_priority() const override;
73 void loop() override;
74
75 protected:
76 GPIOPin *pin_{nullptr};
78};
79
80} // namespace esphome::gpio
Copy of GPIOPin that is safe to use from ISRs (with no virtual functions)
Definition gpio_pin.h:98
Base class for all binary_sensor-type classes.
void loop() override
Check sensor.
float get_setup_priority() const override
Hardware priority.
void setup() override
Setup pin.
void set_interrupt_type(gpio::InterruptType type)
void set_use_interrupt(bool use_interrupt)
static void gpio_intr(GPIOBinarySensorStore *arg)
const Component * component
Definition component.cpp:34
uint8_t type
void setup()
@ INTERRUPT_ANY_EDGE
Definition gpio_pin.h:54