techposts

Homekit Occupancy Presence Sensor LD2410 Code

Feb 21st, 2025 (edited)
788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | Software | 0 0
  1. #include "HomeSpan.h"
  2.  
  3. #define LD2410_PIN 4  // GPIO pin connected to the sensor's OUT pin
  4.  
  5. ////////////////////////////////////////////
  6. // Occupancy Sensor Service Definition
  7. ////////////////////////////////////////////
  8.  
  9. struct OccupancySensor : Service::OccupancySensor {
  10.  
  11.   SpanCharacteristic *occupancy; // 0 = Not Occupied, 1 = Occupied
  12.  
  13.   // Constructor
  14.   OccupancySensor() : Service::OccupancySensor() {
  15.     occupancy = new Characteristic::OccupancyDetected(0);
  16.     pinMode(LD2410_PIN, INPUT); // or INPUT_PULLUP if needed
  17.   }
  18.  
  19.   // Continuously called by HomeSpan
  20.   void loop() {
  21.     bool isPresent = digitalRead(LD2410_PIN);
  22.     occupancy->setVal(isPresent ? 1 : 0);
  23.   }
  24. };
  25.  
  26. ////////////////////////////////////////////
  27. // Setup and Main Loop
  28. ////////////////////////////////////////////
  29.  
  30. void setup() {
  31.   Serial.begin(115200);
  32.  
  33.   // Initialize HomeSpan
  34.   homeSpan.begin(Category::Sensors, "LD2410 Occupancy Sensor");
  35.  
  36.   // Create an Accessory with Identify + Occupancy
  37.   new SpanAccessory();
  38.     new Service::AccessoryInformation();
  39.       new Characteristic::Identify();
  40.     new OccupancySensor();  // Attach our custom OccupancySensor
  41. }
  42.  
  43. void loop() {
  44.   homeSpan.poll();
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment