Skip to content

Commit 082762d

Browse files
Added Zigbee light sensor
1 parent 66abd86 commit 082762d

File tree

7 files changed

+370
-0
lines changed

7 files changed

+370
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Arduino-ESP32 Zigbee Light Sensor Sleepy Device Example
2+
3+
This example demonstrates how to use the Zigbee library to create an end device light sensor and use it as a Home Automation (HA) extended light sensor.
4+
5+
# Supported Targets
6+
7+
Currently, this example supports the following targets.
8+
9+
| Supported Targets | ESP32-C6 | ESP32-H2 |
10+
| ----------------- | -------- | -------- |
11+
12+
## Light Sensor Functions
13+
14+
1. Initialize a Zigbee light sensor.
15+
2. Measure illuminance value.
16+
3. Report the measured value to the Zigbee network.
17+
18+
## Hardware Required
19+
20+
* ESP32-H2 or ESP32-C6 development board
21+
* A USB cable for power supply and programming
22+
* Some kind of light sensor, such as a photoresistor
23+
24+
### Configure the Project
25+
26+
In this example the raw analog value of a light sensor is used to calculate illuminance.
27+
Alter the calculation according to your use case and calibrate it to receive correct lux values.
28+
Set the light sensor GPIO by changing the `light_sensor_pin` variable to the pin to the pin to which your sensor is connected.
29+
Set the button GPIO by changing the `button` variable. By default, it's the pin `BOOT_PIN` (BOOT button on ESP32-C6 and ESP32-H2).
30+
31+
#### Using Arduino IDE
32+
33+
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
34+
35+
* Before Compile/Verify, select the correct board: `Tools -> Board`.
36+
* Select the End device Zigbee mode: `Tools -> Zigbee mode: Zigbee ED (end device)`
37+
* Select Partition Scheme for Zigbee: `Tools -> Partition Scheme: Zigbee 4MB with spiffs`
38+
* Enable USB CDC to be able to use the serial monitor: `Tools -> USB CDC On Boot: Enabled`
39+
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
40+
* Optional: Set debug level to verbose to see all logs from Zigbee stack: `Tools -> Core Debug Level: Verbose`.
41+
42+
## Troubleshooting
43+
44+
If the End device flashed with this example is not connecting to the coordinator, erase the flash of the End device before flashing the example to the board. It is recommended to do this if you re-flash the coordinator.
45+
You can do the following:
46+
47+
* In the Arduino IDE go to the Tools menu and set `Erase All Flash Before Sketch Upload` to `Enabled`.
48+
* Add to the sketch `Zigbee.factoryReset();` to reset the device and Zigbee stack.
49+
50+
By default, the coordinator network is closed after rebooting or flashing new firmware.
51+
To open the network you have 2 options:
52+
53+
* Open network after reboot by setting `Zigbee.setRebootOpenNetwork(time);` before calling `Zigbee.begin();`.
54+
* In application you can anytime call `Zigbee.openNetwork(time);` to open the network for devices to join.
55+
56+
***Important: Make sure that you are using a good quality USB cable with data lines and that you have a reliable power source***
57+
58+
* **LED not blinking:** Check the wiring connection and the IO selection.
59+
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
60+
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.
61+
62+
If the error persists, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
63+
64+
## Contribute
65+
66+
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
67+
68+
If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!
69+
70+
Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else.
71+
72+
## Resources
73+
74+
* Official ESP32 Forum: [Link](https://esp32.com)
75+
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
76+
* ESP32-C6 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c6_datasheet_en.pdf)
77+
* ESP32-H2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-h2_datasheet_en.pdf)
78+
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* @brief This example demonstrates Zigbee light sensor.
17+
*
18+
* The example demonstrates how to use Zigbee library to create a end device light sensor.
19+
* The light sensor is a Zigbee end device, which is controlled by a Zigbee coordinator.
20+
*
21+
* Proper Zigbee mode must be selected in Tools->Zigbee mode
22+
* and also the correct partition scheme must be selected in Tools->Partition Scheme.
23+
*
24+
* Please check the README.md for instructions and more detailed description.
25+
*
26+
* Created by MikaFromTheRoof (https://github.com/MikaFromTheRoof)
27+
*/
28+
29+
#ifndef ZIGBEE_MODE_ED
30+
#error "Zigbee end device mode is not selected in Tools->Zigbee mode"
31+
#endif
32+
33+
#include "Zigbee.h"
34+
35+
#define ZIGBEE_LIGHT_SENSOR_ENDPOINT 9
36+
uint8_t button = BOOT_PIN;
37+
uint8_t light_sensor_pin = 6; // Insert the analog pin to which the sensor (e.g. photoresistor) is connected
38+
39+
ZigbeeLightSensor zbLightSensor = ZigbeeLightSensor(ZIGBEE_LIGHT_SENSOR_ENDPOINT);
40+
41+
/********************* Light sensor **************************/
42+
static void light_sensor_value_update(void *arg) {
43+
for (;;) {
44+
// read the raw analog value from the sensor
45+
int lsens_analog = analogRead(light_sensor_pin);
46+
Serial.printf("[Light Sensor] raw analog value: %d°C\r\n", lsens_analog);
47+
48+
// conversion into zigbee illuminance number value (typically between 0 in darkness and 50000 in direct sunlight)
49+
// depends on the value range of the raw analog sensor values and will need calibration for correct lux values
50+
int lsens_value = lsens_analog * 10; // mult by 10 for the sake of this example
51+
Serial.printf("[Light Sensor] number value: %d°C\r\n", lsens_value);
52+
53+
// zigbee uses the formular below to calculate lx (lux) values from the number values
54+
int lsens_value_lx = (int) 10^(lsens_value/10000)-1;
55+
Serial.printf("[Light Sensor] lux value: %d°C\r\n", lsens_value_lx);
56+
57+
// Update illuminance in light sensor EP
58+
zbLightSensor.setIlluminance(lsens_value); // use the number value here!
59+
60+
delay(1000); // reduce delay (in ms), if you want your device to react more quickly to changes in illuminance
61+
}
62+
}
63+
64+
/********************* Arduino functions **************************/
65+
void setup() {
66+
Serial.begin(115200);
67+
68+
// Optional: configure analog input
69+
analogSetAttenuation(ADC_11db); // set analog to digital converter (ADC) attenuation to 11 dB (up to ~3.3V input)
70+
analogReadResolution(12); // set analog read resolution to 12 bits (value range from 0 to 4095), 12 is default
71+
72+
// Init button for factory reset
73+
pinMode(button, INPUT_PULLUP);
74+
75+
// Optional: Set Zigbee device name and model
76+
zbLightSensor.setManufacturerAndModel("Espressif", "ZigbeeLightSensor");
77+
78+
// Optional: Set power source (choose between ZB_POWER_SOURCE_MAINS and ZB_POWER_SOURCE_BATTERY), defaults to unknown
79+
zbLightSensor.setPowerSource(ZB_POWER_SOURCE_MAINS);
80+
81+
// Set minimum and maximum illuminance number value (0 min and 50000 max equals to 0 lx - 100,000 lx)
82+
zbLightSensor.setMinMaxValue(0, 50000);
83+
84+
// Optional: Set tolerance for illuminance measurement
85+
zbLightSensor.setTolerance(1);
86+
87+
// Add endpoint to Zigbee Core
88+
Serial.println("Adding Zigbee light sensor endpoint to Zigbee Core");
89+
Zigbee.addEndpoint(&zbLightSensor);
90+
91+
Serial.println("Starting Zigbee...");
92+
// When all EPs are registered, start Zigbee in End Device mode
93+
if (!Zigbee.begin()) {
94+
Serial.println("Zigbee failed to start!");
95+
Serial.println("Rebooting...");
96+
ESP.restart();
97+
} else {
98+
Serial.println("Zigbee started successfully!");
99+
}
100+
Serial.println("Connecting to network");
101+
while (!Zigbee.connected()) {
102+
Serial.print(".");
103+
delay(100);
104+
}
105+
Serial.println();
106+
107+
// Start light sensor reading task
108+
xTaskCreate(light_sensor_value_update, "light_sensor_update", 2048, NULL, 10, NULL);
109+
110+
// Set reporting schedule for illuminance value measurement in seconds, must be called after Zigbee.begin()
111+
// min_interval and max_interval in seconds, delta
112+
// if min = 1 and max = 0, delta = 1000, reporting is sent when illuminance value changes by 1000, but at most once per second
113+
// if min = 0 and max = 10, delta = 1000, reporting is sent every 10 seconds or if illuminance value changes by 1000
114+
// if min = 0, max = 10 and delta = 0, reporting is sent every 10 seconds regardless of illuminance change
115+
// Note: On pairing with Zigbee Home Automation or Zigbee2MQTT the reporting schedule will most likely be overwritten with their default settings
116+
zbLightSensor.setReporting(1, 0, 1000);
117+
}
118+
119+
/********************* Main loop **************************/
120+
void loop() {
121+
// Checking button for factory reset
122+
if (digitalRead(button) == LOW) { // Push button pressed
123+
// Key debounce handling
124+
delay(100);
125+
int startTime = millis();
126+
while (digitalRead(button) == LOW) {
127+
delay(50);
128+
if ((millis() - startTime) > 3000) {
129+
// If key pressed for more than 3 secs, factory reset Zigbee and reboot
130+
Serial.println("Resetting Zigbee to factory and rebooting in 1s");
131+
delay(1000);
132+
Zigbee.factoryReset();
133+
}
134+
}
135+
// force report of illuminance when button is pressed
136+
zbLightSensor.reportIlluminance();
137+
}
138+
delay(100);
139+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"fqbn_append": "PartitionScheme=zigbee,ZigbeeMode=ed",
3+
"requires": [
4+
"CONFIG_SOC_IEEE802154_SUPPORTED=y",
5+
"CONFIG_ZB_ENABLED=y"
6+
]
7+
}

libraries/Zigbee/keywords.txt

+5
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ ZigbeeGateway KEYWORD1
2929
ZigbeeRangeExtender KEYWORD1
3030
ZigbeeVibrationSensor KEYWORD1
3131
ZigbeeWindowCovering KEYWORD1
32+
ZigbeeLightSensor KEYWORD1
3233

3334
# Other
3435
zigbee_role_t KEYWORD1
@@ -123,6 +124,10 @@ setHumidity KEYWORD2
123124
setHumidityReporting KEYWORD2
124125
reportHumidity KEYWORD2
125126

127+
# ZigbeeLightSensor
128+
setLightValue KEYWORD2
129+
reportLightValue KEYWORD2
130+
126131
# ZigbeeFlowSensor
127132
setFlow KEYWORD2
128133

libraries/Zigbee/src/Zigbee.h

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include "ep/ZigbeeAnalog.h"
1919
#include "ep/ZigbeeFlowSensor.h"
2020
#include "ep/ZigbeeOccupancySensor.h"
21+
#include "ep/ZigbeeLightSensor.h"
2122
#include "ep/ZigbeeCarbonDioxideSensor.h"
2223
#include "ep/ZigbeeContactSwitch.h"
2324
#include "ep/ZigbeeDoorWindowHandle.h"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include "ZigbeeLightSensor.h"
2+
#if CONFIG_ZB_ENABLED
3+
4+
ZigbeeLightSensor::ZigbeeLightSensor(uint8_t endpoint) : ZigbeeEP(endpoint) {
5+
_device_id = ESP_ZB_HA_LIGHT_SENSOR_DEVICE_ID;
6+
7+
esp_zb_light_sensor_cfg_t light_sensor_cfg = ESP_ZB_DEFAULT_LIGHT_SENSOR_CONFIG();
8+
_cluster_list = esp_zb_light_sensor_clusters_create(&light_sensor_cfg);
9+
10+
_ep_config = {
11+
.endpoint = _endpoint, .app_profile_id = ESP_ZB_AF_HA_PROFILE_ID, .app_device_id = ESP_ZB_HA_LIGHT_SENSOR_DEVICE_ID, .app_device_version = 0
12+
};
13+
}
14+
15+
static int16_t zb_int_to_s16(int value) {
16+
return (int16_t) value;
17+
}
18+
19+
void ZigbeeLightSensor::setMinMaxValue(int min, int max) {
20+
int16_t zb_min = zb_int_to_s16(min);
21+
int16_t zb_max = zb_int_to_s16(max);
22+
esp_zb_attribute_list_t *light_measure_cluster =
23+
esp_zb_cluster_list_get_cluster(_cluster_list, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
24+
esp_zb_cluster_update_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MIN_MEASURED_VALUE_ID, (void *)&zb_min);
25+
esp_zb_cluster_update_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MAX_MEASURED_VALUE_ID, (void *)&zb_max);
26+
}
27+
28+
void ZigbeeLightSensor::setTolerance(int tolerance) {
29+
uint16_t zb_tolerance = (uint16_t) tolerance;
30+
esp_zb_attribute_list_t *light_measure_cluster =
31+
esp_zb_cluster_list_get_cluster(_cluster_list, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
32+
esp_zb_illuminance_meas_cluster_add_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_TOLERANCE_ID, (void *)&zb_tolerance);
33+
}
34+
35+
void ZigbeeLightSensor::setReporting(uint16_t min_interval, uint16_t max_interval, int delta) {
36+
esp_zb_zcl_reporting_info_t reporting_info;
37+
memset(&reporting_info, 0, sizeof(esp_zb_zcl_reporting_info_t));
38+
reporting_info.direction = ESP_ZB_ZCL_CMD_DIRECTION_TO_SRV;
39+
reporting_info.ep = _endpoint;
40+
reporting_info.cluster_id = ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT;
41+
reporting_info.cluster_role = ESP_ZB_ZCL_CLUSTER_SERVER_ROLE;
42+
reporting_info.attr_id = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID;
43+
reporting_info.u.send_info.min_interval = min_interval;
44+
reporting_info.u.send_info.max_interval = max_interval;
45+
reporting_info.u.send_info.def_min_interval = min_interval;
46+
reporting_info.u.send_info.def_max_interval = max_interval;
47+
reporting_info.u.send_info.delta.u16 = (uint16_t) delta;
48+
reporting_info.dst.profile_id = ESP_ZB_AF_HA_PROFILE_ID;
49+
reporting_info.manuf_code = ESP_ZB_ZCL_ATTR_NON_MANUFACTURER_SPECIFIC;
50+
esp_zb_lock_acquire(portMAX_DELAY);
51+
esp_zb_zcl_update_reporting_info(&reporting_info);
52+
esp_zb_lock_release();
53+
}
54+
55+
void ZigbeeLightSensor::setIlluminance(int illuminanceValue) {
56+
int16_t zb_illuminanceValue = zb_int_to_s16(illuminanceValue);
57+
log_v("Updating Illuminance...");
58+
/* Update light sensor measured illuminance */
59+
log_d("Setting Illuminance to %d", zb_illuminanceValue);
60+
esp_zb_lock_acquire(portMAX_DELAY);
61+
esp_zb_zcl_set_attribute_val(
62+
_endpoint, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID, &zb_illuminanceValue, false
63+
);
64+
esp_zb_lock_release();
65+
}
66+
67+
void ZigbeeLightSensor::reportIlluminance() {
68+
/* Send report attributes command */
69+
esp_zb_zcl_report_attr_cmd_t report_attr_cmd;
70+
report_attr_cmd.address_mode = ESP_ZB_APS_ADDR_MODE_DST_ADDR_ENDP_NOT_PRESENT;
71+
report_attr_cmd.attributeID = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID;
72+
report_attr_cmd.direction = ESP_ZB_ZCL_CMD_DIRECTION_TO_CLI;
73+
report_attr_cmd.clusterID = ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT;
74+
report_attr_cmd.zcl_basic_cmd.src_endpoint = _endpoint;
75+
report_attr_cmd.manuf_code = ESP_ZB_ZCL_ATTR_NON_MANUFACTURER_SPECIFIC;
76+
77+
esp_zb_lock_acquire(portMAX_DELAY);
78+
esp_zb_zcl_report_attr_cmd_req(&report_attr_cmd);
79+
esp_zb_lock_release();
80+
log_v("Illuminance report sent");
81+
}
82+
83+
#endif // CONFIG_ZB_ENABLED
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/* Class of Zigbee Light sensor endpoint inherited from common EP class */
2+
3+
#pragma once
4+
5+
#include "soc/soc_caps.h"
6+
#include "sdkconfig.h"
7+
#if CONFIG_ZB_ENABLED
8+
9+
#include "ZigbeeEP.h"
10+
#include "ha/esp_zigbee_ha_standard.h"
11+
12+
/**/
13+
#define ESP_ZB_DEFAULT_LIGHT_SENSOR_CONFIG() \
14+
{ \
15+
.basic_cfg = \
16+
{ \
17+
.zcl_version = ESP_ZB_ZCL_BASIC_ZCL_VERSION_DEFAULT_VALUE, \
18+
.power_source = ESP_ZB_ZCL_BASIC_POWER_SOURCE_DEFAULT_VALUE, \
19+
}, \
20+
.identify_cfg = \
21+
{ \
22+
.identify_time = ESP_ZB_ZCL_IDENTIFY_IDENTIFY_TIME_DEFAULT_VALUE, \
23+
}, \
24+
.illuminance_cfg = \
25+
{ \
26+
.measured_value = ESP_ZB_ZCL_ILLUMINANCE_MEASUREMENT_LIGHT_SENSOR_TYPE_DEFAULT_VALUE, \
27+
/*not sure with next two values, but there are no*/ \
28+
/*ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MIN_MEASURED_VALUE_DEFAULT and*/ \
29+
/*ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MAX_MEASURED_VALUE_DEFAULT*/ \
30+
/*thats why I chose MIN_VALUE and MAX_VALUE*/ \
31+
.min_value = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MIN_MEASURED_VALUE_MIN_VALUE, \
32+
.max_value = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MAX_MEASURED_VALUE_MAX_VALUE, \
33+
}, \
34+
}
35+
36+
class ZigbeeLightSensor : public ZigbeeEP {
37+
public:
38+
ZigbeeLightSensor(uint8_t endpoint);
39+
~ZigbeeLightSensor() {}
40+
41+
// Set the light value
42+
void setIlluminance(int value);
43+
44+
// Set the min and max value for the light sensor
45+
void setMinMaxValue(int min, int max);
46+
47+
// Set the tolerance value for the light sensor
48+
void setTolerance(int tolerance);
49+
50+
// Set the reporting interval for light measurement in seconds and delta
51+
void setReporting(uint16_t min_interval, uint16_t max_interval, int delta);
52+
53+
// Report the light value
54+
void reportIlluminance();
55+
};
56+
57+
#endif // CONFIG_ZB_ENABLED

0 commit comments

Comments
 (0)