// Optional: set Zigbee device name and model
zbContactSwitch.setManufacturerAndModel("Espressif", "ZigbeeContactSwitch");
// Add endpoint to Zigbee Core
Zigbee.addEndpoint(&zbContactSwitch);
Serial.println("Starting Zigbee...");
// When all EPs are registered, start Zigbee in End Device mode
if (!Zigbee.begin()) {
Serial.println("Zigbee failed to start!");
Serial.println("Rebooting...");
ESP.restart();
} else {
Serial.println("Zigbee started successfully!");
}
Serial.println("Connecting to network");
while (!Zigbee.connected()) {
Serial.print(".");
delay(100);
}
Serial.println();
}
void loop() {
// Checking pin for contact change
static bool contact = false;
if (digitalRead(sensor_pin) == HIGH && !contact) {
// Update contact sensor value
zbContactSwitch.setOpen();
contact = true;
} else if (digitalRead(sensor_pin) == LOW && contact) {
zbContactSwitch.setClosed();
contact = false;
}
// Checking button for factory reset
if (digitalRead(button) == LOW) { // Push button pressed
// Key debounce handling
delay(100);
int startTime = millis();
while (digitalRead(button) == LOW) {
delay(50);
if ((millis() - startTime) > 3000) {
// If key pressed for more than 3secs, factory reset Zigbee and reboot
Serial.println("Resetting Zigbee to factory and rebooting in 1s.");
delay(1000);
Zigbee.factoryReset();
}
}
}
delay(100);
}
add adc code for battery to this code
Assistant
Here's the modified code with ADC battery monitoring added. I'll include the necessary changes to read the battery voltage and report it through the Zigbee network:
cpp
User
Compilation error: 'esp_adc_cal_characteristics_t' does not name a type
Assistant
The error occurs because the esp_adc_cal.h header might not be included correctly or the ADC calibration types aren't properly defined. Let's modify the code to use a simpler approach for battery monitoring that should work without requiring the ADC calibration structure. Here's the updated version:
cpp
User
error: 'class ZigbeeContactSwitch' has no member named 'setBatteryLevel'
81 | zbContactSwitch.setBatteryLevel(batteryPercent * 2);
Assistant
The error occurs because the ZigbeeContactSwitch class doesn't have a setBatteryLevel method. To properly report battery level in a Zigbee device, we need to use the Power Configuration cluster. Here's how to modify the code to properly implement battery reporting:
#ifndef ZIGBEE_MODE_ED
#error "Zigbee end device mode is not selected in Tools->Zigbee mode"
#endif
#include "Zigbee.h"
#include "esp_adc_cal.h" // For ADC calibration
/* Zigbee contact sensor configuration */
#define CONTACT_SWITCH_ENDPOINT_NUMBER 10
#define BATTERY_PIN 35 // GPIO35 is commonly used for ADC1_CH7 on ESP32
#define BATTERY_SAMPLES 10 // Number of samples to average
#define BATTERY_VOLTAGE_DIVIDER_RATIO 2.0 // Adjust based on your voltage divider (R1+R2)/R2
uint8_t button = BOOT_PIN;
uint8_t sensor_pin = 4;
ZigbeeContactSwitch zbContactSwitch = ZigbeeContactSwitch(CONTACT_SWITCH_ENDPOINT_NUMBER);
// ADC calibration
esp_adc_cal_characteristics_t adc_chars;
void setup() {
Serial.begin(115200);
// Init button + switch
pinMode(button, INPUT_PULLUP);
pinMode(sensor_pin, INPUT_PULLUP);
// Configure ADC for battery monitoring
adc1_config_width(ADC_WIDTH_BIT_12); // Set ADC width to 12 bits
adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_11); // Configure attenuation for GPIO35 (ADC1_CH7)
// Characterize ADC
esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 0, &adc_chars);
// Optional: set Zigbee device name and model
zbContactSwitch.setManufacturerAndModel("Espressif", "ZigbeeContactSwitch");
// Add endpoint to Zigbee Core
Zigbee.addEndpoint(&zbContactSwitch);
Serial.println("Starting Zigbee...");
// When all EPs are registered, start Zigbee in End Device mode
if (!Zigbee.begin()) {
Serial.println("Zigbee failed to start!");
Serial.println("Rebooting...");
ESP.restart();
} else {
Serial.println("Zigbee started successfully!");
}
Serial.println("Connecting to network");
while (!Zigbee.connected()) {
Serial.print(".");
delay(100);
}
Serial.println();
}
float readBatteryVoltage() {
uint32_t adc_reading = 0;
// Take multiple samples and average
for (int i = 0; i < BATTERY_SAMPLES; i++) {
adc_reading += adc1_get_raw(ADC1_CHANNEL_7);
delay(10);
}
adc_reading /= BATTERY_SAMPLES;
// Convert to voltage (in mV)
uint32_t voltage = esp_adc_cal_raw_to_voltage(adc_reading, &adc_chars);
// Apply voltage divider ratio and convert to volts
return (voltage / 1000.0) * BATTERY_VOLTAGE_DIVIDER_RATIO;
}
void reportBatteryLevel() {
float voltage = readBatteryVoltage();
// Convert voltage to percentage (adjust these values based on your battery characteristics)
// Example: assuming 3.0V = 0%, 4.2V = 100% for Li-ion
int batteryPercent = constrain((voltage - 3.0) / (4.2 - 3.0) * 100, 0, 100);
// Report battery level (0-200 where 100 = 50%)
zbContactSwitch.setBatteryLevel(batteryPercent * 2);
Serial.printf("Battery voltage: %.2fV, Level: %d%%\n", voltage, batteryPercent);
}
void loop() {
// Checking pin for contact change
static bool contact = false;
if (digitalRead(sensor_pin) == HIGH && !contact) {
// Update contact sensor value
zbContactSwitch.setOpen();
contact = true;
} else if (digitalRead(sensor_pin) == LOW && contact) {
zbContactSwitch.setClosed();
contact = false;
}
// Report battery level periodically (e.g., every 10 minutes)
static unsigned long lastBatteryReport = 0;
if (millis() - lastBatteryReport > 600000) { // 10 minutes
reportBatteryLevel();
lastBatteryReport = millis();
}
// Checking button for factory reset
if (digitalRead(button) == LOW) { // Push button pressed
// Key debounce handling
delay(100);
int startTime = millis();
while (digitalRead(button) == LOW) {
delay(50);
if ((millis() - startTime) > 3000) {
// If key pressed for more than 3secs, factory reset Zigbee and reboot
Serial.println("Resetting Zigbee to factory and rebooting in 1s.");
delay(1000);
Zigbee.factoryReset();
}
}
}
delay(100);
}
Important Notes:
Hardware Setup:
You'll need to connect your battery to GPIO35 (or another ADC pin) through a voltage divider to ensure the voltage is within the ESP32's ADC range (0-3.3V).
Adjust BATTERY_VOLTAGE_DIVIDER_RATIO based on your actual voltage divider circuit.
Battery Reporting:
The code reports battery level as a percentage (0-100) converted to the Zigbee standard (0-200 where 100 = 50%).
The voltage-to-percentage conversion assumes a Li-ion battery (3.0V-4.2V). Adjust these values for your specific battery chemistry.
Power Considerations:
For battery-powered devices, you might want to increase the delay between battery reports to save power.
Consider putting the device into deep sleep between readings if power consumption is critical.
Calibration:
The code uses ESP32's ADC calibration features for more accurate readings.
For best results, you should calibrate your specific device's ADC characteristics.
ZigbeeContactSwitch Class:
The code assumes your ZigbeeContactSwitch class has a setBatteryLevel() method. If it doesn't, you'll need to implement battery reporting through the appropriate Zigbee cluster.
#ifndef ZIGBEE_MODE_ED
#error "Zigbee end device mode is not selected in Tools->Zigbee mode"
#endif
#include "Zigbee.h"
#include "driver/adc.h" // Basic ADC driver
/* Zigbee contact sensor configuration */
#define CONTACT_SWITCH_ENDPOINT_NUMBER 10
#define BATTERY_PIN ADC1_CHANNEL_7 // GPIO35 is ADC1_CHANNEL_7
#define BATTERY_SAMPLES 10 // Number of samples to average
#define BATTERY_VOLTAGE_DIVIDER_RATIO 2.0 // Adjust based on your voltage divider (R1+R2)/R2
#define DEFAULT_VREF 1100 // Default reference voltage in mV (typical for ESP32)
uint8_t button = BOOT_PIN;
uint8_t sensor_pin = 4;
ZigbeeContactSwitch zbContactSwitch = ZigbeeContactSwitch(CONTACT_SWITCH_ENDPOINT_NUMBER);
void setup() {
Serial.begin(115200);
// Init button + switch
pinMode(button, INPUT_PULLUP);
pinMode(sensor_pin, INPUT_PULLUP);
// Configure ADC for battery monitoring
adc1_config_width(ADC_WIDTH_BIT_12); // Set ADC width to 12 bits
adc1_config_channel_atten(BATTERY_PIN, ADC_ATTEN_DB_11); // 11dB attenuation (up to ~3.3V)
// Optional: set Zigbee device name and model
zbContactSwitch.setManufacturerAndModel("Espressif", "ZigbeeContactSwitch");
// Add endpoint to Zigbee Core
Zigbee.addEndpoint(&zbContactSwitch);
Serial.println("Starting Zigbee...");
// When all EPs are registered, start Zigbee in End Device mode
if (!Zigbee.begin()) {
Serial.println("Zigbee failed to start!");
Serial.println("Rebooting...");
ESP.restart();
} else {
Serial.println("Zigbee started successfully!");
}
Serial.println("Connecting to network");
while (!Zigbee.connected()) {
Serial.print(".");
delay(100);
}
Serial.println();
}
float readBatteryVoltage() {
uint32_t adc_reading = 0;
// Take multiple samples and average
for (int i = 0; i < BATTERY_SAMPLES; i++) {
adc_reading += adc1_get_raw(BATTERY_PIN);
delay(10);
}
adc_reading /= BATTERY_SAMPLES;
// Convert to voltage (in mV) using default Vref
// Formula: voltage = (adc_reading * Vref) / (2^ADC_WIDTH - 1)
float voltage = (adc_reading * DEFAULT_VREF) / 4095.0; // 4095 = 2^12 - 1
// Apply voltage divider ratio and convert to volts
return (voltage / 1000.0) * BATTERY_VOLTAGE_DIVIDER_RATIO;
}
void reportBatteryLevel() {
float voltage = readBatteryVoltage();
// Convert voltage to percentage (adjust these values based on your battery characteristics)
// Example: assuming 3.0V = 0%, 4.2V = 100% for Li-ion
int batteryPercent = constrain((voltage - 3.0) / (4.2 - 3.0) * 100, 0, 100);
// Report battery level (0-200 where 100 = 50%)
zbContactSwitch.setBatteryLevel(batteryPercent * 2);
Serial.printf("Battery voltage: %.2fV, Level: %d%%\n", voltage, batteryPercent);
}
void loop() {
// Checking pin for contact change
static bool contact = false;
if (digitalRead(sensor_pin) == HIGH && !contact) {
// Update contact sensor value
zbContactSwitch.setOpen();
contact = true;
} else if (digitalRead(sensor_pin) == LOW && contact) {
zbContactSwitch.setClosed();
contact = false;
}
// Report battery level periodically (e.g., every 10 minutes)
static unsigned long lastBatteryReport = 0;
if (millis() - lastBatteryReport > 600000) { // 10 minutes
reportBatteryLevel();
lastBatteryReport = millis();
}
// Checking button for factory reset
if (digitalRead(button) == LOW) { // Push button pressed
// Key debounce handling
delay(100);
int startTime = millis();
while (digitalRead(button) == LOW) {
delay(50);
if ((millis() - startTime) > 3000) {
// If key pressed for more than 3secs, factory reset Zigbee and reboot
Serial.println("Resetting Zigbee to factory and rebooting in 1s.");
delay(1000);
Zigbee.factoryReset();
}
}
}
delay(100);
}
Key Changes:
Simplified ADC Implementation:
Removed dependency on esp_adc_cal_characteristics_t
Using basic ADC functions with a default reference voltage
Changed BATTERY_PIN definition to use the channel number directly
Voltage Calculation:
Using a simpler voltage calculation with a default reference voltage
The formula (adc_reading * DEFAULT_VREF) / 4095.0 converts the ADC reading to voltage
Compatibility:
This version should work with standard ESP32 Arduino core installations
Uses only the basic ADC driver functions that are widely available
Additional Notes:
Accuracy:
For better accuracy, you might want to:
Measure your actual Vref voltage and update DEFAULT_VREF
Perform a two-point calibration for your specific device
Use a more precise voltage divider
Power Consumption:
The ADC is configured with 11dB attenuation which provides better accuracy but consumes more power
For battery-powered devices, you might want to use lower attenuation when possible
Battery Reporting:
The battery level is reported every 10 minutes (600000 ms)
Adjust this interval based on your power requirements
This version should compile without the ADC calibration error while still providing reasonable battery voltage measurements.
#ifndef ZIGBEE_MODE_ED
#error "Zigbee end device mode is not selected in Tools->Zigbee mode"
#endif
#include "Zigbee.h"
#include "driver/adc.h" // Basic ADC driver
/* Zigbee contact sensor configuration */
#define CONTACT_SWITCH_ENDPOINT_NUMBER 10
#define BATTERY_PIN ADC1_CHANNEL_7 // GPIO35 is ADC1_CHANNEL_7
#define BATTERY_SAMPLES 10 // Number of samples to average
#define BATTERY_VOLTAGE_DIVIDER_RATIO 2.0 // Adjust based on your voltage divider (R1+R2)/R2
#define DEFAULT_VREF 1100 // Default reference voltage in mV (typical for ESP32)
uint8_t button = BOOT_PIN;
uint8_t sensor_pin = 4;
// Forward declaration
class BatteryPowerConfigurationCluster;
class ZigbeeContactSwitchWithBattery : public ZigbeeContactSwitch {
public:
ZigbeeContactSwitchWithBattery(uint8_t endpoint) : ZigbeeContactSwitch(endpoint) {
// Add Power Configuration cluster to the endpoint
addCluster(new BatteryPowerConfigurationCluster());
}
class BatteryPowerConfigurationCluster : public Cluster {
public:
BatteryPowerConfigurationCluster() : Cluster(0x0001) {} // Power Configuration cluster ID
void configure() override {
// Configure attributes for the Power Configuration cluster
addAttribute(new Attribute(0x0020, ZCL_UINT8_TYPE)); // Battery Percentage Remaining
addAttribute(new Attribute(0x0021, ZCL_UINT8_TYPE)); // Battery Voltage
}
void setBatteryLevel(uint8_t level) {
// Set battery percentage (0-100)
setAttributeValue(0x0020, level);
}
void setBatteryVoltage(uint8_t voltage) {
// Set battery voltage (in 1/10ths of a volt)
setAttributeValue(0x0021, voltage);
}
};
void setBatteryLevel(uint8_t level) {
// Get the Power Configuration cluster
BatteryPowerConfigurationCluster* powerCluster = static_cast<BatteryPowerConfigurationCluster*>(getCluster(0x0001));
if (powerCluster) {
powerCluster->setBatteryLevel(level);
}
}
void setBatteryVoltage(uint8_t voltage) {
// Get the Power Configuration cluster
BatteryPowerConfigurationCluster* powerCluster = static_cast<BatteryPowerConfigurationCluster*>(getCluster(0x0001));
if (powerCluster) {
powerCluster->setBatteryVoltage(voltage);
}
}
};
ZigbeeContactSwitchWithBattery zbContactSwitch(CONTACT_SWITCH_ENDPOINT_NUMBER);
void setup() {
Serial.begin(115200);
// Init button + switch
pinMode(button, INPUT_PULLUP);
pinMode(sensor_pin, INPUT_PULLUP);
// Configure ADC for battery monitoring
adc1_config_width(ADC_WIDTH_BIT_12); // Set ADC width to 12 bits
adc1_config_channel_atten(BATTERY_PIN, ADC_ATTEN_DB_11); // 11dB attenuation (up to ~3.3V)
// Optional: set Zigbee device name and model
zbContactSwitch.setManufacturerAndModel("Espressif", "ZigbeeContactSwitch");
// Add endpoint to Zigbee Core
Zigbee.addEndpoint(&zbContactSwitch);
Serial.println("Starting Zigbee...");
// When all EPs are registered, start Zigbee in End Device mode
if (!Zigbee.begin()) {
Serial.println("Zigbee failed to start!");
Serial.println("Rebooting...");
ESP.restart();
} else {
Serial.println("Zigbee started successfully!");
}
Serial.println("Connecting to network");
while (!Zigbee.connected()) {
Serial.print(".");
delay(100);
}
Serial.println();
}
float readBatteryVoltage() {
uint32_t adc_reading = 0;
// Take multiple samples and average
for (int i = 0; i < BATTERY_SAMPLES; i++) {
adc_reading += adc1_get_raw(BATTERY_PIN);
delay(10);
}
adc_reading /= BATTERY_SAMPLES;
// Convert to voltage (in mV) using default Vref
float voltage = (adc_reading * DEFAULT_VREF) / 4095.0; // 4095 = 2^12 - 1
// Apply voltage divider ratio and convert to volts
return (voltage / 1000.0) * BATTERY_VOLTAGE_DIVIDER_RATIO;
}
void reportBatteryLevel() {
float voltage = readBatteryVoltage();
// Convert voltage to percentage (adjust these values based on your battery characteristics)
int batteryPercent = constrain((voltage - 3.0) / (4.2 - 3.0) * 100, 0, 100);
// Report battery level (0-100%)
zbContactSwitch.setBatteryLevel(batteryPercent);
// Report battery voltage (in 1/10ths of a volt)
zbContactSwitch.setBatteryVoltage(voltage * 10);
Serial.printf("Battery voltage: %.2fV, Level: %d%%\n", voltage, batteryPercent);
}
void loop() {
// Checking pin for contact change
static bool contact = false;
if (digitalRead(sensor_pin) == HIGH && !contact) {
// Update contact sensor value
zbContactSwitch.setOpen();
contact = true;
} else if (digitalRead(sensor_pin) == LOW && contact) {
zbContactSwitch.setClosed();
contact = false;
}
// Report battery level periodically (e.g., every 10 minutes)
static unsigned long lastBatteryReport = 0;
if (millis() - lastBatteryReport > 600000) { // 10 minutes
reportBatteryLevel();
lastBatteryReport = millis();
}
// Checking button for factory reset
if (digitalRead(button) == LOW) { // Push button pressed
// Key debounce handling
delay(100);
int startTime = millis();
while (digitalRead(button) == LOW) {
delay(50);
if ((millis() - startTime) > 3000) {
// If key pressed for more than 3secs, factory reset Zigbee and reboot
Serial.println("Resetting Zigbee to factory and rebooting in 1s.");
delay(1000);
Zigbee.factoryReset();
}
}
}
delay(100);
}
Key Changes:
Created a Custom Class:
Created ZigbeeContactSwitchWithBattery that inherits from ZigbeeContactSwitch
Added a nested BatteryPowerConfigurationCluster class that implements the Power Configuration cluster (0x0001)
Implemented Battery Reporting:
Added methods to set battery level (percentage) and voltage
The Power Configuration cluster includes standard attributes for battery reporting
Proper Zigbee Implementation:
Uses the standard Zigbee Power Configuration cluster (0x0001)
Implements the battery percentage remaining (0x0020) and battery voltage (0x0021) attributes
Usage:
The setBatteryLevel and setBatteryVoltage methods are now properly implemented
Battery level is reported as a percentage (0-100)
Battery voltage is reported in 1/10ths of a volt
This implementation follows the Zigbee specification for battery reporting and should work with standard Zigbee hubs and controllers. The battery information will be available through the Power Configuration cluster, which is the standard way to report battery status in Zigbee devices.