### Real World Example: Setup function using Preferences Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/tutorials/preferences.html An example setup() function that initializes system configuration based on whether it's the first run or a subsequent run, using Preferences to store and retrieve settings. ```cpp #include #define RW_MODE false #define RO_MODE true Preferences stcPrefs; void setup() { // not the complete setup(), but in setup(), include this... stcPrefs.begin("STCPrefs", RO_MODE); // Open our namespace (or create it // if it doesn't exist) in RO mode. bool tpInit = stcPrefs.isKey("nvsInit"); // Test for the existence // of the "already initialized" key. if (tpInit == false) { // If tpInit is 'false', the key "nvsInit" does not yet exist therefore this // must be our first-time run. We need to set up our Preferences namespace keys. So... stcPrefs.end(); // close the namespace in RO mode and... stcPrefs.begin("STCPrefs", RW_MODE); // reopen it in RW mode. // The .begin() method created the "STCPrefs" namespace and since this is our // first-time run we will create // our keys and store the initial "factory default" values. stcPrefs.putUChar("curBright", 10); stcPrefs.putString("talChan", "one"); stcPrefs.putLong("talMax", -220226); stcPrefs.putBool("ctMde", true); stcPrefs.putBool("nvsInit", true); // Create the "already initialized" // key and store a value. // The "factory defaults" are created and stored so... stcPrefs.end(); // Close the namespace in RW mode and... stcPrefs.begin("STCPrefs", RO_MODE); // reopen it in RO mode so the setup code // outside this first-time run 'if' block // can retrieve the run-time values // from the "STCPrefs" namespace. } // Retrieve the operational parameters from the namespace // and save them into their run-time variables. currentBrightness = stcPrefs.getUChar("curBright"); // tChannel = stcPrefs.getString("talChan"); // The LHS variables were defined tChanMax = stcPrefs.getLong("talMax"); // earlier in the sketch. ctMode = stcPrefs.getBool("ctMde"); // // All done. Last run state (or the factory default) is now restored. stcPrefs.end(); // Close our preferences namespace. // Carry on with the rest of your setup code... // When the sketch is running, it updates any changes to an operational parameter // to the appropriate key-value pair in the namespace. } ``` -------------------------------- ### Option 1: Using Arduino setup() and loop() Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/esp-idf_component.html Example main.cpp file formatted for using Arduino's setup() and loop() functions. ```cpp //file: main.cpp #include "Arduino.h" void setup(){ Serial.begin(115200); while(!Serial){ ; // wait for serial port to connect } } void loop(){ Serial.println("loop"); delay(1000); } ``` -------------------------------- ### Example ci.yml for Wi-Fi support Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html This ci.yml configuration specifies that an example requires Wi-Fi support to run. ```yaml requires: - CONFIG_SOC_WIFI_SUPPORTED=y ``` -------------------------------- ### Wi-Fi STA Example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/api/wifi.html This code example demonstrates connecting an ESP32 to a Wi-Fi network in Station mode, sending data to a ThingSpeak channel, and reading data from it. It includes setup for Wi-Fi connection, sending data via GET requests to the ThingSpeak API, and receiving data. The comments provide detailed instructions on setting up a ThingSpeak channel and obtaining API keys. ```c++ /* Go to thingspeak.com and create an account if you don't have one already. After logging in, click on the "New Channel" button to create a new channel for your data. This is where your data will be stored and displayed. Fill in the Name, Description, and other fields for your channel as desired, then click the "Save Channel" button. Take note of the "Write API Key" located in the "API keys" tab, this is the key you will use to send data to your channel. Replace the channelID from tab "Channel Settings" and privateKey with "Read API Keys" from "API Keys" tab. Replace the host variable with the thingspeak server hostname "api.thingspeak.com" Upload the sketch to your ESP32 board and make sure that the board is connected to the internet. The ESP32 should now send data to your Thingspeak channel at the intervals specified by the loop function. Go to the channel view page on thingspeak and check the "Field1" for the new incoming data. You can use the data visualization and analysis tools provided by Thingspeak to display and process your data in various ways. Please note, that Thingspeak accepts only integer values. You can later check the values at https://thingspeak.com/channels/2005329 Please note that this public channel can be accessed by anyone and it is possible that more people will write their values. */ #include #include const char *ssid = "your-ssid"; // Change this to your WiFi SSID const char *password = "your-password"; // Change this to your WiFi password const char *host = "api.thingspeak.com"; // This should not be changed const int httpPort = 80; // This should not be changed const String channelID = "2005329"; // Change this to your channel ID const String writeApiKey = "V6YOTILH9I7D51F9"; // Change this to your Write API key const String readApiKey = "34W6LGLIFXD56MPM"; // Change this to your Read API key // The default example accepts one data filed named "field1" // For your own server you can ofcourse create more of them. int field1 = 0; int numberOfResults = 3; // Number of results to be read int fieldNumber = 1; // Field number which will be read out void setup() { Serial.begin(115200); // We start by connecting to a WiFi network Serial.println(); Serial.println("******************************************************"); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void readResponse(NetworkClient *client) { unsigned long timeout = millis(); while (client->available() == 0) { if (millis() - timeout > 5000) { Serial.println(">>> Client Timeout !"); client->stop(); return; } } // Read all the lines of the reply from server and print them to Serial while (client->available()) { String line = client->readStringUntil('\r'); Serial.print(line); } Serial.printf("\nClosing connection\n\n"); } void loop() { NetworkClient client; String footer = String(" HTTP/1.1\r\n") + "Host: " + String(host) + "\r\n" + "Connection: close\r\n\r\n"; // WRITE -------------------------------------------------------------------------------------------- if (!client.connect(host, httpPort)) { return; } client.print("GET /update?api_key=" + writeApiKey + "&field1=" + field1 + footer); readResponse(&client); // READ -------------------------------------------------------------------------------------------- String readRequest = "GET /channels/" + channelID + "/fields/" + fieldNumber + ".json?results=" + numberOfResults + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"; if (!client.connect(host, httpPort)) { return; } client.print(readRequest); readResponse(&client); // ------------------------------------------------------------------------------------------------- ++field1; delay(10000); } ``` -------------------------------- ### Example: Get and store preference type Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/tutorials/preferences.html Demonstrates how to get the `PreferenceType` for a key and store it in a variable. ```cpp PreferenceType whatType = getType("myKey"); ``` -------------------------------- ### Basic OpenThread Setup using Classes API Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/openthread/openthread.html Demonstrates how to initialize the OpenThread stack, create and configure a dataset, and start the Thread network using the Classes API. ```cpp #include void setup() { Serial.begin(115200); // Initialize OpenThread stack OpenThread::begin(); // Wait for OpenThread to be ready while (!OThread) { delay(100); } // Create and configure dataset DataSet dataset; dataset.initNew(); dataset.setNetworkName("MyThreadNetwork"); dataset.setChannel(15); // Apply dataset and start network OThread.commitDataSet(dataset); OThread.start(); OThread.networkInterfaceUp(); // Print network information OpenThread::otPrintNetworkInformation(Serial); } ``` -------------------------------- ### Header Example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html An example of the required header for all source files in a contribution, including the example name and license information. ```c /* Wi-Fi FTM Initiator Arduino Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ ``` -------------------------------- ### Example: Build UART Test for ESP32-C3 Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html An example of how to build the 'uart' test for the 'esp32c3' target. ```bash ./.github/scripts/tests_build.sh -s uart -t esp32c3 ``` -------------------------------- ### Example CI YAML File for the wifi Test Suite Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html This example demonstrates the structure and fields of a ci.yml file for the 'wifi' test suite, including tags, FQBNs for different targets, platform configurations, required configurations, and more. ```yaml tags: - wifi_router fqbn: esp32: - espressif:esp32:esp32:PSRAM=enabled,PartitionScheme=huge_app,FlashMode=dio - espressif:esp32:esp32:PSRAM=disabled,PartitionScheme=huge_app,FlashMode=dio esp32s2: - espressif:esp32:esp32s2:PSRAM=enabled,PartitionScheme=huge_app,FlashMode=dio - espressif:esp32:esp32s2:PSRAM=disabled,PartitionScheme=huge_app,FlashMode=dio esp32s3: - espressif:esp32:esp32s3:PSRAM=opi,USBMode=default,PartitionScheme=huge_app,FlashMode=qio - espressif:esp32:esp32s3:PSRAM=disabled,USBMode=default,PartitionScheme=huge_app,FlashMode=qio - espressif:esp32:esp32s3:PSRAM=enabled,USBMode=default,PartitionScheme=huge_app,FlashMode=qio platforms: qemu: false requires_any: - CONFIG_SOC_WIFI_SUPPORTED=y - CONFIG_ESP_WIFI_REMOTE_ENABLED=y ``` -------------------------------- ### Example Usage Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/api/insights.html Example code to get started with Insights, including WiFi connection and Insights initialization. ```c++ #include #include "Insights.h" #include "WiFi.h" const char insights_auth_key[] = ""; #define WIFI_SSID "" #define WIFI_PASSPHRASE "" void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSPHRASE); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); if (!Insights.begin(insights_auth_key)) { return; } Serial.println("========================================="); Serial.printf("ESP Insights enabled Node ID %s\n", Insights.nodeID()); Serial.println("========================================="); } void loop() { delay(1000); } ``` -------------------------------- ### Install pre-commit dependencies Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html Installs the necessary dependencies to run pre-commit hooks locally. ```bash pip install -U -r tools/pre-commit/requirements.txt ``` -------------------------------- ### startConsole Example Usage Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/openthread/openthread_cli.html An example demonstrating how to start the OpenThread CLI console with a specific stream, echo setting, and prompt. ```cpp OThreadCLI.startConsole(Serial, true, "ot> "); ``` -------------------------------- ### Example: Run UART Test for ESP32-C3 Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html An example of how to run the 'uart' test on the 'esp32c3' target after it has been built. ```bash ./.github/scripts/tests_run.sh -s uart -t esp32c3 ``` -------------------------------- ### Running a test using QEMU Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html Example command to run the 'uart' test using QEMU, setting the QEMU_PATH environment variable. ```bash QEMU_PATH= ./.github/scripts/tests_run.sh -s uart -t esp32c3 -Q ``` -------------------------------- ### ESP-NOW Example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/api/espnow.html This example demonstrates how to initialize and use ESP-NOW for communication between ESP devices. It includes setting up the Wi-Fi mode, printing the MAC address, starting ESP-NOW, and handling data transmission via serial communication. ```cpp while (!(WiFi.STA.started() || WiFi.AP.started())) { delay(100); } Serial.print("MAC Address: "); Serial.println(ESPNOW_WIFI_MODE == WIFI_AP ? WiFi.softAPmacAddress() : WiFi.macAddress()); // Start the ESP-NOW communication Serial.println("ESP-NOW communication starting..."); NowSerial.begin(115200); Serial.printf("ESP-NOW version: %d, max data length: %d\n", ESP_NOW.getVersion(), ESP_NOW.getMaxDataLen()); Serial.println("You can now send data to the peer device using the Serial Monitor.\n"); } void loop() { while (NowSerial.available()) { Serial.write(NowSerial.read()); } while (Serial.available() && NowSerial.availableForWrite()) { if (NowSerial.write(Serial.read()) <= 0) { Serial.println("Failed to send data"); break; } } delay(1); } ``` -------------------------------- ### getInstalledOpenLimitTilt Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/matter/ep_window_covering.html Gets the installed open limit for tilt. ```c uint16_t getInstalledOpenLimitTilt(); ``` -------------------------------- ### Create test directory structure Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html Example of creating the necessary directory structure for a multi-device test, using 'wifi_ap' as a reference. ```bash mkdir -p tests/validation/wifi_ap/ap mkdir -p tests/validation/wifi_ap/client ``` -------------------------------- ### Zigbee Thermostat Example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/zigbee/ep_thermostat.html This C++ code demonstrates a basic Zigbee thermostat implementation. It includes setup for receiving temperature data from a sensor, configuring thermostat parameters, and integrating with the Zigbee network as a coordinator. The code also shows how to handle optional features like time synchronization. ```cpp // Copyright 2024 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @brief This example demonstrates simple Zigbee thermostat. * * The example demonstrates how to use Zigbee library to get data from temperature * sensor end device and act as an thermostat. * The temperature sensor is a Zigbee end device, which is controlled by a Zigbee coordinator (thermostat). * * Proper Zigbee mode must be selected in Tools->Zigbee mode * and also the correct partition scheme must be selected in Tools->Partition Scheme. * * Please check the README.md for instructions and more detailed description. * * Created by Jan Procházka (https://github.com/P-R-O-C-H-Y/) */ #include #ifndef ZIGBEE_MODE_ZCZR #error "Zigbee coordinator mode is not selected in Tools->Zigbee mode" #endif #include "Zigbee.h" /* Zigbee thermostat configuration */ #define THERMOSTAT_ENDPOINT_NUMBER 1 #define USE_RECEIVE_TEMP_WITH_SOURCE 1 uint8_t button = BOOT_PIN; ZigbeeThermostat zbThermostat = ZigbeeThermostat(THERMOSTAT_ENDPOINT_NUMBER); // Save temperature sensor data float sensor_temp; float sensor_max_temp; float sensor_min_temp; float sensor_tolerance; struct tm timeinfo = {}; // Time structure for Time cluster /****************** Temperature sensor handling *******************/ #if USE_RECEIVE_TEMP_WITH_SOURCE == 0 void receiveSensorTemp(float temperature) { Serial.printf("Temperature sensor value: %.2f°C\n", temperature); sensor_temp = temperature; } #else void receiveSensorTempWithSource(float temperature, uint8_t src_endpoint, esp_zb_zcl_addr_t src_address) { if (src_address.addr_type == ESP_ZB_ZCL_ADDR_TYPE_SHORT) { Serial.printf("Temperature sensor value: %.2f°C from endpoint %u, address 0x%04x\n", temperature, src_endpoint, src_address.u.short_addr); } else { Serial.printf( "Temperature sensor value: %.2f°C from endpoint %u, address %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", temperature, src_endpoint, src_address.u.ieee_addr[7], src_address.u.ieee_addr[6], src_address.u.ieee_addr[5], src_address.u.ieee_addr[4], src_address.u.ieee_addr[3], src_address.u.ieee_addr[2], src_address.u.ieee_addr[1], src_address.u.ieee_addr[0] ); } sensor_temp = temperature; } #endif void receiveSensorConfig(float min_temp, float max_temp, float tolerance) { Serial.printf("Temperature sensor config: min %.2f°C, max %.2f°C, tolerance %.2f°C\n", min_temp, max_temp, tolerance); sensor_min_temp = min_temp; sensor_max_temp = max_temp; sensor_tolerance = tolerance; } /********************* Arduino functions **************************/ void setup() { Serial.begin(115200); // Init button switch pinMode(button, INPUT_PULLUP); // Set callback function for receiving temperature from sensor - Use only one option #if USE_RECEIVE_TEMP_WITH_SOURCE == 0 zbThermostat.onTempReceive(receiveSensorTemp); // If you bound only one sensor or you don't need to know the source of the temperature #else zbThermostat.onTempReceiveWithSource(receiveSensorTempWithSource); #endif // Set callback function for receiving sensor configuration zbThermostat.onTempConfigReceive(receiveSensorConfig); //Optional: set Zigbee device name and model zbThermostat.setManufacturerAndModel("Espressif", "ZigbeeThermostat"); //Optional Time cluster configuration //example time January 13, 2025 13:30:30 CET timeinfo.tm_year = 2025 - 1900; // = 2025 timeinfo.tm_mon = 0; // January timeinfo.tm_mday = 13; // 13th timeinfo.tm_hour = 12; // 12 hours - 1 hour (CET) timeinfo.tm_min = 30; // 30 minutes timeinfo.tm_sec = 30; // 30 seconds timeinfo.tm_isdst = -1; // Set time and gmt offset (timezone in seconds -> CET = +3600 seconds) zbThermostat.addTimeCluster(timeinfo, 3600); //Add endpoint to Zigbee Core Zigbee.addEndpoint(&zbThermostat); //Open network for 180 seconds after boot Zigbee.setRebootOpenNetwork(180); // When all EPs are registered, start Zigbee with ZIGBEE_COORDINATOR mode if (!Zigbee.begin(ZIGBEE_COORDINATOR)) { Serial.println("Zigbee failed to start!"); Serial.println("Rebooting..."); ESP.restart(); } Serial.println("Waiting for Temperature sensor to bound to the thermostat"); while (!zbThermostat.bound()) { Serial.printf("."); delay(500); } Serial.println(); ``` -------------------------------- ### Basic Light Implementation Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/zigbee/ep_light.html This example demonstrates how to use the Zigbee library to create an end device light bulb that is controlled by a Zigbee coordinator. It includes setup for the Zigbee light, LED control, button handling for factory reset, and network connection. ```C++ // Copyright 2024 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @brief This example demonstrates simple Zigbee light bulb. * * The example demonstrates how to use Zigbee library to create a end device light bulb. * The light bulb is a Zigbee end device, which is controlled by a Zigbee coordinator. * * Proper Zigbee mode must be selected in Tools->Zigbee mode * and also the correct partition scheme must be selected in Tools->Partition Scheme. * * Please check the README.md for instructions and more detailed description. * * Created by Jan Procházka (https://github.com/P-R-O-C-H-Y/) */ #include #ifndef ZIGBEE_MODE_ED #error "Zigbee end device mode is not selected in Tools->Zigbee mode" #endif #include "Zigbee.h" /* Zigbee light bulb configuration */ #define ZIGBEE_LIGHT_ENDPOINT 10 uint8_t led = RGB_BUILTIN; uint8_t button = BOOT_PIN; ZigbeeLight zbLight = ZigbeeLight(ZIGBEE_LIGHT_ENDPOINT); /********************* RGB LED functions **************************/ void setLED(bool value) { digitalWrite(led, value); } /********************* Arduino functions **************************/ void setup() { Serial.begin(115200); // Init LED and turn it OFF (if LED_PIN == RGB_BUILTIN, the rgbLedWrite() will be used under the hood) pinMode(led, OUTPUT); digitalWrite(led, LOW); // Init button for factory reset pinMode(button, INPUT_PULLUP); //Optional: set Zigbee device name and model zbLight.setManufacturerAndModel("Espressif", "ZBLightBulb"); // Set callback function for light change zbLight.onLightChange(setLED); //Add endpoint to Zigbee Core Serial.println("Adding ZigbeeLight endpoint to Zigbee Core"); Zigbee.addEndpoint(&zbLight); // When all EPs are registered, start Zigbee. By default acts as ZIGBEE_END_DEVICE if (!Zigbee.begin()) { Serial.println("Zigbee failed to start!"); Serial.println("Rebooting..."); ESP.restart(); } Serial.println("Connecting to network"); while (!Zigbee.connected()) { Serial.print("."); delay(100); } Serial.println(); } void loop() { // 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(); } } // Toggle light by pressing the button zbLight.setLight(!zbLight.getLightState()); } delay(100); } ``` -------------------------------- ### Running a test using Wokwi Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html Example command to run the 'uart' test using Wokwi, setting the WOKWI_CLI_TOKEN environment variable. ```bash WOKWI_CLI_TOKEN= ./.github/scripts/tests_run.sh -s uart -t esp32c3 -W ``` -------------------------------- ### Basic Occupancy Sensor Example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/matter/ep_occupancy_sensor.html This C++ code demonstrates the setup and loop functions for a Matter Occupancy Sensor on an ESP32. It includes WiFi connection (optional), Matter initialization, commissioning, and simulated occupancy state changes. It also shows how to use a button for decommissioning. ```cpp // Copyright 2025 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * This example is an example code that will create a Matter Device which can be * commissioned and controlled from a Matter Environment APP. * Additionally the ESP32 will send debug messages indicating the Matter activity. * Turning DEBUG Level ON may be useful to following Matter Accessory and Controller messages. * * The example will create a Matter Occupancy Sensor Device. * The Occupancy Sensor will be simulated to change its state every 2 minutes. * * The onboard button can be kept pressed for 5 seconds to decommission the Matter Node. * The example will also show the manual commissioning code and QR code to be used in the Matter environment. * */ // Matter Manager #include #include #if !CONFIG_ENABLE_CHIPOBLE // if the device can be commissioned using BLE, WiFi is not used - save flash space #include #endif // List of Matter Endpoints for this Node // Matter Occupancy Sensor Endpoint MatterOccupancySensor OccupancySensor; // CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network #if !CONFIG_ENABLE_CHIPOBLE // WiFi is manually set and started const char *ssid = "your-ssid"; // Change this to your WiFi SSID const char *password = "your-password"; // Change this to your WiFi password #endif // set your board USER BUTTON pin here - decommissioning only const uint8_t buttonPin = BOOT_PIN; // Set your pin here. Using BOOT Button. // Button control uint32_t button_time_stamp = 0; // debouncing control bool button_state = false; // false = released | true = pressed const uint32_t decommissioningTimeout = 5000; // keep the button pressed for 5s, or longer, to decommission void setup() { // Initialize the USER BUTTON (Boot button) that will be used to decommission the Matter Node pinMode(buttonPin, INPUT_PULLUP); Serial.begin(115200); // CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network #if !CONFIG_ENABLE_CHIPOBLE // Manually connect to WiFi WiFi.begin(ssid, password); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); #endif // set initial occupancy sensor state as false and connected to a PIR sensor type (default) OccupancySensor.begin(); // Matter beginning - Last step, after all EndPoints are initialized Matter.begin(); // Check Matter Accessory Commissioning state, which may change during execution of loop() if (!Matter.isDeviceCommissioned()) { Serial.println(""); Serial.println("Matter Node is not commissioned yet."); Serial.println("Initiate the device discovery in your Matter environment."); Serial.println("Commission it to your Matter hub with the manual pairing code or QR code"); Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str()); Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str()); // waits for Matter Occupancy Sensor Commissioning. uint32_t timeCount = 0; while (!Matter.isDeviceCommissioned()) { delay(100); if ((timeCount++ % 50) == 0) { // 50*100ms = 5 sec Serial.println("Matter Node not commissioned yet. Waiting for commissioning."); } } Serial.println("Matter Node is commissioned and connected to the network. Ready for use."); } } bool simulatedHWOccupancySensor() { // Simulated Occupancy Sensor static bool occupancyState = false; static uint32_t lastTime = millis(); const uint32_t occupancyTimeout = 120000; // 2 minutes to toggle the state // Simulate a Occupancy Sensor state change every 2 minutes if (millis() - lastTime > occupancyTimeout) { occupancyState = !occupancyState; lastTime = millis(); } return occupancyState; } void loop() { // Check if the button has been pressed if (digitalRead(buttonPin) == LOW && !button_state) { // deals with button debouncing button_time_stamp = millis(); // record the time while the button is pressed. button_state = true; // pressed. } if (button_state && digitalRead(buttonPin) == HIGH) { button_state = false; // released } // Onboard User Button is kept pressed for longer than 5 seconds in order to decommission matter node ``` -------------------------------- ### Zigbee Multistate Device Example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/zigbee/ep_multistate.html This C++ code demonstrates the setup and configuration of a Zigbee multistate input/output device using the Arduino framework. It includes definitions for both standard and custom multistate devices, event handlers for state changes, and configuration for input and output clusters. ```cpp // Copyright 2025 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @brief This example demonstrates Zigbee multistate input / output device. * * The example demonstrates how to use Zigbee library to create a router multistate device. * In the example, we have two multistate devices: * - zbMultistateDevice: uses defined application states from Zigbee specification * - zbMultistateDeviceCustom: uses custom application states (user defined) * * Proper Zigbee mode must be selected in Tools->Zigbee mode * and also the correct partition scheme must be selected in Tools->Partition Scheme. * * Please check the README.md for instructions and more detailed description. * * NOTE: HomeAssistant ZHA does not support multistate input and output clusters yet. * * Created by Jan Procházka (https://github.com/P-R-O-C-H-Y/) */ #include #ifndef ZIGBEE_MODE_ZCZR #error "Zigbee coordinator/router device mode is not selected in Tools->Zigbee mode" #endif #include "Zigbee.h" /* Zigbee multistate device configuration */ #define MULTISTATE_DEVICE_ENDPOINT_NUMBER 1 uint8_t button = BOOT_PIN; // zbMultistateDevice will use defined application states ZigbeeMultistate zbMultistateDevice = ZigbeeMultistate(MULTISTATE_DEVICE_ENDPOINT_NUMBER); // zbMultistateDeviceCustom will use custom application states (user defined) ZigbeeMultistate zbMultistateDeviceCustom = ZigbeeMultistate(MULTISTATE_DEVICE_ENDPOINT_NUMBER + 1); const char *multistate_custom_state_names[6] = {"Off", "On", "UltraSlow", "Slow", "Fast", "SuperFast"}; void onStateChange(uint16_t state) { // print the state Serial.printf("Received state change: %u\r\n", state); // print the state name using the stored state names const char *const *state_names = ZB_MULTISTATE_APPLICATION_TYPE_7_STATE_NAMES; if (state_names && state < zbMultistateDevice.getMultistateOutputStateNamesLength()) { Serial.printf("State name: %s\r\n", state_names[state]); } // print state index of possible options Serial.printf("State index: %u / %u\r\n", state, zbMultistateDevice.getMultistateOutputStateNamesLength() - 1); } void onStateChangeCustom(uint16_t state) { // print the state Serial.printf("Received state change: %u\r\n", state); // print the state name using the stored state names if (state < zbMultistateDeviceCustom.getMultistateOutputStateNamesLength()) { Serial.printf("State name: %s\r\n", multistate_custom_state_names[state]); } // print state index of possible options Serial.printf("State index: %u / %u\r\n", state, zbMultistateDeviceCustom.getMultistateOutputStateNamesLength() - 1); Serial.print("Changing to fan mode to: "); switch (state) { case 0: Serial.println("Off"); break; case 1: Serial.println("On"); break; case 2: Serial.println("UltraSlow"); break; case 3: Serial.println("Slow"); break; case 4: Serial.println("Fast"); break; case 5: Serial.println("SuperFast"); break; default: Serial.println("Invalid state"); break; } } void setup() { log_d("Starting serial"); Serial.begin(115200); // Init button switch log_d("Init button switch"); pinMode(button, INPUT_PULLUP); // Optional: set Zigbee device name and model log_d("Set Zigbee device name and model"); zbMultistateDevice.setManufacturerAndModel("Espressif", "ZigbeeMultistateDevice"); // Set up analog input log_d("Add Multistate Input"); zbMultistateDevice.addMultistateInput(); log_d("Set Multistate Input Application"); zbMultistateDevice.setMultistateInputApplication(ZB_MULTISTATE_APPLICATION_TYPE_0_INDEX); log_d("Set Multistate Input Description"); zbMultistateDevice.setMultistateInputDescription("Fan (on/off/auto)"); zbMultistateDevice.setMultistateInputStates(ZB_MULTISTATE_APPLICATION_TYPE_0_NUM_STATES); // Set up analog output log_d("Add Multistate Output"); zbMultistateDevice.addMultistateOutput(); log_d("Set Multistate Output Application"); zbMultistateDevice.setMultistateOutputApplication(ZB_MULTISTATE_APPLICATION_TYPE_7_INDEX); log_d("Set Multistate Output Description"); zbMultistateDevice.setMultistateOutputDescription("Light (high/normal/low)"); zbMultistateDevice.setMultistateOutputStates(ZB_MULTISTATE_APPLICATION_TYPE_7_NUM_STATES); // Set up custom output log_d("Add Multistate Output"); zbMultistateDeviceCustom.addMultistateOutput(); ``` -------------------------------- ### Example - Get current temperature Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/matter/ep_temperature_sensor.html Example of getting the current temperature. ```cpp double temp = mySensor; // Get current temperature ``` -------------------------------- ### Example Application: WiFiAccessPoint Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/guides/docs_contributing.html Includes an example application from the WiFi library using a literal include directive. ```arduino .. literalinclude:: ../../../libraries/WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino :language: arduino ``` -------------------------------- ### Example: Build for esp32 SoC Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/guides/core_debug.html Example command to build the libraries specifically for the esp32 SoC. ```bash ./build.sh -t esp32 ``` -------------------------------- ### Setup Function Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/tutorials/blink.html Configures the defined LED pin as an output during the setup phase. ```c++ void setup() { pinMode(LED, OUTPUT); } ``` -------------------------------- ### Run Installation Script Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html Execute the get.exe script to download necessary tools. ```bash get.exe ``` -------------------------------- ### Inline Comments Example 2 Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html An example of inline comments for defining Wi-Fi credentials. ```c const char * WIFI_FTM_SSID = "WiFi_FTM_Responder"; // SSID of AP that has FTM Enabled const char * WIFI_FTM_PASS = "ftm_responder"; // STA Password ``` -------------------------------- ### OpenThread is ready example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/openthread/openthread_core.html Example of checking if OpenThread is started. ```c++ if (OThread) { Serial.println("OpenThread is ready"); } ``` -------------------------------- ### Key Existence Check Example Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/tutorials/preferences.html An example demonstrating how to check for the existence of a key and execute different code blocks based on the result, useful for initializing namespaces on first run. ```cpp Preferences mySketchPrefs; String doesExist; mySketchPrefs.begin("myPrefs", false); // open (or create and then open if it does not // yet exist) the namespace "myPrefs" in RW mode. bool doesExist = mySketchPrefs.isKey("myTestKey"); if (doesExist == false) { /* If doesExist is false, we will need to create our namespace key(s) and store a value into them. */ // Insert your "first time run" code to create your keys & assign their values below here. } else { /* If doesExist is true, the key(s) we need have been created before and so we can access their values as needed during startup. */ // Insert your "we've been here before" startup code below here. } ``` -------------------------------- ### timerBegin Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/api/timer.html Configures and starts a timer. The timer will automatically start after successful setup. ```c hw_timer_t * timerBegin(uint32_t frequency); ``` -------------------------------- ### Setup Function for Console and WiFi Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/api/console.html This C++ code demonstrates the setup function, which initializes the serial communication, begins the Wi-Fi station interface, and creates a binary semaphore for ping operations. ```cpp void setup() { Serial.begin(115200); while (!Serial) { delay(10); } // Initialize WiFi WiFi.STA.begin(); // Create semaphore for ping done ping_done_sem = xSemaphoreCreateBinary(); // Initialize argtable. // arg_str1() = required string. arg_str0() = optional string. ``` -------------------------------- ### Inline Comments Example 1 Source: https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html An example of an inline comment explaining a specific configuration value. ```c // Number of FTM frames requested in terms of 4 or 8 bursts (allowed values - 0 (No pref), 16, 24, 32, 64) ```