<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AndroidCrypto on Medium]]></title>
        <description><![CDATA[Stories by AndroidCrypto on Medium]]></description>
        <link>https://medium.com/@androidcrypto?source=rss-8d474649a487------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AA0rI01_Tb7GaZZfcMGpPQ.png</url>
            <title>Stories by AndroidCrypto on Medium</title>
            <link>https://medium.com/@androidcrypto?source=rss-8d474649a487------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:54:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@androidcrypto/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[HLK-LD2410C Human Presence Sensor in Pro Mode: Real-Time Equalizer, Auto-Calibration, and Dashboard…]]></title>
            <link>https://medium.com/@androidcrypto/hlk-ld2410c-human-presence-sensor-in-pro-mode-real-time-equalizer-auto-calibration-and-dashboard-e4fed6ea745d?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4fed6ea745d</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[ld2410c]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 14:39:50 GMT</pubDate>
            <atom:updated>2026-11-12T14:39:50.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>HLK-LD2410C Human Presence Sensor in Pro Mode: Real-Time Equalizer, Auto-Calibration, and Dashboard Architecture with ESP32</h3><p>I recently published the beginner tutorial “<a href="https://medium.com/@androidcrypto/how-to-use-an-hlk-ld2410c-human-presence-sensor-with-an-esp32-beginner-tutorial-17c9adde8e5a?sharedUserId=androidcrypto"><strong>How to Use an HLK LD2410C Human Presence Sensor with an ESP32</strong></a>” here. In this follow-up article, I will show you how to push the <strong>HLK-LD2410 Human Presence Sensor</strong> to its full potential using the <strong>LD2410 library</strong>. Since I will not repeat the basic information about the sensor and the underlying technology, I strongly recommend reading my previous article first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*PkcrH7Lm5GkikIGHXKiaeg.png" /></figure><h3><strong>Topics Covered in This Tutorial</strong></h3><ul><li>Hardware Used and Software Environment</li><li>Description of the Two Operating Modes of the LD2410C Sensor</li><li>Description of the Stored Configuration Data</li><li>Reading and Writing Configuration Data</li><li>What is the Gate Equalizer?</li><li>Sensor Calibration</li><li>Program Description</li><li>Conclusion</li></ul><h3><strong>Hardware Used and Software Environment</strong></h3><p>I am using the HLK-LD2410C Human Presence Sensor (which is technically compatible with the LD2410B) connected to an ESP32 microcontroller. In principle, the example program should run on all boards of the ESP32 family (ESP32-C3, -C5, -C6, -H2, and -S3). Please pay close attention to this exact model designation when purchasing the sensor; <strong>a sensor labeled LD2410S is not compatible with this tutorial</strong>.</p><p>I connected a 2.8-inch TFT display (ST7789 or ILI9341 driver chip) to the processor so that I can evaluate the sensor data independently from a computer (Serial Monitor). Since I also want to read the screen from a distance of several meters, I chose the 2.8-inch variant.</p><p>For programming, I am using <strong>Arduino IDE version 2.3.10</strong> and the <strong>esp32 board package version 3.3.11</strong>. The display is driven by the <strong>LovyanGFX library</strong>, as it works reliably under esp32 core 3.x and supports all of my ESP32 boards (ESP32, -S3, -H2, -C5, and -C6). It can also be installed via the Library Manager (or manually from <a href="https://github.com/lovyan03/LovyanGFX),">https://github.com/lovyan03/LovyanGFX),</a> and I am using <strong>version 1.2.35</strong>.</p><p>The centerpiece of this tutorial is the <strong>LD2410 library by Nick Reynolds</strong>, which can be installed via the Arduino Library Manager or manually from <a href="https://github.com/ncmreynolds/ld2410">https://github.com/ncmreynolds/ld2410</a> (<strong>version 0.2.2</strong>). This library provides access to all configuration and data fields of the LD2410C.</p><p><strong>Warning: This library is NOT compatible with the LD2410S sensor!</strong></p><p>Using this library simplifies parsing the incoming data and allows reading and modifying the sensor’s configuration via simple commands.</p><h3><strong>Description of the Two Operating Modes of the LD2410C Sensor</strong></h3><p>In the beginner tutorial, we used the sensor in its factory default state, receiving data formatted according to the “Normal” protocol, which has the following structure:</p><h4><strong>The 6 Payload Values in Normal Mode</strong></h4><ul><li><strong>Target Status (1 Byte): </strong>Indicates what type of target is currently detected. Possible values are 0x00 (no target), 0x01 (moving target only), 0x02 (stationary presence only), and 0x03 (both moving and stationary presence simultaneously).</li><li><strong>Moving Target Distance (2 Bytes): </strong>The calculated distance to the moving target in centimeters (cm).</li><li><strong>Moving Target Energy (1 Byte): </strong>The signal strength or energy of the moving target as a percentage from 0 to 100.</li><li><strong>Stationary Target Distance (2 Bytes): </strong>The calculated distance to the resting (stationary) target in centimeters (cm).</li><li><strong>Stationary Target Energy (1 Byte): </strong>The signal strength or energy of the stationary target as a percentage from 0 to 100.</li><li><strong>Detection Distance (2 Bytes): </strong>The combined overall detection distance to the nearest target in centimeters (cm).</li></ul><p>As we saw in the beginner tutorial, this is already sufficient for basic room monitoring while relying on the factory-preset sensitivities for each gate. However, if we want to set up more granular room monitoring or change the sensitivities, we need significantly more data from the sensor — and we get that in the Engineering protocol. I will explain how to switch between the two protocols later; first, here is the structure of the <strong>Engineering protocol</strong>:</p><h4>The Payload Values in Engineering Mode</h4><p><strong>1. The 6 Known Base Values (Identical to Normal Mode)</strong></p><p>Target Status, Moving Distance/Energy, Stationary Distance/Energy, and Detection Distance.</p><p><strong>2. The 4 Additional Payload Values in Engineering Mode</strong></p><ul><li><strong>Max Moving Gate (1 Byte): </strong>The maximum gate currently stored in the sensor for motion detection (default value 0x08, corresponding to Gate 8 or 6.75 m).</li><li><strong>Max Stationary Gate (1 Byte): </strong>The maximum gate currently stored in the sensor for stationary presence detection (default value 0x08).</li><li><strong>Moving Gate Energies (9 Bytes): </strong>An array of 9 individual values (0 to 100%) indicating the current motion energy separately for each distance gate (Gate 0 to Gate 8).</li><li><strong>Stationary Gate Energies (9 Bytes): </strong>An array of 9 individual values (0 to 100%) indicating the current presence energy separately for each distance gate (Gate 0 to Gate 8).</li></ul><p><em>(Note: Depending on the firmware version, 2 reserved bytes follow immediately after the two gate arrays. In standard operation, these are usually 0x00 and are either ignored by the library or handled separately as light-sensor/auxiliary status placeholders.)</em></p><p>This means that the extended Engineering Mode initially provides the exact same base data as the Normal Mode, supplemented by the individual gate energies.</p><h3><strong>Description of the Stored Configuration Data</strong></h3><p>In the HLK-LD2410C, configuration data is divided into two main sections: global Base Parameters (range and timeout delay) and detailed Gate Sensitivities (Thresholds).</p><h4><strong>1. Section: Base Configuration (Max Gates &amp; Timeout)</strong></h4><p>This section defines the outer detection boundaries and the temporal switching behavior of the sensor.</p><ul><li><strong>Max Moving Gate (1 Byte, range: 2 to 8): </strong>Determines the farthest distance gate up to which the sensor evaluates motion. Anything beyond this limit is ignored. With a gate width of 0.75 m, the default value of 8 corresponds to a maximum range of 6.75 meters (Gate 0 to Gate 8).</li><li><strong>Max Stationary Gate (1 Byte, range: 2 to 8): </strong>Sets the maximum range for resting (stationary) individuals (e.g., someone sitting still on a sofa). This value can be configured independently from the moving gate — for instance, to ignore a hallway behind an open door.</li><li><strong>Timeout Delay / Inactivity Timer (2 Bytes, range: 0 to 65535 seconds): </strong>Specifies how many seconds the sensor waits after the last detected target before resetting its state to “No Target” and switching the hardware OUT pin back to LOW. A short value (e.g., 1 to 5 seconds) ensures fast switching, whereas a higher value bridges brief periods of complete stillness.</li></ul><h4><strong>2. Section: Gate Sensitivities (Thresholds)</strong></h4><p>In this section, you define individually for each of the 9 distance gates (Gate 0 to Gate 8) how strong the reflected radar signal must be to register as a human presence.</p><ul><li><strong>Moving Sensitivity / Threshold (9 Bytes, 0 to 100% per gate): </strong>The trigger threshold for motion within the respective 75 cm segment. If the measured motion energy (movingEnergyAtGate) exceeds this percentage, the sensor reports motion. A higher value makes the gate less sensitive (filtering out interference like curtains or fans).</li><li><strong>Stationary Sensitivity / Threshold (9 Bytes, 0 to 100% per gate): </strong>The trigger threshold for microscopic movements (such as breathing or heartbeat) within the respective gate. Special note on Gate 0 and Gate 1: In the immediate close range (0 to 1.50 m), stationary thresholds are often disabled (0) or set to very low sensitivity at the factory because the radar antenna’s own background noise scatters most strongly here.</li></ul><p><strong>Summary (Quick Overview)</strong></p><pre>+------------------+--------------------+-------------+-----------------------------------------------------------+<br>| Config Section   | Parameter          | Range       | Function in Room                                          |<br>+------------------+--------------------+-------------+-----------------------------------------------------------+<br>| Base Data        | Max Moving Gate    | 2 - 8       | Limits maximum detection distance for motion.             |<br>| Base Data        | Max Static Gate    | 2 - 8       | Limits maximum detection distance for stationary presence.|<br>| Base Data        | Timeout Delay      | 0 - 65535 s | Hold time (switch-off delay) once the room is empty.      |<br>| Gate Thresholds  | Moving Sensitivity | 0 - 100%    | Minimum energy per gate required to trigger motion.       |<br>| Gate Thresholds  | Static Sensitivity | 0 - 100%    | Minimum energy per gate required to maintain presence.    |<br>+------------------+--------------------+-------------+-----------------------------------------------------------+</pre><h3><strong>Reading and Writing Configuration Data</strong></h3><p>The HLK-LD2410C also separates the two configuration sections (Base Data and Gate Thresholds) technically within its communication protocol — as well as in Nick Reynolds’ ld2410 library — into distinct command and data blocks. The library makes it very easy to read out the configuration and save modified values.</p><h4><strong>Reading Configuration Data</strong></h4><p>For reading configuration data, there is essentially one central request block (0x0061), triggered via radar.requestCurrentConfiguration().</p><ul><li><strong>Batch Response with Single-Field Queries (0x0061): </strong>Upon receiving this command code, the sensor returns all relevant parameters in a single data packet. However, the library does not return this data as a single consolidated object; instead, each field must be queried individually via the instance’s internal member variables:</li><li>Base Fields: Queried individually via radar.max_moving_gate, radar.max_stationary_gate, and radar.sensor_idle_time.</li><li>Gate Fields: The 18 threshold values are queried individually via the array indices radar.motion_sensitivity[0..8] and radar.stationary_sensitivity[0..8].</li></ul><h4><strong>Writing Configuration Data</strong></h4><p>While reading is handled through the single 0x0061 block, the protocol splits the write process into two separate command blocks so that base values and gate sensitivities can be modified independently:</p><ul><li><strong>Write Block 1 — Base Parameters (0x0060): </strong>The function radar.setMaxValues(movingGate, stationaryGate, inactivityTimer) writes only the 3 global boundary values (Max Moving Gate, Max Stationary Gate, and Timeout Delay) to the sensor.</li><li><strong>Write Block 2 — Gate Thresholds (0x0064): </strong>The function radar.setGateSensitivityThreshold(gate, moving, stationary) writes the sensitivity values for a specific distance gate. To update all 9 gates, this block must be sent nine times sequentially inside a loop.</li></ul><p><strong>Note: Both write blocks initially modify the values only in the sensor’s volatile memory (RAM). Only a subsequent reboot via radar.requestRestart() (0x00A3) permanently commits the data to non-volatile flash memory.</strong></p><h3><strong>What is the Gate Equalizer?</strong></h3><p>The Gate Equalizer is a visual representation rendered on the TFT display that shows the measured energy levels as a bar graph for each individual gate, further divided into “Moving” and “Stationary” measurements.</p><p>The thresholds stored for each respective gate are drawn directly onto the bars as horizontal lines. This makes it immediately obvious whether the threshold in a given gate has been exceeded — triggering a “Detect” state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*57Ahsk5lp8YqmGfyarcCDQ.png" /></figure><h3><strong>Sensor Calibration</strong></h3><p>For a 24 GHz FMCW radar sensor like the HLK-LD2410C, calibration means deliberately measuring and masking out room-specific sources of interference (background noise) by adjusting the trigger thresholds for each of the 9 distance gates.</p><p>Unlike a simple passive infrared (PIR) motion sensor that only reacts to heat changes, a millimeter-wave radar detects even the tiniest mechanical vibrations. Without calibration, the sensor cannot distinguish whether a signal reflection originates from a breathing human or a moving object in the room.</p><h4><strong>Why the Sensor Must Be Calibrated</strong></h4><ul><li><strong>Environmental Interference (Background Noise): </strong>Fans, curtains moving in a draft, houseplants, running PC cooling fans, or water flowing through heating pipes behind drywall generate continuous radar echoes.</li><li><strong>Material Penetration: </strong>24 GHz waves pass through glass, wood, and thin walls. If a tree sways outside a window or someone walks in an adjacent room, the corresponding distance gate (e.g., Gate 5 at 3.75 m) registers energy.</li><li><strong>Preventing False Positives: </strong>If the factory thresholds are set too low (too sensitive), the sensor gets stuck permanently in the “Presence Detected” state even when the room is completely empty.</li></ul><h4><strong>What Happens Technically During Calibration</strong></h4><ul><li><strong>1. Capturing the Baseline (Empty Room): </strong>In a completely empty room, the sensor measures the maximum interference energy (movingEnergy and stationaryEnergy) in each 75 cm segment (Gate 0 to Gate 8) over a defined period (e.g., 15 seconds) while running in Engineering Mode.</li><li><strong>2. Setting the Safety Threshold: </strong>A safety margin (e.g., +15% to +20%) is added to the peak background noise measured for each gate. This new value is saved in the sensor as the trigger threshold.</li><li><strong>3. Separating Noise from Signal: </strong>After calibration, the sensor ignores all echoes below this new threshold line (room noise) and only triggers when a human enters the gate and pushes the signal energy clearly above the threshold.</li></ul><h4><strong>Practical Takeaway</strong></h4><p>Calibration transforms an overly sensitive, general-purpose sensor into a tailored room profile. It ensures that the sensor is not permanently triggered by environmental noise while remaining sensitive enough to reliably track a person sitting still on a couch via their breathing movements.</p><h3><strong>Program Description</strong></h3><p>In my example sketch <em>ESP32_C6_Lov_ST7789_Advanced_v01</em>, I combined several functions into a single program so you do not have to upload separate sketches while testing and experimenting.</p><h4><strong>Menu Navigation</strong></h4><p>I use the board’s BOOT button for navigation — you simply need to enter the matching GPIO pin for your specific board in the code header.</p><p>I implemented a rolling menu system where each short button press cycles to the next screen. Because some functions alter the sensor’s configuration, I built in a safety mechanism: the program requires a long press (more than 3 seconds) as confirmation. Some routines also start an on-screen countdown. Measurements are indicated by a red background, saving operations by a blue background, and successful completion by a green background.</p><h4><strong>1: Standard Output (Home Screen)</strong></h4><p>This screen displays the data received via the “Normal Report,” supplemented by configuration parameters:</p><ul><li>It shows the current firmware version of the sensor (“2.44”) and the maximum number of Moving and Stationary Gates (“8” | “8”), representing the maximum range (8 * 75 cm).</li><li>Below that is a table listing the sensitivities of each individual gate, split into Moving and Stationary. (Reminder: Higher numbers mean lower sensitivity.)</li><li>The final configuration item is the Timeout Delay, displayed in seconds. This controls how long the sensor continues to report a “Detect” state after a person has left the detection zone (for example, in room lighting control, keeping the light on for 5 seconds after the room is empty).</li><li>The lower section shows the live (standard) sensor reporting: a [ TARGET DETECTED ] banner appears while a person is in the room. The line directly underneath (“OUT:”) is not derived from serial reporting, but rather reads the physical state of the hardware OUT pin.</li><li>The bottom two lines show the distance at which a person is detected moving or stationary, along with the measured energy level.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*9iZbPD3VZYVhOdEMKW4Syg.png" /></figure><h4><strong>2: Gate Equalizer</strong></h4><p>On this screen, you will see a total of 16 vertical bars, with each pair representing the Moving and Stationary energy for a single gate. This data comes from Engineering Mode, which provides much richer telemetry.</p><p>A total of 8 gates (G0 through G7) are displayed, giving you a live view across the room. Inside the bars, you will see green lines indicating the active sensitivity thresholds. When the measured energy is below the green line, the bar is drawn in dark grey (motion) or orange (stationary). Once the value meets or exceeds the threshold, the bar changes color to white or red, allowing you to see even from several meters away which gate threshold has been breached.</p><h4><strong>3: Calibration Mode</strong></h4><p>This mode does not call a built-in calibration function in the sensor or library; instead, it executes a custom sequence of measurements:</p><ul><li>After confirming with a long press (3 seconds), a 10-second countdown begins, giving you time to completely leave the room.</li><li>Over the next 15 seconds, the program records the peak energy levels across all individual gates (just like in the Gate Equalizer).</li><li>Each peak value is increased by a safety margin (Moving +20%, Stationary +15%), clamped between a minimum sensitivity of “10” and a maximum of “100”.</li><li>The new thresholds are permanently written to the sensor’s flash memory, after which the sensor reboots and immediately applies the new values.</li></ul><p>In the Serial Monitor, you will then find the following output:</p><pre>================ COPY FOR YOUR CODE ================<br> uint8_t calibrationMoveThresholds[9] = { 37, 35, 35, 31, 27, 28, 27, 32, 30 };<br> uint8_t calibrationStatThresholds[9] = { 15, 15, 76, 34, 27, 32, 32, 40, 80 };</pre><p>These are the newly calculated thresholds stored in the sensor, which can be reused in the next menu option. This block is also printed on every cold boot so you can review the data at your desk at any time.</p><h4><strong>4: Load Calibration Data</strong></h4><p>So that you do not have to recalibrate a room repeatedly during testing, you can re-upload the values recorded in Step 3 back to the sensor (for instance, after a factory reset). Simply paste your custom arrays into the code header, and you can restore them whenever needed.</p><h4><strong>5: Set Basic Configuration</strong></h4><p>To let you test the immediate impact of modifying the base parameters, I configured noticeably different target values:</p><ul><li>The Timeout Delay is reduced from 5 seconds to 1 second, reporting the room as “empty” much faster than before.</li><li>The number of Moving Gates drops from 8 down to 4 gates, limiting detection to a range of 0 to 3.75 meters (Gates 0–4). If a person stands farther away than that, the standard output will no longer report a detection.</li><li>The number of Stationary Gates likewise drops from 8 down to 4 gates, changing stationary presence behavior accordingly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*64xupPtto5raUFicfw7nMA.png" /></figure><h4><strong>6: Factory Reset</strong></h4><p>To allow a quick and easy return to factory defaults, this option uses the library’s built-in reset command (requestFactoryReset()) to restore the sensor to its out-of-the-box state.</p><h3><strong>Summary &amp; Conclusion</strong></h3><p>With the functions demonstrated here, you gain full access to all data fields and configuration registers of the LD2410 sensor.</p><p>In Engineering Mode, the HLK-LD2410C offers highly detailed access to live measurement data and enables very precise sensitivity tuning — especially in challenging room environments.</p><p>An additional advantage is that all of these parameters can also be accessed and adjusted wirelessly via the sensor’s built-in Bluetooth Low Energy (BLE) interface using a smartphone app, which is particularly convenient when making adjustments directly inside the monitored room. I may cover BLE configuration in a future tutorial; in the meantime, you can simply use the official HLK Radar Tool apps available for Android and iOS.</p><h3><strong>App Source Code</strong></h3><p>You can find all the code collected in my <a href="https://github.com/AndroidCrypto/ESP32_LD2410C_Human_Presence_Sensor">GitHub repository</a>, together with the code for the beginner tutorial. I added the Data Sheet and the Serial Communication Protocol as well, just in case the original source is not available.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4fed6ea745d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use an HLK LD2410C Human Presence Sensor with an ESP32 (Beginner Tutorial)]]></title>
            <link>https://medium.com/@androidcrypto/how-to-use-an-hlk-ld2410c-human-presence-sensor-with-an-esp32-beginner-tutorial-17c9adde8e5a?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/17c9adde8e5a</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[esp32-tutorial]]></category>
            <category><![CDATA[ld2410c]]></category>
            <category><![CDATA[human-presence-sensor]]></category>
            <category><![CDATA[uart]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 13:15:30 GMT</pubDate>
            <atom:updated>2026-11-12T14:43:08.164Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, you will learn how to connect an <strong>LD2410C Human Presence Sensor</strong> to an <strong>ESP32</strong>, as well as how to read and evaluate the received data. All of this is possible <strong>without using an additional library</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*lpy6sCD6mbBKm9hMoc9R3A.png" /><figcaption>ESP32-C6 Super Mini, ST7789 TFT Display and LD2410C Sensor on a self soldered PCB</figcaption></figure><p>In the meantime I published the “advanced” tutorial “<a href="https://medium.com/@androidcrypto/hlk-ld2410c-human-presence-sensor-in-pro-mode-real-time-equalizer-auto-calibration-and-dashboard-e4fed6ea745d?sharedUserId=androidcrypto"><strong>HLK-LD2410C Human Presence Sensor in Pro Mode: Real-Time Equalizer, Auto-Calibration, and Dashboard Architecture with ESP32</strong></a>” that is using the <a href="https://github.com/ncmreynolds/ld2410">“<strong>ld2410</strong>” library</a> by Nick Reynolds.</p><blockquote><strong>An important note at the beginning: </strong>throughout this tutorial, I will always refer to the ESP32, but <strong>this guide can be used with all processors in the ESP32 family</strong>. For example, I use an ESP32-S3 (LilyGo T-Display), ESP32-C5, and ESP32-C6 with an attached TFT display (ST7789 or ILI9341 chip). A quick tip: use the largest display possible! For the distance tests, we output the measured distance on the screen, and you should still be able to read the value from 6 meters away. :-)</blockquote><h3><strong>Topics of this Tutorial</strong></h3><ul><li>What is a Human Presence Sensor?</li><li>How does a Human Presence Sensor work?</li><li>Choosing the right sensor</li><li>Technical specifications of the HLK LD2410C sensor</li><li>Wiring the sensor to the ESP32</li><li>Manufacturer support</li><li>First contact with the sensor — Raw data without a library</li><li>A simple example</li><li>Notes on the practical test setup</li><li>Excursion: How do I understand the received data?</li><li>Final program</li><li>Summary</li></ul><h3><strong>What is a Human Presence Sensor?</strong></h3><p>A Human Presence Sensor monitors a specific area in front of it and detects whether a person is inside that space. Additionally, a human presence sensor detects whether the person in the room is moving or standing/sitting still. This makes these sensors much more powerful than traditional motion sensors (“PIR”), which can only detect movement.</p><p>A practical example is room lighting control: A PIR sensor detects a person entering the room and turns on the light. However, if the person sits quietly at a desk, the light will turn off again after a hold period. The human presence sensor behaves similarly at first, but it also detects the stationary person in the room and keeps the light turned on.</p><h3><strong>How does a Human Presence Sensor work?</strong></h3><p>Unlike a “PIR” (“Passive Infrared”) sensor, which operates based on thermal imaging detection, a human presence sensor is an active sensor that transmits and receives radio waves (in this case, in the 24 GHz band), making it a “Radar Sensor”. If people are present or moving in the room, the received signal changes, and the sensor reports presence.</p><h4><strong>Why is the 24 GHz band used for this sensor?</strong></h4><p>This frequency band is reserved worldwide for “ISM” (“Industrial, Scientific and Medical”) applications and can be used license-free. The 24 GHz frequency band is particularly well-suited for motion detectors because the very short wavelengths precisely capture even the smallest movements while allowing for an extremely compact sensor design. Furthermore, the 24 GHz signal is insensitive to high temperatures (with a PIR sensor, a heater or a candle can trigger a false alarm).</p><p>Additionally, these waves easily penetrate (thin) materials such as plastic enclosures, glass, wood, or drywall, allowing the sensor to be installed completely out of sight.</p><p>Furthermore, a special modulation of the radio signal is used called “FMCW” (Frequency-Modulated Continuous Wave), which improves the sensor’s performance. FMCW sensors not only detect micro-movements (like breathing) but can also divide the room into detection zones (e.g., “turn light on only when someone is sitting at the desk, but not when passing by in the hallway”) and track multiple people simultaneously.</p><h3><strong>Choosing the Right Sensor</strong></h3><p>The sensor used here, the <strong>LD2410C</strong>, is manufactured by the Chinese company <a href="https://www.hlktech.com/en/"><strong>Hilink Electronics Co., Ltd.</strong></a> (https://www.hlktech.com/en/), which distributes many other (similar) models alongside this one. If you want to buy an HLK human presence sensor from sites like AliExpress or others, <strong>you must pay close attention to the exact model designation (here: LD2410C), because every single letter matters</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*cUOvyM6qobaNc5XyyGkRnQ.png" /><figcaption>HLK LD2410C Sensor (front side)</figcaption></figure><p>The following criteria are important when choosing a sensor:</p><ul><li><strong>Room Size: </strong>The maximum room size is determined by the maximum detection distance and the detection angle. The manufacturer recommends ceiling mounting, for example; however, for convenience, I place my sensor on one side of the room. It does not matter whether the sensor is positioned vertically or horizontally.</li><li><strong>Power Supply: </strong>Generating a high-frequency signal is relatively power-intensive. Therefore, you must expect currents of up to 200 mA and <strong>provide a supply voltage of 5 Volts</strong> (some models can also manage with 3.3 Volts).</li><li><strong>Interface to the Microprocessor: </strong>The vast majority of sensors use the <strong>UART (Universal Asynchronous Receiver Transmitter) interface</strong> at 256000 baud or 115200 baud. The interface requires a two-wire connection (“TX” and “RX” channels). A few sensors also have a <strong>Bluetooth Low Energy (“BLE”) profile</strong> available, which allows for remote configuration of parameters and querying of measured values.</li><li><strong>Form Factor of the Sensor: </strong>The electronic components are located on the sensor board, along with the radar transmitting and receiving antennas in the form of copper planes. The connection to the microprocessor (power and data) is often made using breadboard pins (male) with a 2.54 mm spacing. However, there are variants like the <strong>LD2410B</strong>, which is technically identical to the LD2410C, but <strong>its breadboard pins have a 1.2 mm spacing</strong>. For the alternatively possible solder connection, you will need a super-fine soldering tip. Other sensors, like the LD2450, rely on a plug connection with a ZH 1.5 form factor.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*B45v9iV9vJgo9igei3g56A.png" /><figcaption>Left side: LD2410B — right side: LD2410C sensor</figcaption></figure><ul><li><strong>Availability of a Ready-Made Library: </strong>The sensors deliver a continuous data stream, and a library helps analyze and split the data, as well as modify the sensor’s settings. Therefore, check before purchasing that a library (Arduino) is available for your intended sensor. Just like with the purchase itself, it is crucial to meticulously read through the technical description or the source code (here too, every letter of the model name counts).</li></ul><h3><strong>Technical Specifications of the HLK LD2410C Sensor</strong></h3><p>For this tutorial, the choice fell on the <strong>HLK LD2410C sensor</strong> because, in my opinion, it <strong>is the most universal human presence sensor</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*FcdsD-mAc5wA-E362O-Twg.png" /><figcaption>HLK LD2410C Sensor (back side)</figcaption></figure><p><strong>a) Room Size: </strong>The maximum <strong>distance is 5 meters</strong> (according to the datasheet), with the space in front of the sensor divided into 8 equally sized zones or “gates”. The sensor’s opening angle is +/- 60 degrees, allowing it to monitor an area of around 26 square meters. The maximum width at the furthest point (5 meters) is approximately 8 meters.</p><p><strong>b) Power Supply: </strong>According to the datasheet, <strong>the sensor requires a stable 5-Volt power source</strong> and draws up to <strong>200 mA of current</strong>. However, during my tests, the sensor also functioned flawlessly at 3.3 Volts.</p><p><strong>c) Interface: </strong>The LD2410C communicates with the ESP32 via a 2-wire <strong>UART interface at 256000 baud</strong>. The <strong>signal voltage level is 3.3 Volts</strong> and is directly compatible with the ESP32 signal level. I use the second UART interface on the ESP32 so that I can still exchange external data with the processor via the default interface.</p><p>Additionally, <strong>the sensor features a switchable Bluetooth Low Energy (BLE) interface</strong>, which can be conveniently used via the manufacturer’s own apps (Android and iOS). Of course, the ESP32 can also work with the sensor over BLE, enabling wireless communication (this is not part of this tutorial).</p><p><strong>d) Form Factor: </strong>The sensor has a size of 22x16 millimeters and features 5 soldered male pins with the standard breadboard spacing of 2.54 mm. The following connections are made at the 5 pins: VCC (5 Volts), GND, OT1 (corresponds to the TX pin), RX, and OT2 (corresponds to the OUT pin).</p><blockquote>Attention: The meaning of the OT1 and OT2 pins varies from model to model; please read the respective sensor documentation carefully!</blockquote><p><strong>e) Libraries: </strong>Since this sensor is the direct successor to the LD2410 sensor, several proven libraries are available. For this sensor (but not in this tutorial), I use the “<a href="https://github.com/ncmreynolds/ld2410">ld2410</a>” library by Nick Reynolds, which can be installed via the Arduino Library Manager or manually from <a href="https://github.com/ncmreynolds/ld2410;">https://github.com/ncmreynolds/ld2410;</a> the current version is 0.2.2. The library provides access to all configuration and data fields of the LD2410C.</p><p>Attention: <strong>This library is not compatible with the LD2410S sensor!</strong></p><h3><strong>Wiring the Sensor to the ESP32</strong></h3><p>In this tutorial, I am focusing solely on the human presence sensor; you will need to manage the wiring of your display yourself.</p><p>Whenever I use a display in an example program, it is controlled via the <a href="https://github.com/lovyan03/LovyanGFX"><strong>LovyanGFX library</strong></a>, as it works under esp32-boards 3.x and supports all of my ESP32 boards (ESP32, -S3, H2, C5, and C6). It can also be installed via the Library Manager (or manually from here: <a href="https://github.com/lovyan03/LovyanGFX),">https://github.com/lovyan03/LovyanGFX),</a> and I am using version 1.2.35. I worked with Arduino IDE version 2.3.10 and use esp32-boards version 3.3.11.</p><p>For this tutorial, you will need 2 free GPIO pins for the UART interface. The pins between the sensor and the ESP32 board are connected as follows:</p><p><strong>Sensor — ESP32<br> </strong>VCC — 5 Volts<br> GND — GND<br> RX Pin — TX Pin<br> OT1/TX Pin — RX Pin<br> OT2 Pin — Free GPIO (optional)</p><p>It is important that the TX and RX pins are connected crosswise, meaning “RX to TX” and “TX to RX”.</p><p>As previously mentioned, the sensor’s signal level is 3.3 Volts, so it can be connected directly to the ESP32’s GPIOs.</p><p>I have also connected the OT2 pin (which is the OUT output) to the ESP32, as it provides digital “room is empty” or “room is occupied” information. When the sensor detects presence, the signal level goes “HIGH”; otherwise, it stays “LOW”. If you do not wish to use this connection, the tutorial will still work perfectly fine.</p><h3><strong>Manufacturer Support</strong></h3><p>The manufacturer provides the necessary information on its website in a <a href="https://drive.google.com/drive/folders/1ypOlacBmmFXY6lDQ0f1hEJFmczNe-0WG">Google Drive archive</a>. As I discovered during my testing, the manufacturer’s own information is unfortunately not always up to date, but it should still contain the correct data for our work.</p><p>You can find the Google Drive archive via this link: <a href="https://drive.google.com/drive/folders/1ypOlacBmmFXY6lDQ0f1hEJFmczNe-0WG.">https://drive.google.com/drive/folders/1ypOlacBmmFXY6lDQ0f1hEJFmczNe-0WG.</a> You should also take a look at the information for the <a href="https://drive.google.com/drive/folders/16zI-fium_BZeP08EyQke0rWp0BJTMvw3">LD2410B sensor</a>, as that sensor is technically fully compatible with the LD2410C and you can find additional information regarding the BLE interface there (Link: <a href="https://drive.google.com/drive/folders/16zI-fium_BZeP08EyQke0rWp0BJTMvw3).">https://drive.google.com/drive/folders/16zI-fium_BZeP08EyQke0rWp0BJTMvw3).</a></p><p>In any case, you should download both PDFs: “<em>HLK LD2410C Life Presence Sensor Module Data Sheet V1.00</em>” and “<em>HLK-LD2410C Serial communication protocol V1.07</em>”, as you will need to refer to them repeatedly when working with the sensor.</p><h3><strong>First Contact with the Sensor — Raw Data Without a Library</strong></h3><p>I will start with the simplest example and gradually make the received data more readable:</p><h4><strong>Sketch: ESP32 C6 LD2410 Raw V01</strong></h4><p>Our first sketch does not use a library but works exclusively with the raw data from the sensor in its factory default state.</p><p>This is the smallest possible program, which first initializes both serial interfaces, listens on the second serial interface (“Serial1”) inside loop(), and displays the received data in hexadecimal encoding.</p><p>We receive a continuous data stream that appears completely random at first glance:</p><pre>ESP32-C6 HLK LD2410C Human Presence Sensor Raw V01 F4 F3 F2 F1 0D 00 02 AA 01 3B 00 64 00 00 00 00 00 55 00 F8 F7 F6 F5 F4 F3 F2 F1 0D 00 02 AA 01 31 00 64 00 00 00 00 00 55 00 F8 F7 F6 F5 F4 F3</pre><h4><strong>Sketch: ESP32 C6 LD2410 Raw Record Limiter V01</strong></h4><p>The basic structure corresponds to the “Raw” program, but upon closer inspection of the data, recurring patterns become apparent. We repeatedly see the bytes “<em>F8 F7 F6 F5 F4 F3 F2 F1</em>”. At this point, we look into the “<em>Serial Communication Protocol</em>” under section “<em>2.3 Radar data output protocol</em>” and find the crucial hints a bit later under “<em>2.3.1 Reported data frame format</em>”. Table 9 reveals the fundamental structure of the transmitted data:</p><p>Frame header: F4 F3 F2 F1<br>End of frame: F8 F7 F6 F5</p><p>This makes it clear: <strong>every data record ends with the “End of frame” sequence</strong>. I have integrated a ring buffer into the Raw program, which is continuously queried and compared with the “End of frame” data sequence. Upon a match, the data record is separated by a line break:</p><pre>Header: <br>// Buffer to detect the 4-byte footer: F8 F7 F6 F5 <br>uint32_t footerCheckBuffer = 0;  <br><br>loop(): <br>// Slide the incoming byte into our 32-bit footer history checker <br>footerCheckBuffer = (footerCheckBuffer &lt;&lt; 8) | incomingByte;  <br>// Check if the last 4 bytes match the LD2410 standard footer: F8 F7 F6 F5 <br>if (footerCheckBuffer == 0xF8F7F6F5) {   <br>  // Footer detected! Break line and mark packet boundary   <br>  Serial.println(&quot; &lt;- [PACKET END]&quot;); <br>}</pre><p>Here you can see the result:</p><pre>F4 F3 F2 F1 0D 00 02 AA 03 46 00 64 38 00 64 29 00 55 00 F8 F7 F6 F5  &lt;- [PACKET END] <br>F4 F3 F2 F1 0D 00 02 AA 03 41 00 64 46 00 64 2A 00 55 00 F8 F7 F6 F5  &lt;- [PACKET END] <br>F4 F3 F2 F1 0D 00 02 AA 03 45 00 64 41 00 64 2B 00 55 00 F8 F7 F6 F5  &lt;- [PACKET END] <br>F4 F3 F2 F1 0D 00 02 AA 03 1E 00 64 45 00 64 27 00 55 00 F8 F7 F6 F5  &lt;- [PACKET END] <br>F4 F3 F2 F1 0D 00 02 AA 03 4A 00 64 1E 00 64 29 00 55 00 F8 F7 F6 F5  &lt;- [PACKET END]</pre><h4><strong>Sketch: ESP32 C6 LD2410 Raw Parser V01</strong></h4><p>We look into the Serial Communication Protocol once more and split (“parse”) the received data.</p><p>Section “<em>2.3.2 Target data composition</em>” lists all the data fields contained in our data record:</p><p>In section 2.3.1, we already saw the basic structure: a “Frame Header”, the length of the data in 2 bytes (fundamentally encoded in “Little Endian”), the actual data, and the “End of frame” sequence. We now look into the actual data, which is broken down in 2.3.2. However, the order of the data is somewhat confusing because it is shown in separate tables. Here is the exact sequence of the data and its meaning:</p><ul><li>Data Type: Reporting mode</li><li>Head check: static data — Protocol Data Head (0xAA)</li><li>Target Status: what detected the sensor</li><li>Movement target distance (cm)</li><li>Move Energy</li><li>Stationary Distance (cm)</li><li>Stationary Energy</li><li>Detect Distance (cm)</li><li>Tail Check: static data — Protocol Data Tail (0x55 0x00)</li></ul><p>When I send this data to the parser, I get the following output:</p><pre>F4 F3 F2 F1 0D 00 02 AA 03 49 00 64 3F 00 64 20 00 55 00 F8 F7 F6 F5  &lt;- [PACKET END] <br>------------------ PARSED DATA ------------------ <br>Field 01: Header, 4 Bytes: F4 F3 F2 F1  | Meaning: Start of data <br>Field 02: Data Length, 2 Bytes: 0D 00  | Value: 13 Bytes within the frame <br>Field 03: Data Type, 1 Byte: 02  | Meaning: Normal Mode (0x02) <br>Field 04: Head Check, 1 Byte: AA  | Meaning: Protocol Data Head (0xAA) <br>Field 05: Target Status, 1 Byte: 03  | Value: 0x3 -&gt; BOTH moving and stationary targets detected <br>Field 06: Move Distance, 2 Bytes: 49 00  | Value: 73 cm <br>Field 07: Move Energy, 1 Byte: 64  | Value: 100 % <br>Field 08: Stat Distance, 2 Bytes: 3F 00  | Value: 63 cm <br>Field 09: Stat Energy, 1 Byte: 64  | Value: 100 % <br>Field 10: Detect Distance, 2 Bytes: 20 00  | Value: 32 cm <br>Field 11: Tail Check, 2 Bytes: 55 00  | Meaning: Protocol Data Tail (0x55 0x00) <br>Field 12: Footer, 4 Bytes: F8 F7 F6 F5  | Meaning: End of Dataset <br>Status OUT Pin: Person detected in room. <br>-------------------------------------------------</pre><p>Result: <strong>We have a fully usable parser</strong>, as it gives us all the necessary information for subsequent processing (turning a lamp on or off, etc.).</p><blockquote>Please ensure that the displayed Data Type is “<strong>Normal Mode</strong>” (<strong>and not “Engineering Mode”</strong>), because only then can the simple parser split and output the data record. If you have changed the mode due to any previous use, you must reset it to “Normal Mode”. I do not provide support for this in this tutorial, but the mentioned “ld2410” library includes a corresponding function.</blockquote><p><strong>Field 03: Data Type, 1 Byte: 02 | Meaning: Normal Mode (0x02)</strong></p><p>Very important for everyone working with raw data in the future: <strong>all data fields are copied in “Little Endian”</strong>, meaning the least significant byte is displayed first. Example: Move Distance is 0x49 0x00 = decimal 73 * 1 + decimal 0 * 256 = 73 cm.</p><p>If you connected the additional wire from <strong>OT1</strong> to another GPIO, you can query the status of this pin using digitalRead. The sensor keeps the state of OT1 LOW when it does not detect any person in the room. <strong>When a detection occurs, the value jumps to “HIGH”, which equates to “Detected”</strong>.</p><p>Therefore, if you connect a small relay directly to the OUT pin, for example, you can trigger an action immediately without even using a microcontroller.</p><h3><strong>Notes on the Practical Test Setup</strong></h3><p>At this point, it is time to talk about the practical test setup in your programming lab. You will notice that the sensor constantly reports “detected”, which is simply because the sensor is so sensitive that it always notices your presence “next door”. Even though the sensor’s main viewing direction is away from the PCB, its waves propagate throughout the room and the receiver catches them.</p><p>For this reason, I chose an ESP32-C6 board with a large display that operates autonomously — meaning without a computer connected via Serial Monitor. The most important information is displayed large and in a color that allows reading over a distance of several meters.</p><p>After uploading a new version, I carry the setup to another room where a power bank provides the power supply, and I can perform my tests in peace. Although the room is several meters long, I sometimes have to leave it entirely to trigger a “room is empty” status on the sensor.</p><blockquote>Important Note: Even when the last person leaves the room, <strong>the sensor does not immediately show “EMPTY” </strong>because it features a built-in timer (“No one duration”). Only after no one is left in the room is it triggered, and it changes to the LOW state (meaning “EMPTY”) after 5 seconds.</blockquote><h3><strong>Excursion: How do I understand the received data?</strong></h3><p>Moving forward, I will use a few terms that I will explain to you here:</p><ul><li><strong>Gate: </strong>The area in front of the sensor is divided into 9 zones, each 75 cm wide. <strong>This results in a maximum distance of 6.75 meters</strong> within which the sensor takes measurements. Each of these zones is called a “Gate”; the numbering starts at 0 and designates the area immediately in front of the sensor.</li><li><strong>Energy: </strong>If a person is within a gate, the sensor perceives this as an energy field. The higher the value, the more “human” was detected. The values range between 0 and a maximum of 100.</li><li><strong>Sensitivity Thresholds: </strong>For each gate, there is a (modifiable) preset value specifying at which energy level it should trigger a “Detect”. Crucially, lower values mean higher sensitivity. Example: the sensor measures an energy of “50” in a gate. If the threshold was set to “70”, no “Detect” message is issued. If, on the other hand, the sensitivity threshold is set to “30”, the detect message is output. <strong>Attention: different sensitivities can be configured for moving and stationary sensitivity</strong>.</li><li><strong>Stationary or Moving: </strong>The sensor is capable of measuring the energy of a stationary or moving person separately for each individual gate. This is useful if you want to start different actions for both states. Example: a person walks past in Gate 8, and a person is sitting in Gate 2. The sensor can recognize these two distinct patterns and react accordingly.</li><li><strong>Detect Hold Time (also “no one duration”): </strong>This variable controls how many seconds the sensor should hold the Out pin HIGH after the last detection, and how long a detect should appear in the Serial Protocol.</li></ul><h3><strong>Final Program</strong></h3><p>As mentioned above, practical testing can sometimes be a bit difficult. To read the Serial Monitor, you have to sit at the computer, and since the LD2410C is nearby, you rarely reach the “Empty” state. Therefore, I expanded the simple parser with an output function for a TFT display in 240x320 pixel portrait mode.</p><h4>Sketch Name: ESP32 C6 Lov ST7789 LD2410 Raw Parser V04</h4><p>The program uses the LovyanGFX graphics library, which can handle almost any TFT display on the ESP32. The parsed data record continues to be output unchanged in the Serial Monitor, and the exact same data is also shown on the TFT display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*OWnj0ZyP6t7jdSu3soibSQ.png" /><figcaption>The maximal distance is around 6 Meters</figcaption></figure><h3><strong>Summary</strong></h3><p>The HLK LD2410C sensor is a fantastic addition for any developer of microprocessor applications. It can be used quickly and easily with an ESP32 and provides a high quality of measured data.</p><h3><strong>App Source Code</strong></h3><p>You can find all the code collected in <a href="https://github.com/AndroidCrypto/ESP32_LD2410C_Human_Presence_Sensor"><strong>my GitHub repository</strong></a>. I added the Data Sheet and the Serial Communication Protocol as well just in case the original source is not available. The code for the advanced tutorial is published there as well.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17c9adde8e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect an ILI9341 TFT Display and SHT30 Environment Sensor to an Arduino UNO R3]]></title>
            <link>https://medium.com/@androidcrypto/connect-an-ili9341-tft-display-and-sht30-environment-sensor-to-an-arduino-uno-r3-1613eb34e98e?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/1613eb34e98e</guid>
            <category><![CDATA[arduino-uno]]></category>
            <category><![CDATA[logic-level-converter]]></category>
            <category><![CDATA[ili9341]]></category>
            <category><![CDATA[spi-interface]]></category>
            <category><![CDATA[sht30]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 14:22:27 GMT</pubDate>
            <atom:updated>2026-10-12T14:22:27.477Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, you will learn how to connect an <strong>ILI9341 TFT display</strong> to an <strong>Arduino UNO R3</strong> and also how to read and display data from an <strong>SHT30 environmental sensor</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7sk6NOcz_akKDlLfSA73Og.png" /></figure><p>A reader recently asked me, “How do I connect an ILI9341 TFT display to an Arduino UNO?” but unfortunately, I couldn’t give a good answer at the time. So, I did some research and found all the necessary parts in my stash to carry out this project. Let’s get started.</p><blockquote>A word of <strong>urgent warning</strong> right at the start: please never connect a display or sensor to an <strong>Arduino UNO</strong> before familiarizing yourself with the technical details of your hardware — otherwise, <strong>you could destroy your devices</strong>.</blockquote><p>Note: I haven’t tested it, but an identical display with an <strong>ST7789 driver chip</strong> and the corresponding Adafruit library should work just as well.</p><h3>Topics of this tutorial</h3><ul><li>Hardware used in this tutorial</li><li>A brief overview of the Arduino UNO 3</li><li>Software and Libraries used for the project</li><li>Circuit (technical configuration)</li><li>Overview of the sketch used</li><li>Troubleshooting</li><li>Summary</li></ul><h3>Hardware used in this tutorial</h3><p>I used the following hardware for the tutorial project:</p><ul><li>an Arduino Uno 3 clone,</li><li>an ILI9341 TFT display (2.8-inch screen, 240 x 320 pixel resolution, SPI interface),</li><li>an SHT30 sensor module with an I2C interface,</li><li>and two 4-channel level shifter modules.</li></ul><p>I will explain the Arduino UNO in the next chapter.</p><h4>ILI9341 TFT Display</h4><p>The display used here is one I employ in my ESP32 projects; it is driven by the <strong>ILI9341 chip</strong> and, in addition to its primary display function, features an <strong>SD card reader</strong> and an optional <strong>resistive touch interface</strong>. In this tutorial, I focus exclusively on the display function. The reason for this lies in the UNO’s hardware: its built-in memory is too small for extensive image functions or other features, and you will quickly hit that limit.</p><p>The display is designed for a voltage level of 3.3 volts so that it can be used with an ESP32. Although these displays (usually on a red PCB) are available with a 5-volt modification option, you should exercise caution, as even the 5-volt versions typically expect a 3.3-volt signal level.</p><p>The display connects to the UNO via the <strong>SPI interface</strong>; in addition to the power supply (3.3 V and GND), five lines are required for this: MOSI, SCLK, RST, DC, and CS. The display also provides an MISO line — which I did connect — though it is not actually used by the graphics library employed.</p><h4>SHT30 Environment Sensor</h4><p>I used the SHT30 sensor for this project simply because it was the first one I had on hand; naturally, you can also use the newer SHT31, SHT40, SHT41, or SHT45 sensors, or the AHTxx or BME280 — you just need to use the appropriate library for the sensor and, if necessary, adjust the data reading method.</p><p>This sensor is connected to the processor via the <strong>I2C interface</strong> — that is, via the two control lines SCK and SCL, in addition to the power supply (3.3 volts and GND).</p><h4>4 channel I2C Logic Level Converter Bi-Directional Module 5V to 3.3V</h4><p>Since I need to connect a total of eight data lines between the Arduino UNO and the display and sensor, I am using two logic level converter modules. Each channel employs a <strong>MOSFET</strong> and two resistors. They convert a 5-volt control signal to 3.3 volts and vice versa (bidirectionally).</p><p>Such a module costs around 1.50 euros and is available from a great many sellers, for example on AliExpress.</p><p>Each module has two long sides — one for each of the two voltage levels: there is the <strong>“high-voltage side” (“HV”)</strong> and the <strong>“low-voltage side” (“LV”)</strong>, and it is very important not to mix up the two sides.</p><h3>A brief overview of the Arduino UNO 3</h3><p>You can order an Arduino UNO R3 clone from AliExpress for around 3 euros. The board features the <strong>ATmega328P microcontroller</strong> and the <strong>CH340G USB-to-serial converter</strong>. If you are accustomed to the memory capacity and performance of the ESP32 family, you will need to adjust to the fact that this board has significantly more modest specifications and is slower.</p><p>As is typical for the Arduino family, the board features connectors on both sides into which another circuit board (a “shield”) can be plugged. However, for my setup, I am using point-to-point wiring to a breadboard.</p><p>The board offers two voltages — a <strong>5-volt</strong> and a <strong>3.3-volt</strong> rail.</p><blockquote>The most important point, however, is that <strong>all data lines (both digital and analog channels) operate at a 5-volt voltage level</strong>.</blockquote><p>To revisit the warning from the beginning of the tutorial: <strong>if you connect a display or sensor without checking it first, there is a high probability that you will fry the chips inside your devices</strong>.</p><p>Yes, there are displays or sensors designed for 5-volt logic levels, but they are usually significantly more expensive than the 3.3-volt versions and not as widely available — so don’t say I didn’t warn you! :-)</p><h4>How do I convert the voltage levels?</h4><p>In principle, there are two options: you can use a resistor-based voltage divider, or you can use suitable switching chips.</p><p>However, the voltage divider approach works in only one direction — stepping down from 5 volts to 3.3 volts. In our case, though, you would need to install a total of 12 resistors for at least 6 of the 8 lines. There are also a few additional points worth considering regarding the chip-based approach.</p><p>There are a few options available, and the “universal converters” I use generally work reliably; however, you should be aware of their limitations. They are perfectly suited for the I2C interface but have limited switching speeds — meaning they cannot keep up with the high speeds typical of the SPI interface, which manifests as artifacts or a white screen.</p><p>Other chips are perfectly suited for the SPI interface but do not handle the necessary pull-up resistors for the I2C interface and are often designed to be unidirectional.</p><p>To avoid expanding the scope of my project, I used the standard converters, which work with the appropriate settings.</p><h3>Software and Libraries used for the project</h3><p>I am using <strong>Arduino IDE</strong> version 2.3.10 (macOS) with <strong>Arduino AVR Boards</strong> version 1.8.8. For the display, I am using the <strong>Adafruit ILI9341 library</strong> version 1.6.4, and for the SHT30 sensor, the <strong>Adafruit SHT31 library</strong> version 2.2.2 is used.</p><h3>Circuit (technical configuration)</h3><p>For this project, you should be aware that you will have to handle a lot of wiring, since you are essentially <strong>doubling up on the cabling</strong>. All data lines first run to the voltage level converters before continuing via a second wiring harness to the display or sensor.</p><p>In addition, both converters require both the high (5-volt) and low (3.3-volt) voltage supplies, as well as a GND connection on both sides.</p><p>Since the SPI interface is particularly sensitive to poor connections, you should use <strong>high-quality cables and a good breadboard</strong> — or, better yet, opt for a <strong>soldered circuit board</strong> instead of this type of wiring setup. As this tutorial involves a temporary project, I chose a free-wired setup, but I would prefer the soldered version if I were to use this combination frequently.</p><p>You should also ensure you use <strong>short cables</strong>, as the SPI interface is sensitive to this.</p><h3>Overview of the sketch used</h3><p>The sketch shouldn’t contain anything unusual if you have already implemented a project like this using an ESP32. I include the libraries and create instances for the display and the sensor. Since I am using the default pins for the I2C and SPI interfaces, I only need to add the pin definitions for “CS” (10), “DC” (9), and “RST” (8). The I2C SDA pin is A5 and the SCL pin is A4; for SPI, MOSI is 11, SCLK is 13, and MISO connects to 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OCuu6msn6LzWpxCkHr4y4w.png" /></figure><p>After the display starts up, the sensor is initialized and the “static” interface is displayed. Within the ‘loop()’ function, the sensor is polled every two seconds to read the temperature and humidity, which are then shown on the display.</p><h3>Troubleshooting</h3><p>In the “Circuit” chapter, I already wrote about how sensitive the SPI interface is, particularly due to its high speed. This is usually where the source of display-related problems lies. I myself experienced a situation where a setup that had worked flawlessly the night before failed to function the next morning — even though the circuit hadn’t been moved, let alone modified.</p><p>In my sketch, I decided on a drastic measure that can significantly improve the stability of the setup: I am reducing the SPI speed from the default value (24 MHz) to just 4 MHz. This is implemented with a single line when the display starts up:</p><pre>// start Display<br>//tft.begin(); // default 24 MHz<br>tft.begin(4000000); // 4 MHz</pre><p>If your setup works smoothly, you can easily increase the speed to, for example, 8, 16, or 24 MHz, and revert to the working configuration if any issues arise.</p><p>If the display still fails to work, your only option will be to check every single wire and, if necessary, take measurements. It is also crucial to ensure that the connectors fit tightly into every single breadboard socket.</p><p>A second point concerns the power supply: Arduino UNO 3 boards often feature inferior or weaker <strong>LDOs (Low-Dropout Linear Regulators)</strong>, and a fully active display can draw more than 100 mA — potentially causing a reboot or a reset of the (display) registers. Therefore, please pay close attention to the two voltage channels!</p><p>As a final point, I’ll revisit the soldered circuit board mentioned earlier — or you can simply use a ready-made shield with a display.</p><h3>Summary</h3><p>Connecting an SPI display and an I2C sensor to an Arduino Uno R3 is not a major challenge, but it does require careful wiring of the components, as the two different voltage levels — 5 volts for the Arduino and 3.3 volts for the display and sensor — make voltage conversion essential.</p><h3>App Source Code</h3><p>You can find all the code collected in <a href="https://github.com/AndroidCrypto/Arduino_UNO_3_ILI9341_SHT30">my GitHub repository</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1613eb34e98e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How precise is the timing of an ESP32-C3 processor in deep sleep?]]></title>
            <link>https://medium.com/@androidcrypto/how-precise-is-the-timing-of-an-esp32-c3-processor-in-deep-sleep-12ccb7412fb2?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ccb7412fb2</guid>
            <category><![CDATA[accuracy]]></category>
            <category><![CDATA[esp32-c3]]></category>
            <category><![CDATA[rtc]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[real-time-clock]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 15:36:36 GMT</pubDate>
            <atom:updated>2026-09-10T15:36:36.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>How precise is the timing of an ESP32-C3 processor in deep sleep? A personal experiment answers this question.</h3><p>The processors of the ESP32-family feature a built-in <strong>real-time clock (RTC)</strong> that offers excellent time stability. However, there are also use cases where the processor spends the majority of its time asleep, wakes up for a few seconds to — for example — perform measurements and transmit them to a control unit, and then goes back to sleep. This phase is known as “<strong>deep sleep mode</strong>” and is used for a single reason: <strong>to conserve (precious) battery capacity</strong>.</p><p>In this tutorial, I will show you how to test the accuracy and timing stability of your ESP32 processor yourself and apply appropriate compensation measures.</p><h3>Topics of this tutorial</h3><ul><li>Real Time Clock (RTC) overview</li><li>Deep Sleep mode overview</li><li>Sketch for measuring RTC accuracy</li><li>Result of my own measurements</li><li>Appropriate corrective measures</li><li>Summary</li></ul><h3><strong>Real Time Clock (RTC) overview</strong></h3><p>To get the best overview, we download the latest datasheet for our processor from the <a href="https://documentation.espressif.com/esp32-c3_datasheet_en.pdf">Espressif website</a> and start on page 2 with the “Functional Block Diagram”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_0ti5EB6wmCVlAhOBMAhA.png" /><figcaption>Copyright Espressif Systems (Shanghai) Co., Ltd.</figcaption></figure><p>In the large “Peripherals” block, the “<strong>System Timer</strong>” block is located at the bottom center. This timer is driven by an extremely precise clock signal from the external oscillator; together with a second clock (located in the “<strong>RTC</strong>” section at the bottom right), it forms the basis of the system clock, which operates with millisecond precision and maintains accurate time over a period of several days. My tests over the course of several days showed that the system clock might have been off by perhaps two or three seconds over the span of a week.</p><p>This means that I can provide an ESP32-C3 processor with the exact time once at startup, and it can then reliably provide the current time over a period of several weeks. However, there is a downside: <strong>the situation changes dramatically when I put the processor into deep-sleep mode</strong>. Before we move on to the next point, I would like to draw your attention to a small “dark gray” detail in the diagram: some fields have a dark gray background, and the legend describes them as “<strong>Low power consumption components capable of working in Deep-sleep mode</strong>.” So, what exactly is deep-sleep mode?</p><h3>Deep Sleep mode overview</h3><p>In Deep Sleep mode, the ESP32-C3 achieves its lowest power state while still maintaining the ability to wake up on a timer or external triggers.</p><ul><li><strong>Core CPU, Main RAM, and digital peripherals</strong> are completely powered down.</li><li><strong>Power consumption</strong> drops to approximately <strong>5 μA</strong> (when powered from the chip’s VDD and using the internal slow RC oscillator).</li></ul><p>The fundamental reason to use Deep Sleep is <strong>to maximize battery life in remote, portable, or IoT (Internet of Things) devices</strong>.</p><p>When the ESP32-C3 is fully active (especially with Wi-Fi or Bluetooth enabled), it can draw between <strong>80 mA and 300 mA</strong> of current. A standard battery would be drained within hours or days.</p><p>By utilizing Deep Sleep, you shift the device’s operational model to a <strong>“Duty Cycle” pattern</strong>:</p><ul><li><strong>Sleep Phase (99% of the time):</strong> The chip turns off its CPU, radio, and RAM. Power consumption drops from ~100 mA down to roughly <strong>5 μA</strong>.</li><li><strong>Active Phase (1% of the time):</strong> The chip wakes up, takes a quick sensor reading, transmits the data via Wi-Fi/Bluetooth, and immediately goes back to sleep.</li></ul><p>Through this strategy, a device that would normally last only <strong>20 hours</strong> on a standard LiPo battery can easily run for <strong>months or even years</strong> on the exact same battery. It is the core mechanism that makes modern, maintenance-free wireless sensors possible.</p><p>However, this dramatic reduction in power consumption is only possible because the ESP32-C3 processor <strong>shuts down many of its otherwise active components</strong> when entering deep-sleep mode. Looking back at the block diagram above, these are all the system components with a light grey background (i.e., the vast majority of them).</p><p>On page 39, you will find a similar overview (“Figure 4–2. Components and Power Domains”): this shows the various “power domain” blocks, and you can find the “RTC” block at the bottom left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eg_xjHc5B-AaDeG3zubKGQ.png" /><figcaption>Copyright Espressif Systems (Shanghai) Co., Ltd.</figcaption></figure><p>To be absolutely clear: apart from this block, <strong>all other blocks are switched off during the deep-sleep phase,</strong> including the System Timer (top right).</p><p>You will find additional information about this RTC implementation on page 37:</p><h4>RTC Clock</h4><p>The RTC slow clock is used for RTC counter, RTC watchdog and low-power controller. It has three possible sources:</p><ul><li>External low-speed (32 kHz) crystal clock</li><li>Internal slow RC oscillator (typically about 136 kHz, and adjustable)</li><li>Internal fast RC oscillator divided clock (derived from the fast RC oscillator divided by 256)</li></ul><p>The RTC fast clock is used for RTC peripherals and sensor controllers. It has two possible sources:</p><ul><li>External main crystal clock divided by 2</li><li>Internal fast RC oscillator divide-by-N clock (typically about 17.5 MHz, and adjustable)</li></ul><p>In this RTC, our system time is generated by <strong>the “low-speed crystal,”</strong> which <strong>is significantly less accurate than the “System Timer.”</strong></p><p>At this point, I noticed that terms like “very inaccurate,” “useless,” or “reliable” appear in almost all publications and tutorials without any further explanation. Personally, I believe that many people have adopted these phrases from others without verifying the facts.</p><p>To dispel all the myths and stories surrounding the inaccuracy of the ESP32 system clock during deep sleep, I have created a small program that checks and reports the accuracy over a user-defined time period.</p><h3>Sketch for measuring RTC accuracy</h3><p>This sketch evaluates the drift and accuracy of the internal Real-Time Clock (RTC) of an ESP32-C3 microcontroller over an extended period.</p><p>Before I explain the individual steps to you, I will first explain some important settings in the sketch:</p><pre>#define WIFI_SSID           &quot;change to your router ssid&quot;<br>#define WIFI_PASSWORD       &quot;change to your password&quot;<br><br>#define SMTP_HOST           &quot;mail.gmx.net&quot;<br>#define SMTP_PORT           587<br>#define AUTHOR_EMAIL        &quot;change to the email address that is the sender&quot;<br>#define AUTHOR_PASSWORD     &quot;change to the password of the sender&quot;<br>#define RECIPIENT_EMAIL     &quot;change to the email address that is the recipient&quot;<br><br>// Sleep Mode Configuration (1 = Enabled, 0 = Disabled)<br>#define USE_DEEP_SLEEP          1</pre><p>The first block is the Wi-Fi part (change to the SSID and passsword of your own Wi-Fi network. The second block is the email part. As I’m located in Germany, I’m using tthe email provider “GMX.NET” for my email account.</p><p>It is very important to find out the “sender host” and “port” beforehand. It is also important to note that some email providers require additional authorization or — as is the case with Gmail — necessitate the creation of a dedicated password for this type of “external” email sending.</p><p>The final setting concerns the use of Deep Sleep mode: if it is not set to “1”, the standard (i.e., always-on) processor is used.</p><p>Let us now turn to the program flow: When the program starts for the first time, the ESP32-C3 establishes a connection to the <strong>Wi-Fi router</strong>. Once the connection is established, a request is sent to an <strong>NTP server</strong> using the <strong>Network Time Protocol (NTP)</strong>, and the server responds with the current <strong>Coordinated Universal Time (UTC)</strong>. The time received is then used to set the ESP32-C3’s internal system clock.</p><p>If you have created clock programs yourselves, you will notice that I am not using the usual lines of code for this (more on that later, see “Don’t use this call”).</p><p>At this point, the program is “finished” and waits for the next program step — or enters <strong>deep sleep</strong> until the next program step.</p><p>Once the set time interval has elapsed (60 minutes in my case), the program proceeds to the next step (or wakes up from its deep sleep phase). The sequence resembles the initial startup: connecting to the Wi-Fi router, querying the NTP time, and disconnecting. The major difference compared to the initial startup is that <strong>the system time is no longer synchronized</strong> with the retrieved time, <strong>but merely compared against it</strong>.</p><p>The difference in seconds is stored in a file within the SPIFF partition. This is where the second interval comes into play: the settings specify that an email must also be sent after one hour has elapsed. This email lists the current time difference and includes the generated file as an attachment.</p><p>In plain terms, this means that with these settings, you will receive 24 emails a day keeping you updated on the accuracy of your ESP32-C3. Please note that some email providers might classify such emails as spam due to the constant stream of messages.</p><p>I chose this type of “communication” because it allows me to test the processors without additional components (displays) while still obtaining a precise overview.</p><h4>Don’t use this call</h4><p>If you have previously programmed ESP32 clocks with time synchronization, this line will be very familiar to you:</p><pre>configTime(0, 0, NTP_SERVER_PRIMARY, NTP_SERVER_BACKUP);</pre><p>This line of code serves to provide the necessary NTP server URLs to the `<em>time.h</em>` library; additionally, the call sets up <strong>automatic time synchronization in the background</strong>. This means that as soon as the <em>time.h</em> library detects that the ESP32 is “online,” the system time is synchronized with the NTP time — completely without any intervention on our part.</p><p>With a standard clock, this behavior is highly desirable, but in our specific case, it is <strong>completely counterproductive</strong>. After all, we want to detect any potential time difference without any retrospective synchronization of the system time having taken place.</p><p>For our purposes, then, the rule is: <strong>hands off this call</strong>!</p><h3>Result of my own measurements</h3><p>I ran two ESP32-C3 Super Mini boards in parallel and unattended. One of the two ran in “always-on” mode, while the other entered deep sleep between the hourly time checks. To be honest, I was somewhat surprised by the result.</p><h4>Always On Mode</h4><p>The first surprise was that <strong>the ESP32-C3 achieves an accuracy of 2 seconds in “Always On Mode,”</strong> even after several days of continuous operation. This suggests that the processor likely remains highly accurate even after several weeks.</p><h3>Deep Sleep Mode</h3><p>The second surprise was the even greater deviation of the internal clock in deep sleep mode. <strong>After 78 hours</strong> (3 days and 6 hours) of operation, <strong>the difference between the RTC clock and UTC time is 3,033 seconds</strong> (equivalent to approximately 50 minutes). Or, expressed differently: the inaccuracy increases by about 38 seconds for every 60 minutes of deep sleep.</p><h3>Appropriate corrective measures</h3><p>You can take two measures to improve accuracy. One is to connect an external RTC module to the ESP32-C3, thereby significantly improving the accuracy of the system clock. The slight downside is that you will need to modify your program code in several places.</p><p>The second option involves simply adding to or subtracting from the internal time base. In my specific case, the deviation amounts to slightly more than 38 seconds per deep sleep phase.</p><h3>Summary</h3><p>With this test program, you determine the accuracy of the ESP32-C3’s internal system clock in “always-on” and Deep Sleep modes. The results are sent to you via email on an hourly basis.</p><h3>App Source Code</h3><p>You can find all the code collected in <a href="https://github.com/AndroidCrypto/ESP32_C3_Long_Term_RTC_Clock_Test">my GitHub repository</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ccb7412fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use the Time Cluster on an ESP32-C6 Zigbee Time Coordinator and End Device]]></title>
            <link>https://medium.com/@androidcrypto/how-to-use-the-time-cluster-on-an-esp32-c6-zigbee-time-coordinator-and-end-device-9966c89c31d5?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/9966c89c31d5</guid>
            <category><![CDATA[zigbee-time-cluster]]></category>
            <category><![CDATA[zigbee]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[coordinator]]></category>
            <category><![CDATA[esp32-c6]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 11:02:07 GMT</pubDate>
            <atom:updated>2026-08-18T11:02:07.877Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>Time Cluster</strong> is a useful feature within the <strong>Zigbee ecosystem</strong>, as it enables the standardized distribution of the current time from a Zigbee Coordinator to paired routers and end devices. While the Time Cluster appears in a few Arduino Zigbee examples, it is often treated merely as a minor add-on and is not particularly well-documented. In this tutorial, I will show you how to set up the Time Cluster on a<strong> Zigbee Coordinator</strong> and subsequently utilize that time data on a <strong>Zigbee end device</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eoKykwPwfxHRYobZPgfTNg.png" /><figcaption>On the left is the coordinator, and on the right side is the end device.</figcaption></figure><p>This tutorial is part of a series on Zigbee, specifically focusing on connecting to the ESP32-C6 processor (overview article: <a href="https://medium.com/@androidcrypto/how-to-use-an-esp32-c6-as-zigbee-coordinator-or-end-device-overview-e70cfa7f45f9"><strong>How to use an ESP32-C6 as Zigbee Coordinator or End Device</strong></a>). Since I cover all the basics of Zigbee in the overview article, I strongly recommend reading this article beforehand.</p><h3>Topics of this tutorial</h3><ul><li>Source for an accurate, up-to-date time</li><li><strong>Important Warning Regarding Arduino ESP32 Board Versions</strong></li><li>Setting up the ESP32-C6 (Zigbee Coordinator)</li><li>What is the Time Cluster used for?</li><li>Setting up the ESP32-C6 (Zigbee Coordinator) with a one-time Wi-Fi connection to retrieve the current NTP time</li><li>Setting up the ESP32-C6 Light (Zigbee End Device)</li><li>Zigbee internal time handling</li><li>Summary</li></ul><h3>Source for an accurate, up-to-date time</h3><p>An important aspect of this project concerns the source for obtaining an accurate, up-to-date time. Typically, we utilize freely available <strong>Network Time Protocol (NTP) servers</strong> on the internet for this purpose, which can be accessed via a Wi-Fi router. However, a challenge arises here: our Zigbee coordinator fully dedicates its transceiver to the Zigbee application, preventing us from simultaneously utilizing the Wi-Fi interface. For this reason, I have written a supplementary tutorial that describes in detail how to employ a second ESP32 to handle Wi-Fi communication with the NTP server and transmit the time to our ESP32-C6 coordinator via a UART interface; I therefore strongly recommend reading the tutorial “<a href="https://medium.com/@androidcrypto/how-to-create-an-esp32-based-ntp-time-server-for-an-esp32-c6-zigbee-coordinator-c447eaa4f475?sharedUserId=androidcrypto"><strong>How to create an ESP32-based NTP time server for an ESP32-C6 Zigbee coordinator</strong></a>” in parallel with this guide.</p><h3>Important Warning Regarding Arduino ESP32 Board Versions</h3><p>While I was writing this tutorial, Espressif updated its <a href="https://github.com/espressif/arduino-esp32/">Arduino ESP32 library</a> twice—first from version 3.3.8 to <strong>3.3.9</strong>, and later to <strong>3.3.10 and 11</strong>. The jump to version 3.3.9 was intended to fix a bug within the Zigbee Time Cluster.</p><p>The issue stems from the differing time bases used for the timestamps: while a standard timestamp relies on UTC time—“This<strong> count starts at the Unix Epoch on January 1st, 1970 at UTC”—the</strong> Zigbee timestamp uses a different starting point: “<strong><em>The Zigbee standard base time is defined as the number of seconds since January 1, 2000, 00:00:00 UTC.</em></strong>”</p><p>However, this differing time base was not taken into account within the library. This issue goes unnoticed when both the coordinator and the end device are ESP32-based. Yet, as soon as commercial Zigbee devices are used, the incorrect time base becomes apparent. <strong>Unfortunately, a new error crept in while fixing this issue, preventing the use of the Time Cluster</strong>.</p><p>I have reported this bug to Espressif and <a href="https://github.com/espressif/arduino-esp32/issues/12676"><strong>opened an issue</strong></a>, which is currently being processed and <strong>will get fixed with the next release</strong>!</p><blockquote><strong>Urgent warning</strong>: If you intend to use the <strong>Time Cluster</strong> in your ESP32 project, you <strong>must under no circumstances use versions 3.3.9 or 3.3.10 or 3.3.11</strong>. Regarding future versions, I need to wait for the bug to be fixed before I can give the all-clear. <strong>The last usable version is 3.3.8</strong>.</blockquote><p>In addition to downgrading to version 3.3.8, there is a <strong>second way</strong> to use the Time Cluster with newer Arduino ESP32 versions. If you are using Arduino ESP32 version 3.3.11, there is a fix available in the pull request tab of the GitHub repository: <a href="https://github.com/espressif/arduino-esp32/pull/12799/changes">https://github.com/espressif/arduino-esp32/pull/12799/changes</a>. Go to the “Files Changed” tag, download the <em>Zigbee.cpp</em> file, and replace the original one with this one. See the below “third way” to find the file on your computer.</p><p>This is the <strong>third way</strong>, but I do not recommend this. However, to achieve a working Time Cluster in the meantime, you need to modify the Arduino ESP32 library (specifically, the source code) in two places. Here are the instructions:</p><ol><li>The most important tip is to <strong>use a simple text editor</strong> for the modification—such as the Arduino IDE, Notepad, or similar software. Be cautious with “more advanced” software, which might insert unwanted and sometimes invisible control characters into the code, rendering the entire library unusable.</li><li>The second most important point: <strong>create a backup copy</strong> of every file you intend to modify so that you can revert to the original version at any time if your change fails.</li><li>To restore full functionality to the Time Cluster, you need to make changes in two places within a single file (<strong><em>ZigbeeEP.cpp</em></strong>). Locating this file on your computer can be slightly tricky because it is classified as a “system” or “hidden” file and is therefore not immediately visible. You should first find out how to display hidden files in your file manager (please use Google or similar).</li><li><strong>Where is the file located?</strong> Since I use macOS, I typically find library files at the following path: `&lt;Drive&gt;/Users/&lt;Username&gt;/Library/Arduino15/packages/esp32/hardware/esp32/3.3.11/libraries/Zigbee/src/`. Please note that the “<em>3.3.11</em>” in the path refers to the currently installed Arduino ESP32 version. If, for example, you are using “3.3.10,” you must adjust the path accordingly!</li><li>Open the file with TextEdit and search for “<strong><em>ZigbeeEP::getTime</em></strong>”. Scroll down to the section: “<em>if (!readClusterAttribute(&amp;read_req)) { return tm(); }</em>”. You need to comment out (or delete) this part: “<em>/* if (!readClusterAttribute(&amp;read_req)) { return tm(); }*/</em>”. In its place, copy “<em>esp_zb_zcl_read_attr_cmd_req(&amp;read_req);</em>”. Now look for the second location: “<strong><em>ZigbeeEP::getTimezone</em></strong>” (in my case, this is in the function immediately below). Look for the line again and make the same changes. I have compiled the necessary changes here:</li></ol><pre>File ZigbeeEP.cpp<br>...<br>tm ZigbeeEP::getTime(uint8_t endpoint, int32_t short_addr, esp_zb_ieee_addr_t ieee_addr) {<br>  ...<br>  /*  <br>  if (!readClusterAttribute(&amp;read_req)) {<br>    return tm();<br>  }<br>  */<br>  // taken from version 3.3.8<br>  esp_zb_zcl_read_attr_cmd_req(&amp;read_req);<br>...<br>}<br><br>int32_t ZigbeeEP::getTimezone(uint8_t endpoint, int32_t short_addr, esp_zb_ieee_addr_t ieee_addr) {<br>  ...<br>  /*<br>  if (!readClusterAttribute(&amp;read_req)) {<br>    return 0;<br>  }<br>  */<br>  // taken from version 3.3.8<br>  esp_zb_zcl_read_attr_cmd_req(&amp;read_req);<br>  ...<br>}</pre><p><strong>Save the changes and close the file—you&#39;re done!</strong></p><h3>Setting up the ESP32-C6 (Zigbee Coordinator)</h3><p>There are three important changes to the original switch coordinator sketch:</p><ol><li>The sketch is receiving timestamps of the current UTC via the UART interface</li><li>Save the UTC time in the Real-Time Clock (RTC) and calculate the local time (which, in the end, gives an offset to the UTC)</li><li>Synchronize the time with the Zigbee Time Cluster</li></ol><h4>Receive timestamps via the UART interface</h4><p>Data exchange via the UART interface is straightforward: we define two pins for the task (one transmit—TX—and one receive—RX—channel) and wait until we receive data from the other ESP32. As soon as the received number exceeds a certain threshold, we acknowledge receipt with an “OK” and pass it on to the next routine.</p><pre>in header:<br>#define SERIAL_UART_RX_PIN 5<br>#define SERIAL_UART_TX_PIN 4<br><br>in setup():<br>// setup the second UART interface<br>Serial1.begin(115200, SERIAL_8N1, SERIAL_UART_RX_PIN, SERIAL_UART_TX_PIN);<br><br>in setup() and loop():<br>while (receivedTime &lt; UTC_RECEIVED_TIMESTAMP) {<br>  if (Serial1.available()) {<br>    String ts = Serial1.readStringUntil(&#39;\n&#39;);<br>    receivedTime = (time_t)ts.toInt();<br>    if (receivedTime &gt; UTC_RECEIVED_TIMESTAMP) {<br>      Serial1.println(&quot;OK&quot;);<br>      Serial1.println(&quot;OK&quot;);<br>      Serial1.println(&quot;OK&quot;);<br>      Serial.println(&quot;Send OK to the NTP Timeserver&quot;);<br>    }<br>  }<br>  delay(100);<br>}</pre><h4>Save the UTC time and calculate the local time and offset</h4><p>We take the received timestamp and store it in a struct, which we then save to the RTC using “settimeofday.” The next step utilizes a time zone string (in my case, for Germany/Europe) to calculate the local time. This is accomplished using the built-in “<em>time.h</em>” library. We then retrieve the local time and subtract the UTC time from it to obtain the offset between the two time zones.</p><pre>in header:<br>const char* TZ_INFO = &quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;;<br><br>in setup() and loop():<br>void setTimeByUtcTimestamp(time_t newTime) {<br>  // set the system time (UTC)<br>  struct timeval tv = { .tv_sec = newTime, .tv_usec = 0 };<br>  settimeofday(&amp;tv, NULL);<br>  // convert the UTC in local time<br>  setenv(&quot;TZ&quot;, TZ_INFO, 1);<br>  tzset();<br>  // start Zigbee with the local time<br>  getLocalTime(&amp;timeinfo);<br>  // calculate the offset, e.g., 7200 seconds<br>  localOffset = (int32_t)(newTime - mktime(&amp;timeinfo));<br>  if (localOffset &lt; 0) localOffset *= -1;<br>  Serial.printf(&quot;setTimeByUtcTimestamp localOffset: %d\n&quot;, localOffset);<br>}</pre><h4>Synchronize the time with the Zigbee Time Cluster</h4><p>Unfortunately, this part is not shown in the examples and is therefore easily overlooked. In the “<em>setup()</em>” section, we add the Time Cluster to our Zigbee “<em>zbSwitch</em>” object and populate the current UTC time and offset.</p><p>Although we have supplied our system clock with the current time, the Time Cluster unfortunately does not update subsequently. Users of the ESP32-IDF can utilize automatic synchronization; however, this feature is currently unavailable in the Arduino Zigbee implementation.</p><pre>in setup():<br>zbSwitch.addTimeCluster(timeinfo, localOffset);<br><br>in loop():<br>getTimeByUtcTimestamp();<br>zbSwitch.setTime(timeinfo);<br>zbSwitch.setTimezone(localOffset);</pre><p>Therefore, within our program loop, we must regularly update the UTC time—and, where applicable, the offset as well. In my sketch, I do this every 60 seconds; however, this makes it clear that the Zigbee end devices rarely, if ever, receive a “real-time” timestamp but rather rely on a time base that is consistently off by up to 60 seconds.</p><h4>Where to find the sketches?</h4><p>You can find the complete combination of a UART transmitter and receiver sketches in my <a href="https://github.com/AndroidCrypto/ESP32_based_NTP_Time_Server/">GitHub repository</a> that is used for the tutorial “<a href="https://medium.com/@androidcrypto/how-to-create-an-esp32-based-ntp-time-server-for-an-esp32-c6-zigbee-coordinator-c447eaa4f475?sharedUserId=androidcrypto"><strong>How to create an ESP32-based NTP time server for an ESP32-C6 Zigbee coordinator</strong></a>”.</p><h3>What is the Time Cluster used for?</h3><p>Now, however, we should clarify exactly how the end devices utilize the time provided by the Time Cluster. Consider a smart radiator thermostat that controls the heating system to warm up an apartment in the morning and lower the temperature again in the evening to conserve energy. To achieve this, a “heating schedule” is stored within the thermostat; naturally, the thermostat must know the current time to set the appropriate temperature. We quickly realize that second-by-second precision is not critical in this context, as the heating system responds very sluggishly anyway. If necessary, the update interval can be set to a significantly shorter duration; however—particularly in the case of battery-powered units—the end devices typically query the time only at hourly intervals, rendering a shorter update interval pointless.</p><h3>Setting up the ESP32-C6 (Zigbee Coordinator) with a one-time Wi-Fi connection to retrieve the current NTP time</h3><p>While it is fundamentally sound, you likely do not want to create a dedicated ESP32 NTP time server and tightly couple it to the ESP32-C6 for your Zigbee experiments. For this reason, I am presenting a sketch here that combines both functions: <strong>synchronizing</strong> the ESP32-C6 with <strong>the current NTP time</strong> and using it as a <strong>Zigbee coordinator</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*HJzhPos6hZtWpqQub8XxXw.png" /><figcaption>The coordinator is setting up its Wi-Fi channel to retrieve the NTP time.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*wmytdC0tkLgLYlcUJciOqA.png" /><figcaption>The coordinator got the time and synchronized it with the internal RTC clock.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*NpOEGgHeHyRodvqor95zxA.png" /><figcaption>The coordinator has started Zigbee and set the Time Cluster data; the end device (right side) is waiting for data</figcaption></figure><p>Since it is preferable to avoid having the Wi-Fi interface active simultaneously with the Zigbee environment, I resolve this issue using two sequential processes:</p><ol><li>In “setup()”, we initialize the Wi-Fi connection to the router, establish a connection to the NTP time server, synchronize the retrieved time with the ESP32-C6 Real-Time Clock (including the current local time), and then shut down the Wi-Fi environment.</li><li>Next, we initiate the setup and initialization of the Zigbee environment and subsequently operate solely as a Zigbee coordinator.</li></ol><p>The downside of this method is that the ESP32-C6 system time drifts over the course of days and weeks of continuous operation. However, in my own experiments, the system clock remained well within acceptable limits even after several days, with the discrepancy amounting to seconds rather than minutes or hours. This makes the setup perfect for a small, standalone solution. You can find the sketch itself in my GitHub repository for all ESP32-C6 Zigbee projects (see link below).</p><h3>Setting up the ESP32-C6 Light (Zigbee End Device)</h3><p>This point, too, is addressed only peripherally in the official examples. The retrieval of time data from the coordinator is already built into our Switch class—or rather, its predecessor, the ZigbeeED class—and we retrieve both the UTC time and the offset:</p><pre>in getTimeData():<br>struct tm timeinfoTc = zbLight.getTime();<br>int32_t timezoneOffset = zbLight.getTimezone();</pre><p>We once again use UTC to set our system time. Since we receive the offset directly, we use it to calculate the local time:</p><pre>time_t t = mktime(&amp;timeinfoTc);<br>struct timeval tv;<br>tv.tv_sec = t;<br>tv.tv_usec = 0;<br>// set system time (stored in internal RTC memory)<br>settimeofday(&amp;tv, NULL);<br>// optional: set timezone globaly for methods like localtime()<br>char tzConfig[32];<br>sprintf(tzConfig, &quot;GMT%s%ld&quot;, (timezoneOffset &gt;= 0) ? &quot;-&quot; : &quot;+&quot;, abs(timezoneOffset / 3600));<br>setenv(&quot;TZ&quot;, tzConfig, 1);<br>tzset();</pre><p>In my program, this update occurs every 60 seconds; however, this is necessary only for demonstration purposes, as the ESP32 features a rather accurate RTC that drifts by perhaps a few seconds over the course of a day—consequently, an update could be performed just once daily by an end device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PTM2BqD6J-GBC5snyzwSIA.png" /><figcaption>The end device (right display) is connected with the coordinator but has not asked for the Time Cluster data, so the internal RTC clock started at 01.01.1970 0:00</figcaption></figure><p>Since the purpose of this program is to demonstrate the Time Cluster, the display shows both the local time (“CET”) and “UTC.” Additionally, the offset in seconds and the number of seconds since the last time update are displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3z-YUA0foGW6xNImyyX_7A.png" /><figcaption>After 60 seconds, the end device is asking for the Time Cluster data and synchronizing its RTC clock. Please note the difference in seconds, as the (static) Time Cluster data is synchronized every minute only.</figcaption></figure><h3>Zigbee internal time handling</h3><p>When referring to an accurate time source, we typically utilize Network Time Protocol (NTP) servers. These provide <strong>Coordinated Universal Time (UTC)</strong> in the form of a timestamp, which counts the number of seconds elapsed since the epoch of <strong>January 1, 1970</strong>. For instance, we might receive a value of “<strong>1778923446</strong>” transmitted from our ESP32 NTP time server.</p><pre>[ZigbeeEP.cpp:402] setTime(): Setting time to 1778923446<br><br>https://www.epochconverter.com/ntp<br>Timestamp 1778923446<br><br>Date Time (UTC)            May 16. 2026, 09:24:06<br>Date Time (your time zone) May 16. 2026, 11:24:06</pre><p>However, <strong>Zigbee</strong> measures time in seconds since <strong>January 1, 2000, at 00:00:00 UTC</strong>. Consequently, we must first convert the received UTC timestamp so that we can use it within the Zigbee ecosystem. The formula for this is:</p><pre>Zigbee Timestamp = UTC Timestamp - 946684800</pre><p>To stick with our example, the <strong>Zigbee timestamp</strong> would be 1778923446–946684800 = <strong>1082651024</strong>. Fortunately, the two functions, “<strong>addTimeCluster()</strong>” and “<strong>setTime()</strong>” in the coordinator sketch, <strong>handle this task for us</strong>, allowing us to use the received UTC timestamp directly.</p><pre>Zigbee Time Cluster updated UTC timestamp 1082651024 localOffset 7200<br>Local time: 16.05.2026 11:24:06<br>UTC time:   16.05.2026 09:24:06</pre><p>A second point concerns the <strong>time zone</strong>, which is also referred to as the <strong>time offset</strong>. This refers to the number of seconds between UTC time and local time. For example, during daylight saving time, Germany is 2 hours ahead of UTC time—or, converted into seconds: <em>2 hours * 60 minutes * 60 seconds = </em><strong><em>7,200 seconds</em></strong>. In addition to the raw UTC time, you should always include the time zone on the Zigbee Coordinator; since some end devices specifically request the local time from the coordinator, this value should be set.</p><h3>Summary</h3><p>Using the Zigbee Time Cluster on an ESP32-C6 coordinator or end device is simpler than many think, yet setting it up requires considerable care. Unfortunately, the current official Arduino ESP32/Zigbee implementation is still buggy, but with the workaround shown, nothing stands in the way of successfully using the Time Cluster.</p><h3>Source code of the app</h3><p>You can find the complete code of the apps and additional material in my GitHub repository “<a href="https://github.com/AndroidCrypto/ESP32_C6_Zigbee_Coordinator"><strong>ESP32_C6_Zigbee_Coordinator</strong></a>”.</p><p>The coordinator part is in the “<strong><em>Esp32_C6_Zigbee_Switch_TimeCluster_WiFi_v06</em></strong>” subfolder; the end device sketch is here: “<strong><em>Esp32_C6_Zigbee_ED_Time_Cluster_OLED_v05</em></strong>”</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9966c89c31d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create an ESP32-based NTP time server for an ESP32-C6 Zigbee coordinator]]></title>
            <link>https://medium.com/@androidcrypto/how-to-create-an-esp32-based-ntp-time-server-for-an-esp32-c6-zigbee-coordinator-c447eaa4f475?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/c447eaa4f475</guid>
            <category><![CDATA[time]]></category>
            <category><![CDATA[wifi]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[ntp]]></category>
            <category><![CDATA[esp32-tutorial]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 09:57:25 GMT</pubDate>
            <atom:updated>2026-06-16T09:57:25.362Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial I will show you how to <strong>create a time server</strong> using an <strong>ESP32</strong> development board that retrieves the current world time (<strong>Universal Coordinated Time, UTC</strong>) from an <strong>NTP time server (Network Time Protocol server)</strong> via your Wi-Fi network and transmits it at regular intervals to an <strong>ESP32-C6</strong> development board, which acts as a <strong>Zigbee coordinator</strong>, via the <strong>UART (Universal Asynchronous Receiver-Transmitter)</strong> interface. This tutorial is a companion article to “<strong>How to Use the Time Cluster on an ESP32-C6 Zigbee Time Coordinator and End Device</strong>” (&lt;soon&gt;).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*g8oO91SpDbIR4rJWpNC5tA.png" /><figcaption>Left: ESP32-C6 as Zigbee Coordinator, Right: ESP32 as NTP Time Server</figcaption></figure><p>At this point you might ask yourselves: <em>Why do we need a second ESP32 processor to query the NTP time data via the internet — our ESP32-C6 can already use Wi-Fi in addition to Zigbee and Bluetooth</em>? The short answer is: because it makes a lot of technical sense, and for the longer answer I wrote this tutorial.</p><p>This tutorial is part of a series on Zigbee, specifically focusing on connecting to the ESP32-C6 processor (overview article: <a href="https://medium.com/@androidcrypto/how-to-use-an-esp32-c6-as-zigbee-coordinator-or-end-device-overview-e70cfa7f45f9"><strong>How to use an ESP32-C6 as Zigbee Coordinator or End Device</strong></a>). Since I cover all the basics of Zigbee in the overview article, I strongly recommend reading this article beforehand.</p><h3>Topics of this tutorial</h3><ul><li>Structure of the radio module in an ESP32-C6 microprocessor</li><li>Hardware required for this tutorial</li><li>Wiring the two processors</li><li>Power supply for the two development boards</li><li>Setting up the time server sketch</li><li>NTP Time Receiver sketch</li><li>Summary</li></ul><h3>Structure of the radio module in an ESP32-C6 microprocessor</h3><p>Our ESP32-C6 processor, with its integrated radio module, can utilize <strong>Wi-Fi, Bluetooth Low Energy, and Zigbee</strong> wireless technologies. All three technologies primarily use the globally license-free <strong>2.4 GHz ISM band (2.400 to 2.4835 GHz)</strong>, although they allocate the frequency range differently. Although the three technologies use (or can use) different subfrequencies, they all rely on a single transmitter on the chip. To use two or three technologies simultaneously, the radio module must switch between protocols, which always results in a (albeit brief) <strong>interruption</strong> of the previously used technology.</p><p><strong>For the stability of your Zigbee network, it is crucial that your coordinator remains reachable for “its” devices and routers at all times</strong>. To stay on topic with our tutorial: during the synchronization of our device with the NTP server (including establishing the connection to the Wi-Fi router), the Zigbee network has no active coordinator.</p><p>For this reason, you should resist the temptation to connect your ESP32-C6 coordinator directly to the internet, but instead use a second, arbitrary ESP32 processor (ESP32, -S3, C3 or second C6 board).</p><h3>Hardware required for this tutorial</h3><p>For an NTP time server, you need any processor from the ESP-32 family. This means that in addition to the <strong>ESP32</strong>, its variants <strong>S2, S3, C3, C5, or C6</strong> can also be used, as long as they have a Wi-Fi module. This <strong>excludes the H2 variant</strong> due to its lack of Wi-Fi support. Connecting a small <strong>OLED display</strong> (e.g., SSD1306 with a 128x64 pixel resolution) is recommended, as we will be displaying the time as well as status information related to time synchronization. Since I still have an Ideaspark ESP32 development board with an OLED display, I use it for my NTP time server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*E0At4hYLJVaHJ7zeqgXXNw.png" /><figcaption>ESP32 serves as NTP Time Server</figcaption></figure><p>To perform time synchronization, an ESP32-C6 processor, also with a connected OLED display, is required. This will later serve as the Zigbee coordinator and is therefore not needed separately.</p><h3>Wiring the two processors</h3><p>Since both processors use an OLED display with an <strong>I2C</strong> interface, two I2C data lines (SCL and SDA) and the display’s power supply (VCC and Ground) are required for each. To connect the two processors via the <strong>UART</strong> interface, two data lines (Transmit, TX, and Receive, RX) are also needed. Furthermore, <strong>a connection between the GND pins of both processors is essential</strong> to establish a baseline signal level.</p><h3>Power supply for the two development boards</h3><p>In principle, you could power both processors with a shared power supply. For example, you could power the ESP32-C6 (coordinator) via the USB port and the ESP32 (NTP time server) via a wire connecting the two 3.3V pins. This generally works well, but in practice I’ve sometimes encountered seemingly inexplicable malfunctions, and the ESP32 sometimes wouldn’t start.</p><p>The main cause of most problems lies in the power surges that occur when the Wi-Fi channel is switched on and communicating. These <strong>surges can reach several hundred milliamperes</strong> and lead to a dreaded “<strong>brownout</strong>,” where a voltage drop causes one or even both processors to restart.</p><h4>Recommendation</h4><p>For this reason,<strong> I advise you to power both development boards via their respective USB interfaces</strong>. In this case, the two development boards <strong>must absolutely not be connected at its 3.3 volt interfaces!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*65OT8itBoBasdE11yjveZg.png" /><figcaption>ESP32-C6 serves as Zigbee Coordinator</figcaption></figure><h3>Setting up the time server sketch</h3><p>The program uses the following sequence: After setting up the serial interfaces and the display, the program enters a loop:</p><p>1. Establishes a Wi-Fi connection to the router</p><p>2. Connects to an NTP time server, retrieves the UTC time, and sets the ESP32 system time (“RTC”)</p><p>3. Terminates Wi-Fi use (stops Wi-Fi)</p><p>4. Converts the UTC time to the local time</p><p>5. Sends the UTC time to the ESP32-C6 (Zigbee coordinator)</p><p>6. Displays the local time (large digits) and UTC time on the display</p><p>7. Evaluates the response from the ESP32-C6 regarding successful transmission and displays it on the screen</p><p>Since the ESP32 processor has a fairly reliable internal real-time clock (<strong>RTC</strong>), I set the synchronization interval to 60 minutes. If synchronization fails (no “OK” response from the ESP32-C6), the next synchronization will occur after 60 seconds.</p><p>I have included an additional option for “ad hoc” time transmission: when the <strong>Boot button</strong> is clicked, an attempt is made to synchronize the UTC time with the ESP32-C6 board.</p><p>One more note about <strong>local time</strong>: I don’t use a fixed offset for converting UTC to local time, as this changes when switching from winter to summer time (daylight saving time). Instead, I use the built-in “<strong><em>time.h</em></strong>” library, which allows for a simple conversion. However, this requires an information string as a parameter, representing the local time zone and its changeover dates. In my sketch, you’ll see the line `<strong><em>TZ_INFO = “CET-1CEST,M3.5.0,M10.5.0/3”</em></strong>`, which represents the German time zone (Berlin). Please adjust this line to your local time zone; to do this, look in the “<a href="https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv">zones.csv</a>” file and extract your parameter string. On the ESP32, this local time is used exclusively for display purposes; the ESP32-C6 will later use both UTC and local time.</p><h3>NTP Time Receiver sketch</h3><p>Even though the tutorial’s title might suggest otherwise, <strong>the receiver sketch contains no code for using the ESP32-C6 as a Zigbee coordinator</strong>; instead, it focuses on the essential element: <strong>receiving UTC time via the UART interface</strong>.</p><p>When a number is received via the UART interface, it is passed to the “<em>time.h</em>” library to set the ESP32-C6’s <strong>Real-Time Clock (RTC)</strong>. An <strong>acknowledgment</strong> (“OK”) is sent to the NTP time server via the UART interface. Additionally, the local time is calculated using the time zone configuration string (“<strong>POSIX</strong>”). Both times are updated on the display every second. Additionally, the <strong>RGB LED</strong> briefly lights up in white.</p><h3>Summary</h3><p>Using the UART interface is the simplest way to quickly and efficiently transfer small amounts of data between two ESP32 development boards. Retrieving the current time is a quick task thanks to freely available NTP servers, and this data can be transmitted to a second ESP32 processor — including a simple handshake — with just a few lines of code.</p><h3>Source code of the app</h3><p>You find the complete code of the app and additional material in my GitHub repository “<a href="https://github.com/AndroidCrypto/ESP32_based_NTP_Time_Server"><strong>ESP32_based_NTP_Time_Server</strong></a>”.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c447eaa4f475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Detailed Look at the Waveshare ESP32-C6 1.9-inch ST7789 TFT Display with Touch Interface]]></title>
            <link>https://medium.com/@androidcrypto/a-detailed-look-at-the-waveshare-esp32-c6-1-9-inch-st7789-tft-display-with-touch-interface-ced633da6291?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/ced633da6291</guid>
            <category><![CDATA[waveshare]]></category>
            <category><![CDATA[esp32-c6]]></category>
            <category><![CDATA[sd-card]]></category>
            <category><![CDATA[tft-display]]></category>
            <category><![CDATA[touch]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 10:46:56 GMT</pubDate>
            <atom:updated>2026-07-04T19:39:58.562Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial covers the <strong>Waveshare ESP32-C6 development board</strong> featuring a <strong>1.9-inch TFT display</strong> with a <strong>resolution of 170 x 320 pixels</strong> and an optional <strong>touch interface</strong>. Although the board is described on the <a href="https://www.waveshare.com/esp32-c6-lcd-1.9.htm">product page</a> and in the <a href="https://docs.waveshare.com/ESP32-C6-LCD-1.9">wiki</a>, there are still a few surprises encountered during use — surprises I’d like to save you from experiencing. Naturally, all code examples are available in my GitHub repository, which might just end up becoming the “unofficial” product repository :-)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_wE-CmGf1bXf6JJrJKlFIg.png" /></figure><h3><strong>Board Feature Overview</strong></h3><ul><li><strong>ESP32-C6FH8</strong> processor with <strong>8 MB flash</strong> memory and <strong>8 MB PSRAM</strong></li><li>1.9-inch TFT display with <strong>ST7789V2</strong> chip and <strong>170 x 320 pixel</strong> resolution</li><li>Optional: Touch interface with <strong>CST816</strong> chip *1)</li><li>Optional: <strong>WS2812</strong> RGB LED *1)</li><li>Optional: <strong>IPEX1 connector</strong> for an external antenna *1)</li><li><strong>MicroSD card reader</strong></li><li><strong>QMI8658</strong> 6-axis motion (IMU) sensor</li><li><strong>TCA9554</strong> 8-channel GPIO expander</li><li>JST 1.25 connector for a <strong>3.7V lithium battery</strong>, featuring integrated charge/discharge circuitry and a charging status LED</li><li>Reset and Boot buttons</li><li>1) If you select the touch option, you also get the IPEX1 connector; conversely, if you choose the “without touch” option, the RGB LED is included instead.</li></ul><h3><strong>TFT Display</strong></h3><p>If you have already worked with the <strong>ST7789 display type</strong>, getting this display up and running will be quite easy. The SPI interface pins are documented, and for initial testing, I use the Adafruit ST7735/ST7789 graphics library.</p><p>However, there are two specific details to note: to achieve high speed (especially important for frequent drawing operations), you should use the hardware SPI mode, which I configure for the correct pins as follows:</p><p><em>SPI.begin(TFT_SCLK, TFT_MISO, TFT_MOSI, TFT_CS);</em></p><p>The second detail concerns the backlight circuitry: it is controlled via a MOSFET and operates inversely — meaning `<em>digitalWrite(TFT_BL, </em><strong><em>LOW</em></strong><em>)</em>` turns the <strong>backlight on</strong>. To ensure compatibility with other projects, I am providing programs for the three graphics libraries “Adafruit ST7789”, “TFT_eSPI”, and “LovyanGFX”. Please note that<strong> you need a patched library for TFT_eSPI</strong>. You can find details on this in my tutorial “<a href="https://medium.com/@androidcrypto/getting-started-with-an-esp32-c6-supermini-device-connected-to-an-st7789-tft-display-76b0809e292f"><strong>Getting Started with an ESP32-C6 Supermini device connected to an ST7789 TFT display</strong></a>”.</p><h3><strong>Touch Interface</strong></h3><p>Waveshare documents the pinout on the product page, and I attempted to get the <strong>CST816 driver chip</strong> working using several different libraries. This chip is controlled and queried via the I2C interface; additionally, two lines — Interrupt (IRQ) and Reset (RST) — are involved.</p><p>Unfortunately, none of the libraries worked or registered any touch events. I eventually found a clue in the official GitHub repository for the board within the “Arduino/08_LVGL_Test” example (specifically in the `getTouch` function): <strong>although the IRQ and RST pins are listed and appear in the schematic, they are not physically connected to the processor</strong>. They are marked as <strong>“NC” (Not Connected)</strong> on the product page, a detail that is very easily overlooked. Why are these pins explicitly mentioned if they cannot actually be used?</p><p>This explains why none of the standard libraries worked, as they all require one or both of these pins to detect touch events.</p><p>The solution is to continuously read (“poll”) a specific register of the CST816 chip via the I2C interface to detect touches and retrieve the screen coordinates. I have provided an example program for this as well, though only for the TFT_eSPI graphics library (for the microSD card reader, I created an example program compatible with all three graphics libraries that also includes touch detection).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Dj0kG6y3jKQj9xSA21Kcbg.png" /></figure><h3><strong>MicroSD Card Reader</strong></h3><p>Since the ESP32-C6 has only one available SPI interface, four of the SD card reader’s SPI pins are shared with the display’s pins; only the “Chip Select” (“SD_CS”) pin is assigned its own dedicated pin. As with any <strong>shared bus system</strong>, the order in which the various devices (in this case, the TFT display and the SD card reader) are initialized is crucial. I am therefore providing an example program for the three graphics libraries that displays two JPG images and two BMP images on the screen. The next image appears each time the screen is touched. I use the “JPEGDEC” library for JPG images, whereas I draw BMP images pixel by pixel — a process that is significantly slower than rendering JPGs.</p><h3><strong>QMI8658 Motion Sensor</strong></h3><p>This sensor is an <strong>IMU (Inertial Measurement Unit)</strong> — a spatial sensor system that measures an object’s motion, orientation, and attitude in 3D space. It is used for precise orientation and navigation, often serving as a backup when GPS signals are unavailable. It measures acceleration and angular velocity for the X, Y, and Z axes, which is why it is also referred to as a 6-axis sensor. It communicates via the I2C interface, and I use the <strong>QMI8658</strong> Arduino library to retrieve the sensor data. In addition to the six values ​​mentioned, the chip includes a built-in temperature sensor, the readings of which can also be accessed.</p><p>I haven’t tried the much more professional “SensorLib” library, though it is said to work with this sensor as well.</p><p>This sensor works reliably and without surprises; however, Waveshare failed to specify the orientation of the three axes. To ensure we are referring to the same directions, let’s place the board flat on a table in landscape orientation with the USB port facing left:</p><ul><li>X-axis: points forward, away from the long edge</li><li>Y-axis: points to the right, away from the short edge</li><li>Z-axis: points upwards, away from the display</li></ul><p>The directions mentioned yield positive (increasing) values, while the opposite directions yield negative (decreasing) values.</p><p>I will demonstrate how it works using the Adafruit graphics library.</p><h3><strong>Battery Connection</strong></h3><p>You can connect a <strong>3.7-volt lithium battery</strong> to the two-pin JST 1.25 connector here; it is charged via the USB-C port. The polarity follows the standard convention, but you should verify your board’s polarity before connecting the battery to avoid destroying the battery or causing further damage.</p><p>A green LED next to the USB port lights up when the battery is charging.</p><p>Discharge protection: The board lacks discharge protection; therefore, <strong>you should only use batteries with a built-in Battery Management System (BMS)</strong>. Otherwise, the battery could undergo uncontrolled deep discharge, which is detrimental to its lifespan.</p><p>However, the board does feature integrated voltage monitoring connected to GPIO 0 via a resistive voltage divider. Unfortunately, unlike on some other boards, this monitoring circuit cannot be switched on or off; consequently, even during long periods of inactivity (such as deep sleep), a small but constant current flows through the voltage divider, which will eventually drain the battery.</p><p>According to the datasheet, the voltage divider consists of 200kΩ and 100kΩ resistors, reducing the input voltage to one-third of its value: e.g., 3.7 volts becomes 1.233 volts at the Analog-to-Digital Converter (ADC) input. Since the readings fluctuate despite a constant voltage, I read 20 values ​​and calculate the average to obtain a more stable reading.</p><p>I divide the resulting values ​​by the constant `BATTERY_VOLTAGE_DIVIDER` (322.7). The “irregular” value arises from the calculated 1/3 divider (since we receive the raw values ​​in millivolts, we divide by 333); however, every component has a tolerance, which in practice would result in a slightly inaccurate reading. I simply measured the actual voltage with a multimeter and then adjusted the divider so that the values ​​displayed on the ESP32-C6 and the multimeter matched (this constitutes the “calibration”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*y--EXogklI20FXJt5Q3yxw.png" /></figure><h3><strong>TCA9554 GPIO Extender</strong></h3><p>This board features a chip I haven’t encountered on any of my previous boards: the <strong>TCA9554 8-channel GPIO extender</strong>. Since the SPI and I2C interfaces already utilize a significant number of GPIOs, this extender is employed to provide additional I/O capability. It uses the I2C interface, and with the help of the Adafruit xCA9554 library, you can utilize 8 extra GPIOs for input or output tasks. On the board’s pinout, these are labeled <strong>EXIO0 through EXIO7</strong>. Using the library, you define whether each port should operate as an input or an output. <br>In my example, eight red buttons are displayed on the screen; touching a button changes its color to green and lights up the LED connected to the corresponding port, while a subsequent touch turns the LED off again (Adafruit graphics library).</p><h3><strong>Does this board have any downsides?</strong></h3><p>At first glance, it looks like the perfect board; however, there is one weak point: the SPI interface. The ESP32-C6 has an SPI interface that is shared between the display and the microSD card reader (bus sharing). As you have seen, this parallel operation works excellently.</p><p>However, <strong>the manufacturer does not route the base SPI pins to the breadboard-compatible headers</strong>, meaning <strong>you cannot connect additional SPI devices</strong> (such as an NFC card reader). Of course, there are small adapter boards you could insert into the reader slot to access the signals, but that would be more of a temporary DIY solution than a permanent setup.</p><h3><strong>Official GitHub Repository</strong></h3><p>Waveshare does provide a <a href="https://github.com/waveshareteam/ESP32-C6-LCD-1.9">dedicated repository for this board</a> that includes feature examples. In addition to Arduino IDE support, there are examples for ESP-IDE, as well as the pre-installed firmware available as a ready-to-upload binary. I found these examples unhelpful, however, as they are spread across multiple files and offer no guidance on controlling the display or the touch functionality.</p><p>Note: Since this board has only been on sale since March 2026, the examples are just three months old — perhaps the manufacturer will expand upon them in the future.</p><h3><strong>Download links and version details of the software used</strong></h3><ul><li>Arduino IDE 2.3.8: <a href="https://www.arduino.cc/en/software">https://www.arduino.cc/en/software</a></li><li>esp32 Boards 3.3.8 (based on ESP-IDF v5.5.4): <a href="https://github.com/espressif/arduino-esp32">https://github.com/espressif/arduino-esp32</a></li><li>Adafruit ST7735|ST7789 1.11.0: <a href="https://github.com/adafruit/Adafruit-ST7735-Library">https://github.com/adafruit/Adafruit-ST7735-Library</a></li><li>Adafruit GFX 1.12.6: <a href="https://github.com/adafruit/Adafruit-GFX-Library">https://github.com/adafruit/Adafruit-GFX-Library</a></li><li>TFT_eSPI 2.5.43: <a href="https://github.com/Bodmer/TFT_eSPI">https://github.com/Bodmer/TFT_eSPI</a> (unpatched version)</li><li>TFT_eSPI (patched version) based on 2.5.4: <a href="https://github.com/AndroidCrypto/TFT_eSPI">https://github.com/AndroidCrypto/TFT_eSPI</a></li><li>LovyanGFX 1.2.21: <a href="https://github.com/lovyan03/LovyanGFX">https://github.com/lovyan03/LovyanGFX</a></li><li>CST816 Library (without version): created by myself</li><li>SD SD-Card Reader 1.3.0: <a href="https://github.com/arduino-libraries/SD">https://github.com/arduino-libraries/SD</a> (is included in esp32 boards)</li><li>JPEGDEC JPG Bibliothek 1.8.4: <a href="https://github.com/bitbank2/JPEGDEC">https://github.com/bitbank2/JPEGDEC</a></li><li>QMI8658 Arduino Library 1.0.1: <a href="https://github.com/lahavg/QMI8658-Arduino-Library">https://github.com/lahavg/QMI8658-Arduino-Library</a></li><li>Adafruit xCA9554 1.0.0: <a href="https://github.com/adafruit/Adafruit_XCA9554">https://github.com/adafruit/Adafruit_XCA9554</a></li><li>Waveshare Manufacturer Store Page: <a href="https://www.waveshare.com/esp32-c6-lcd-1.9.htm">https://www.waveshare.com/esp32-c6-lcd-1.9.htm</a></li><li>Waveshare Manufacturer GitHub Repository: <a href="https://github.com/waveshareteam/ESP32-C6-LCD-1.9">https://github.com/waveshareteam/ESP32-C6-LCD-1.9</a></li></ul><h3><strong>App Source Code</strong></h3><p>You can find all the code collected in my <a href="https://github.com/AndroidCrypto/ESP32_C6_Waveshare_1-9_inch_TFT_INOFFICIAL">GitHub repository</a>. For the patched TFT_eSPI library, please refer to my tutorial titled “<a href="https://medium.com/@androidcrypto/getting-started-with-an-esp32-c6-supermini-device-connected-to-an-st7789-tft-display-76b0809e292f"><strong>Getting Started with an ESP32-C6 Supermini device connected to an ST7789 TFT display</strong></a>”.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced633da6291" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrade your ESP32-S3 Nixie-style clock with a Web BLE interface]]></title>
            <link>https://medium.com/@androidcrypto/upgrade-your-esp32-s3-nixie-style-clock-with-a-web-ble-interface-06fde0070d9c?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/06fde0070d9c</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[esp32-tutorial]]></category>
            <category><![CDATA[over-the-air-update]]></category>
            <category><![CDATA[ntp]]></category>
            <category><![CDATA[ota]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 08:08:55 GMT</pubDate>
            <atom:updated>2026-06-03T08:08:55.898Z</atom:updated>
            <content:encoded><![CDATA[<p>If you followed my tutorial “<a href="https://medium.com/@androidcrypto/how-do-i-find-the-correct-connection-pins-for-an-esp32-s3-development-board-with-an-attached-tft-eb4bbbbac95b"><strong>How do I find the correct connection pins for an ESP32-S3 development board with an attached TFT display (ST7789)?</strong></a>”, you surely noticed the emulation of a Nixie-style clock. In the sketch presented there, the <strong>Wi-Fi credentials and the POSIX string</strong> (for controlling the local time zone) were hardcoded directly into the source code. In this tutorial, I will show you how to create a <strong>Web BLE-based configuration tool</strong> that allows you to <strong>transmit Wi-Fi credentials and the POSIX string</strong> to the Nixie clock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*_yU_d2MaPd8S8dGtWUwJJw.png" /></figure><h3>Topics of this tutorial</h3><ul><li>A Brief Overview of Web BLE</li><li>Initial Experiences with Web BLE Configuration</li><li>Cause of the Memory Shortage</li><li>Solution for the Out of Memory Problem</li><li>How do you switch between the two programs?</li><li>Required Hardware for the Nixie-Style Clock Project with Web BLE Configuration Interface</li><li>Find the Right Partition Scheme</li><li>Compiling and uploading the two sketch parts</li><li>Using the Web BLE Interface</li><li>Summary</li></ul><h3>A Brief Overview of Web BLE</h3><p>In addition to a Wi-Fi interface, processors in the ESP32 family are equipped with <strong>Bluetooth Low Energy (BLE)</strong> radio modules. This allows us to establish a wireless interface between our smartphone and the ESP32 that operates independently of any Wi-Fi interface currently in use. The underlying Espressif libraries for BLE have now matured, and numerous examples exist demonstrating how to implement such a configuration interface.</p><p>To provide the user with a graphical user interface, we utilize an Edge- or <strong>Chrome-based browser on an Android smartphone</strong> or tablet, allowing us to control the device without the need to pre-install a specific app. The situation may differ on Apple devices, where a dedicated app — responsible for handling Web BLE control — must be installed once (though, lacking an iOS device, I was unable to test this myself, but found Bluefy, BLE Link and WebBLE in the AppStore).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*K5AK0rFZX6WjZE44eiBsvw.png" /></figure><p>In this tutorial, I will not delve deeply into the underlying technology, but rather use it as a “ready-made” system.</p><h3>Initial Experiences with Web BLE Configuration</h3><p>I first tested the Web BLE interface using a minimal clock setup — that is, I used the transmitted configuration data solely to establish the Wi-Fi connection and calculate the local time — which worked without any issues.</p><p>However, once I had integrated the program code into the existing Nixie clock code, suddenly nothing worked at all. To make a long story short: multiple entries appeared in the debug log files pointing to “<strong>Out of memory</strong>” issues. At that point, I realized that “Low Energy” does not also mean “Low Memory” — but rather that the opposite is true.</p><h3>Cause of the Memory Shortage</h3><p>Since the BLE code had functioned flawlessly in a purely text-based environment, I was able to quickly narrow down the cause of the problem. To display the Nixie Clock, I utilize pre-made images depicting a typical Nixie tube with its filaments. For the 10 possible digits, I use 10 sprites, which I draw every second onto a screen-sized sprite before displaying the entire composite image on the actual display in a single operation.</p><p>While this prevents unpleasant flickering, it comes at the cost of internal processor memory — memory that is also used to manage the Bluetooth stack and cannot be expanded. As soon as this memory runs out, either Bluetooth, the display, Wi-Fi, or indeed all three components cease to function.</p><p>I tried a great many optimizations, but none yielded the desired results. Only a radical overhaul of the programming made it possible to implement the programming concept.</p><h3>Solution for the Out of Memory Problem</h3><p>Fortunately, the Web BLE interface is not required for the ongoing operation of the clock; rather, it is typically used just once — either to set up the clock on the home Wi-Fi network or when connecting it to a different Wi-Fi network. Furthermore, as long as I do not provide the ESP32 with new credentials, it cannot receive or display the current time. The same, of course, applies to the POSIX time zone string.</p><p>For this reason, I am now uploading <strong>two different programs</strong> to the ESP32-S3: first, the actual Nixie Clock sketch, and second, the Web BLE configuration interface. If the clock program fails to establish a connection to a Wi-Fi network — or if the Boot button is pressed — the ESP32 automatically restarts and then runs the configuration program. Once the new credentials have been entered, they are stored in <strong>Non-Volatile Storage (NVS)</strong>; the ESP32 then restarts and resumes running the clock program.</p><p>This division ensures that only Wi-Fi and sprites are utilized in the Clock program, while in the Web BLE program, the TFT display displays only static pages without the use of sprites.</p><h3>How do you switch between the two programs?</h3><p>Switching between the two programs requires just a few lines of code. However, uploading both programs to the ESP32 can be a bit tricky, as the Arduino IDE always overwrites the last active program. Fortunately, there is a rather simple and convenient solution available through the website <a href="https://thelastoutpostworkshop.github.io/ESPConnect/"><strong>ESPConnect</strong></a>, which offers a facility for uploading two programs.</p><p>To avoid unnecessarily prolonging this tutorial, I have described the entire process — from program creation and compilation all the way to uploading — in a separate tutorial that you should definitely read: “<a href="https://medium.com/@androidcrypto/what-is-the-second-ota-partition-on-the-esp32-useful-for-other-than-for-an-online-update-fcb06672e2ec"><strong>What is the second OTA partition on the ESP32 useful for, other than for an online update?</strong></a>”. Additionally, I recommend my tutorial “<a href="https://medium.com/@androidcrypto/easily-deploy-and-update-your-platformio-projects-without-an-installed-ide-6dd30162e162"><strong>Easily deploy and update your PlatformIO projects without an installed IDE</strong></a>,” as I introduce the <a href="https://thelastoutpostworkshop.github.io/ESPConnect/"><strong>ESPConnect</strong></a> web service used therein in much greater depth.</p><h3>Required Hardware for the Nixie-Style Clock Project with Web BLE Configuration Interface</h3><p>Even though the original project was programmed on an <strong>ESP32-S3</strong> with 16 MB of flash memory and a built-in TFT display, you can use any processor from the ESP32 family — with the exception of the ESP32-H2 — provided it has at least 4 MB of memory.</p><p>A connected <strong>TFT display</strong> should have a <strong>width of</strong> at least <strong>320 pixels</strong> and a <strong>height of</strong> at least <strong>170 pixels</strong> in order to fully display all Nixie tube images.</p><h3>Find the Right Partition Scheme</h3><p>As previously described, we utilize the two available app partitions — “OTA_0” and “OTA_1” — for the entire project. Since these are primarily intended for “Over-the-Air” updates of existing firmware, <strong>both partitions must be of equal size</strong>. This means that, even though our two sub-programs differ in size, we must base our allocation on the larger of the two. When we compile our <strong>main clock program</strong>, a memory requirement of <strong>1,216,384 bytes</strong> is reported, whereas our <strong>Web BLE configuration program</strong> requires <strong>647,748 bytes</strong>. One possible scheme would be “<strong>Minimal SPIFFS (1.9 MB App with OTA / 128 KB SPIFFS)</strong>,” which allows for 1.9 MB for the two apps and 128 KB for storage in SPIFFS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TrRzDrxFcorzMwOGXsUR2A.png" /></figure><h3>Compiling and uploading the two sketch parts</h3><p>The standard method for compiling and uploading a program is to press the corresponding button on the Arduino GUI. This is exactly what we will do for the first part of our two sketches (“<em>…ota_0</em>”). We must handle the second part (“…ota_1”) in a completely different manner, as the Arduino always uploads a compiled program to the first program partition, thereby overwriting the existing initial program.</p><p>To avoid this, we compile the program using the Arduino menu option *Sketch &gt; Export Compiled Binary* and then upload this binary file (“<em>…bin</em>”) to the second program partition using ESPConnect; for further details, I refer you to my tutorial titled “<a href="https://medium.com/@androidcrypto/what-is-the-second-ota-partition-on-the-esp32-useful-for-other-than-for-an-online-update-fcb06672e2ec"><strong>What is the second OTA partition on the ESP32 useful for, other than for an online update?</strong></a>”.</p><p>After the ESP32 restarts, the main program (“<em>…ota 0</em>”) launches first; finding no stored Wi-Fi credentials (yet), it then switches to the second program (“<em>…ota_1</em>”). Once you have entered the credentials via the Web BLE interface, the program saves this information and returns to the first program. This program utilizes the stored information to establish a Wi-Fi connection to your router, synchronize its time with an NTP server, calculate the local time, and display it on the Nixie-style clock.</p><h3>Using the Web BLE Interface</h3><p>Once the ESP32-S3 has started the <strong>Web BLE interface</strong>, open this page in your Chrome, Edge, or Apple browser: <a href="https://androidcrypto.github.io/WebBle1/wifi_posix_04.html">https://androidcrypto.github.io/WebBle1/wifi_posix_04.html</a>, enter your Wi-Fi credentials, and select your POSIX string (alternatively, you can copy it directly into the input field).</p><p>After tapping “Connect and Send,” your smartphone attempts to locate available BLE devices — here, tap “ESP32-Config-Portal” and then “Pair.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*4IvOPJCOXvVS-KoWq4VKrg.png" /></figure><p>The data is then transmitted, and the ESP32-S3 restarts. It subsequently establishes a connection to the Wi-Fi router, synchronizes with the NTP server, and the sketch resumes its normal operation.</p><h3>Summary</h3><p>If special circumstances (e.g., memory constraints) compel you to use a second program, utilizing the Over-the-Air configuration — with its two separate memory areas — can offer a potential solution. Its implementation — specifically, switching between the two areas — can be accomplished with just a few lines of code.</p><h3>Source code of the app</h3><p>You find the <a href="https://github.com/AndroidCrypto/ESP32_S3_1_9_inch_ST7789_Display">complete code of the apps</a> in the same GitHub repository as the regular clock, the <a href="https://github.com/AndroidCrypto/TFT_eSPI">modified TFT_eSPI library</a> and the device-display settings file (<a href="https://github.com/AndroidCrypto/ESP32_S3_1_9_inch_ST7789_Display/blob/main/Setup810_S3_1_9_ST7789_170x320.h"><em>Setup810_S3_1_9_ST7789_170x320.h</em></a>) in my GitHub repositories. The necessary modification of the TFT_eSPI library is described in my article “<a href="https://medium.com/@androidcrypto/getting-started-with-an-esp32-c6-supermini-device-connected-to-an-st7789-tft-display-76b0809e292f"><strong>Getting Started with an ESP32-C6 Supermini device connected to an ST7789 TFT display</strong></a>”.</p><p>Happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06fde0070d9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the second OTA partition on the ESP32 useful for, other than for an online update?]]></title>
            <link>https://medium.com/@androidcrypto/what-is-the-second-ota-partition-on-the-esp32-useful-for-other-than-for-an-online-update-fcb06672e2ec?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcb06672e2ec</guid>
            <category><![CDATA[esp32-tutorial]]></category>
            <category><![CDATA[partition]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[over-the-air-update]]></category>
            <category><![CDATA[ota]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 07:27:32 GMT</pubDate>
            <atom:updated>2026-06-03T08:10:30.894Z</atom:updated>
            <content:encoded><![CDATA[<p>For an <strong>online update</strong> on a processor from the ESP32 family, a second application partition is absolutely essential, as this is where the new code is stored during the download; subsequently, the ESP32 boots from this second partition. In this tutorial, I will show you the <strong>purpose of this second partition</strong> and how you can utilize it in your own programs — all you need is a little preparation and a few lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*MRjFnK3y2i1ZGwUXM--iwg.png" /></figure><h3>Topics of this tutorial</h3><ul><li>ESP32 Default Configuration</li><li>Brief Information on the Over-the-Air Update Process</li><li>What else can the second program partition be used for?</li><li>Solution for my Out Of Memory issue</li><li>Simplified Test Environment</li><li>Uploading the binaries</li><li>Troubleshooting</li><li>Using OTA Technology for the Nixie-Style Clock</li><li>Summary</li></ul><h3>ESP32 Default Configuration</h3><p>When you upload a program to the ESP32 processor, you will typically use the “Two Partitions” memory formatting, as this is the default setting. The allocation of the flash memory is controlled by the <strong>partition scheme</strong>, which can be changed within the “<em>Tools</em>” section of the Arduino IDE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OJE0vfMlvtxAOZyTznE1yg.png" /></figure><h3>Brief Information on the Over-the-Air Update Process</h3><p>An <strong>Over-the-Air (OTA) update</strong> on an ESP32 is the process of wirelessly uploading new firmware or code to the device, eliminating the need for a physical USB connection. This is especially useful for devices that are already installed in hard-to-reach places like ceilings or outdoor enclosures.</p><h4>How It Works</h4><ul><li>Dual-Partition System: The ESP32 uses a “safe update” mechanism where the flash memory is divided into at least two application slots (e.g., ota_0 and ota_1).</li><li>Background Download: While your current code is running, the new firmware is downloaded and written to the <em>other</em> (inactive) partition.</li><li>Verification &amp; Switching: Once the download is complete, the ESP32 verifies the new image. If valid, it updates a “data partition” to tell the bootloader to use the new slot on the next restart.</li><li>Rollback Safety: If the new firmware fails to boot or has critical errors, the system can automatically roll back to the previous working version to prevent the device from becoming “bricked”.</li></ul><h3>What else can the second program partition be used for?</h3><p>Let me give you a practical example of why I had to use the second program partition: as part of my tutorial “<a href="https://medium.com/@androidcrypto/how-do-i-find-the-correct-connection-pins-for-an-esp32-s3-development-board-with-an-attached-tft-eb4bbbbac95b"><strong>How do I find the correct connection pins for an ESP32-S3 development board with an attached TFT display (ST7789)?</strong></a>”, I demonstrated — among other things — a program that emulates a Nixie-style clock on the TFT display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8iX--AeFvo9p9TJPNc64XA.png" /></figure><p>This clock connects to the local Wi-Fi network, then synchronizes with a Network Time Protocol (NTP) server and calculates the local time using a POSIX configuration string. As is the case in many other projects, the access credentials and the country-specific POSIX string are hardcoded into the program; consequently, any subsequent changes — such as updating the Wi-Fi credentials — necessitate reprogramming.</p><p>As a small added feature, I thought it would be cool to include a <strong>Bluetooth Low Energy (BLE)</strong> interface to <strong>transfer the Wi-Fi credentials and the POSIX string to the ESP32</strong> using a smartphone. This allows the credentials to be easily changed later on — completely without the need for reprogramming. The transmitted data is permanently stored in <strong>Non-Volatile Storage (NVS)</strong>, so that, in principle, I only need to perform this process once.</p><p>I tested the interface using a simple program that outputs all ESP32 data entirely to the Serial Monitor, and everything worked to my complete satisfaction. I copied the BLE code into a separate file and then, with just a few clicks, integrated it into the main code of the clock program.</p><p>Then came the <strong>great disillusionment: nothing worked anymore</strong>. There was no display on the screen, and the BLE connection was no longer active either. How is it possible that two separate programs function flawlessly beforehand, yet stop working after being merged? After an extended period of troubleshooting, I discovered the cause — and it is an “<strong>Out of memory error</strong>.”</p><p>Although my ESP32-S3 processor has 16 MB of flash memory available, there are nevertheless additional internal memory regions that do not scale up alongside a larger main memory (e.g., “<strong>DRAM</strong>” and “<strong>IRAM</strong>”). If an overflow occurs in these areas, a program may behave erratically — ranging from strange behavior to an uncontrolled crash.</p><p>It turned out that the “lightweight” BLE library is, in reality, a true memory hog — which, when used simultaneously with the TFT_eSPI graphics library involving numerous sprites, leads to the described memory bottleneck.</p><p>All attempts to avoid this bottleneck — for instance, by cleverly rearranging initializations or by conditionally deleting and recreating objects — failed; I found no way, given the architecture of my program, to utilize all three modules — the graphics library, Wi-Fi, and BLE — simultaneously.</p><h3>Solution for my Out Of Memory issue</h3><p>In the end, I found a small yet fascinating solution that fulfilled all my requirements: by utilizing the two completely separate program partitions (“OTA_0” and “OTA_1”), I can use both program components — specifically, the display of the current time and the configuration of the Wi-Fi interface — with my ESP32-S3.</p><p>The implementation is carried out using two independent sketches within the Arduino IDE: the clock component in OTA_0, and the BLE configuration component in OTA_1. The sole link connecting these two parts is their shared use of an additional Non-Volatile Storage partition, into which the OTA_1 program writes the new data, and from which OTA_0 reads these credentials to establish a connection with the Wi-Fi router and the NTP server.</p><h3>Simplified Test Environment</h3><p>To ensure we don’t lose sight of the essentials, I’ll start with a greatly simplified program — one that merely demonstrates how easily you can switch back and forth between two independent program sections. These two programs contain absolutely no code related to clocks or Bluetooth; however, they were immensely helpful to me — both for studying the fundamental workflow and for overcoming the minor hurdle of figuring out how to upload two separate programs to the ESP32.</p><p>It is crucial that <strong>both OTA programs utilize the same partition scheme</strong>. Furthermore, please note that <strong>the two programs are uploaded to the ESP32 processor in different ways</strong>:</p><ul><li><strong>OTA_0</strong>: is compiled and uploaded to the ESP32 via the <strong>Arduino IDE</strong>.</li><li><strong>OTA_1</strong>: is merely compiled within the Arduino IDE to generate a binary file, which is subsequently uploaded to the second partition using an <strong>external service (“ESPConnect”)</strong>.</li></ul><h4>Partition Scheme</h4><p>Since our program is very small, we are using, for example, the default settings of the Arduino IDE (please note that default settings may vary depending on the specific ESP32 development board selected): “<strong><em>Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)</em></strong>”.</p><h3>Uploading the binaries</h3><h4>Uploading the OTA_0 Program</h4><p>Uploading is performed just like with any other program, and the program is stored in the OTA_0 partition.</p><h4>Compiling the OTA_1 Program</h4><p>I had already mentioned that this program requires different handling for the upload. This is because Arduino always uploads a program to the OTA_0 partition.</p><p>In the Arduino IDE, please go to the “<strong>Sketch</strong>” menu and select “<strong>Export Compiled Binary</strong>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*tVYW74k24n275eLtAdgcdQ.png" /></figure><p>The sketch is now being compiled, and the “Output” window displays only this information:</p><pre>Sketch uses 325,712 bytes (9%) of program storage space. <br>Maximum is 3,342,336 bytes.<br>Global variables use 22,096 bytes (6%) of dynamic memory, <br>leaving 305,584 bytes for local variables. <br>Maximum is 327,680 bytes.</pre><p>Now, let’s use Windows Explorer or macOS Finder to look inside the Sketch folder — there, you will find a “build” subfolder, and within that, the folder “esp32.esp32.esp32s3” (this folder name may differ for you if you are using a different processor). Inside, there are several files, which may initially appear completely identical. Only one of these files is important to us: “<em>Esp32_S3_Two_Partitions_Sketch_OTA_1.ino.bin</em>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*B9_eZ-XVY1FTocQFMZI3bg.png" /></figure><h4>Using ESPConnect for uploading the sketch</h4><p>In my tutorial “<a href="https://medium.com/@androidcrypto/easily-deploy-and-update-your-platformio-projects-without-an-installed-ide-6dd30162e162"><strong>Easily deploy and update your PlatformIO projects without an installed IDE,</strong></a>” I have already described <a href="https://thelastoutpostworkshop.github.io/ESPConnect/"><strong>ESPConnect</strong></a>; therefore, you should read that article alongside this one.</p><p>After you have connected to the ESP32, select “<strong>Flash Tools</strong>” on the left side, and on the right side, scroll down slightly to “<strong>Flash Firmware</strong>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OqcdLpvS6uEya_fD0MyX1A.png" /></figure><p>Click on “<strong>Firmware binary (.bin)</strong>” and then select the file “<em>Esp32_S3_Two_Partitions_Sketch_OTA_1.ino.bin</em>” from the subdirectory mentioned above. Now comes the most important step: open the dropdown menu under “<strong><em>Recommended offsets</em></strong>” and select “<strong>app1</strong>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*F0Le1oV2Q-C0gq_sxlPdFQ.png" /></figure><p>You will likely need to scroll down a bit; if “<strong>app1</strong>” does not appear there, you selected a partition scheme during the upload of the “<strong>OTA_0</strong>” program that is actually designed for only a single app (<strong>app0</strong>). The “<strong>Flash Offset</strong>” field is now also populated; the displayed value may vary depending on the specific memory configuration or data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*5PxtmyHh438O6Sog0Pt1-g.png" /></figure><p>Finally, click “<strong>Flash Firmware</strong>,” and a final warning window will appear, as the existing content will subsequently be overwritten:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*YDOBrzyZdEV7I4eO2J7aqA.png" /></figure><p>Two windows inform us about the progress and completion of the upload process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*BKiXk3UicZP7aagXC2KVTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*P9qcyioUchnQjPhyFk7Q8w.png" /></figure><p>At this point, we have finished the upload, and the “OTA_0” program is ready for use. In the Serial Monitor, we see the following messages:</p><pre>--- MODE: REGULAR (ota_0) ---<br>Please press the BOOT button to change to the EXTENDED mode.</pre><p>Now, when we press the BOOT button, this happens (if nothing happens, please check the GPIO pin for the BOOT button on your board):</p><pre>Change to ota_1 (Extended mode)...<br><br>&lt;Restart of the ESP32-S3&gt;<br><br>--- MODE: EXTENDED (ota_1) ---<br>Please press the BOOT button to change back to the REGULAR mode.</pre><p>Upon clicking the BOOT button again, the ESP32-S3 switches back to Regular mode:</p><pre>Change back to ota_0 (REGULAR mode)...<br>&lt;Restart of the ESP32-S3&gt;<br>--- MODE: REGULAR (ota_0) ---<br>Please press the BOOT button to change to the EXTENDED mode.</pre><p>The program code for switching partitions is comparatively short:</p><pre>in header:<br>#include &quot;esp_ota_ops.h&quot;<br><br>whereever you want to switch to OTA_1:<br>const esp_partition_t* target = esp_partition_find_first(<br>  ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL);<br>if (target) {<br>  esp_ota_set_boot_partition(target);<br>  esp_restart();<br>} else {<br>  Serial.println(&quot;Error: ota_1 partition not found!&quot;);<br>}<br><br>For switching back to OTA_0 use:<br>const esp_partition_t* target = esp_partition_find_first(<br>  ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);</pre><p>BTW: Of course, you can also upload subsequent <strong>updates for OTA_0</strong> using the steps mentioned — just make sure to select the “<strong>app0</strong>” offset in ESPConnect!</p><h3>Troubleshooting</h3><p>Based on my experiments, I have identified three primary reasons for <strong>malfunctions</strong>:<br>1. Please take meticulous care to ensure that the settings within the “Tools” menu are *exactly* identical for both programs. Even the slightest discrepancy can result in entries being shifted, causing the uploaded code to be written to the wrong memory location. Particular caution is advised when loading a sketch created “some time ago.” Therefore, it would not hurt to embed the selected settings directly into the sketch file during the initial programming phase. For instance, it is very easy — and happens quite frequently — to inadvertently use an incorrect memory size and/or partition scheme, rendering the entire project unusable.</p><p>2. When uploading to ESPConnect, the browser remembers the last-used file location. If, for example, you are working with different versions stored in separate folders, it is very easy to accidentally upload the binary file from the previous version.</p><p>3. The order of uploads can determine success or failure: particularly for the first upload, it is crucial to upload OTA_0 via the Arduino IDE first, and only then upload OTA_1 via ESPConnect.</p><h3>Using OTA Technology for the Nixie-Style Clock</h3><p>In my article “<a href="https://medium.com/@androidcrypto/upgrade-your-esp32-s3-nixie-style-clock-with-a-web-ble-interface-06fde0070d9c"><strong>Upgrade your ESP32-S3 Nixie-style clock with a Web BLE interface</strong></a>,” I show you how to integrate this technology into a project. In it, I utilize the two OTA partitions — one for the main program and the other for the WebBLE configuration program.</p><h3>Summary</h3><p>As you have seen, utilizing the two OTA partitions is very straightforward; the only discontinuity occurs during the upload process, as you have to manually initiate the upload for the second partition. This step might potentially be eliminated when <strong>switching from the Arduino IDE to PlatformIO</strong>, though I have not yet tested this myself.</p><h3>Source code of the app</h3><p>You find the <a href="https://github.com/AndroidCrypto/ESP32_Over_The_Air_Partitions_Alternative_Usage">complete code of the apps</a> in my GitHub repository.</p><p>Happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcb06672e2ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NFC meets LoRa — using Long Range Communication for Access Control Systems with ESP32]]></title>
            <link>https://medium.com/@androidcrypto/nfc-meets-lora-using-long-range-communication-for-access-control-systems-with-esp32-138ba35588ae?source=rss-8d474649a487------2</link>
            <guid isPermaLink="false">https://medium.com/p/138ba35588ae</guid>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[nfc]]></category>
            <category><![CDATA[proof-of-concept]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[esp32-programming]]></category>
            <dc:creator><![CDATA[AndroidCrypto]]></dc:creator>
            <pubDate>Mon, 25 May 2026 08:54:17 GMT</pubDate>
            <atom:updated>2026-05-25T08:54:17.608Z</atom:updated>
            <content:encoded><![CDATA[<p>This is not a tutorial, but rather a <strong>proof-of-concept article</strong> in which I will demonstrate how to combine two technologies. The first is <strong>Near Field Communication (NFC) </strong>— the technology used, for instance, when a hotel key card is held against a door reader to verify credentials and grant access to a room. The second is<strong> Long Range Communication (LoRa)</strong>, which is ideally suited for transmitting small amounts of data over significant distances (ranging from a few meters up to several kilometers). Both technologies share a common characteristic: they handle small data packets efficiently and have been optimized for energy efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-4gWgXxfCPoQlq6COxyCnA.png" /><figcaption>NFC Card Reader unit with ESP32 Development Board and LoRa module</figcaption></figure><h3>Why does combining these two technologies make sense?</h3><p>Many traditional access control systems operate autonomously; that is, their readers do not require direct access to a central “controller.” However, to update a reader with current information — such as the correct time or a list of revoked access cards — staff members must manually visit each individual reader to update it. Furthermore, if the access card is to serve a dual purpose — for example, as a payment method (e.g., at a beverage dispenser or equipment rental kiosk) — it becomes highly advantageous to transmit the card’s current credit balance and inventory levels to a central computer.</p><p>Within a single building, establishing such communication is usually quite simple using the existing Wi-Fi network. However, the task becomes significantly more challenging if the reader is located outdoors — for instance, on a golf course — several hundred meters away from the main clubhouse. This is where LoRa communication comes into play: it provides a wireless link that can be utilized license-free and implemented using small, low-cost devices. For example, if I use an ESP32 microcontroller as the foundation for the card reader, adding a LoRa interface is a quick and straightforward process.</p><h3>What Hardware Do I Need?</h3><p>For my test setup, on the card reader side, I am using an <strong>ESP32 development board with an integrated TFT display</strong>, an <strong>NFC card reader (Type PN532)</strong> with an SPI interface, and a <strong>LoRa transceiver</strong> equipped with a UART (serial) interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*jVhgVTlmXY2k4Ll9O0k5GA.png" /><figcaption>NFC Card Reader PN532</figcaption></figure><p>For the controller side, I am using an <strong>ESP32-S3 development board</strong> that is equipped with both a <strong>TFT display</strong> and a <strong>LoRa transceiver chip</strong> (Type: SX126X) (Heltec Vision Master T190).</p><p>I programmed this example to demonstrate the use of the popular <strong>Mifare Classic NFC cards</strong>, which are utilized as access control cards in nearly all hotels. To simulate the two verification states — “Access Granted” and “Access Denied” — I am using two different cards.</p><p>For an overview of the LoRa module with a UART interface, I recommend my tutorial “<a href="https://medium.com/@androidcrypto/simple-lora-transmissions-over-several-kilometers-using-uart-serial-lora-modules-6c5abbf464f2"><strong>Simple LoRa transmissions over several kilometers using UART/Serial LoRa modules</strong></a>,” which explains this module and its usage in detail. For guidance on using off-the-shelf ESP32 development boards with LoRa capabilities, I recommend my article series “<a href="https://medium.com/@androidcrypto/working-with-long-range-communication-lora-lorawan-and-meshtastic-on-an-esp32-platform-3bdd0ec2c956"><strong>Working with Long Range Communication (“LoRa®”, “LoRaWAN®” and “Meshtastic®”) on an ESP32 platform</strong></a>.”</p><p>The reason I connected the card reader to a UART-based LoRa module (instead of utilizing the standard SPI interface) is simple: the wiring is significantly easier to manage — especially since the ESP32 is already utilizing both SPI interfaces (for the TFT display and the NFC reader), meaning I would otherwise have had to implement interface sharing (which is technically possible, but would have entailed considerably more effort).</p><h3>What software do I use?</h3><p>Programming is performed using the <strong>Arduino IDE version 2.3.8</strong> and the <strong>esp32-boards version 3.3.8</strong> on Windows 10. I incorporate the following additional libraries: the <a href="https://github.com/Bodmer/TFT_eSPI"><strong>TFT_eSPI</strong></a> graphics library by <strong>Bodmer</strong> (for both devices), and the <a href="https://github.com/StuartsProjects/SX12XX-LoRa"><strong>ST12XX-LoRa</strong></a> library by <strong>Stuart Projects</strong> for LoRa communication on the controller side. For reading NFC cards, I use the <a href="https://github.com/adafruit/Adafruit-PN532"><strong>Adafruit PN532</strong></a> library.</p><h3>Basic Program Flow</h3><ol><li>After both boards have started up, the controller side first establishes a connection to the Wi-Fi router, contacts the Network Time Protocol (NTP) server, and synchronizes its system time (which is Coordinated Universal Time, UTC).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*moK3jnTR30aNjr7k87Vl3A.png" /><figcaption>ESP32 Card Reader Unit waiting for Time Synchronization</figcaption></figure><p>2. Next, the program calculates the local time and displays it on the idle screen.</p><p>3. From this point on, the controller sends the current local time timestamp every minute as a LoRa broadcast — that is, to every LoRa device within its range.</p><p>4. The controller enters a waiting phase to await access permission requests.</p><p>5. The card reader side receives the timestamp via LoRa and synchronizes its system time with the controller’s local time (thus, unlike on the controller, the system time here corresponds to the actual local time).</p><p>6. The card reader also enters a waiting phase, waiting for an access card to be placed on the reader device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*BxUBGRU0BF06_R_ff3EXCA.png" /><figcaption>ESP32 Card Reader Unit waiting for tapping a Mifare Classic Card to the reader</figcaption></figure><p>At this point, both devices are in an inactive waiting phase, during which an “Idle” screen displaying the current local time is shown.</p><p>7. An access card is held up to the card reader; it is read, and its details are displayed on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*YnmvMjrMjJrwYHU0CYwCnw.png" /></figure><p>8. The read access data is transmitted to the controller via LoRa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*rOaBKyVq5-jqRCH7I90Kyw.png" /></figure><p>9. The controller receives the access data and displays it on its screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*BF-3T83Ug3g2llPOsqW2gw.png" /></figure><p>10. The controller verifies whether the card currently holds valid access authorization. In this specific program, authorization is granted solely if the room number is “12.” If access authorization is confirmed, the text “GRANTED” appears beneath the access data; otherwise, “DENIED” is displayed.</p><p>11. The controller transmits the verification result via LoRa (0 = No authorization; 1 = Access granted), along with a transmission ID, to enable — if necessary — the correlation of the result with the original verification request (this ID is not currently being processed).</p><p>12. The card reader receives the response from the controller and displays either “Access Granted” or “Access Denied” on its screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*473z5E5JJK--UeVb_ngg7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*dQGzX4rMKzyIZqmUjcxcUg.png" /></figure><p>At this point, both devices return to an inactive waiting phase, during which an “Idle” screen displaying the current local time is shown.</p><h3>Project Goal</h3><p>With this test setup, I demonstrate that we can seamlessly combine both technologies — NFC and LoRa — and effortlessly bridge significant distances between a card reader and its controller using LoRa.</p><h3>How does the NFC reading component work?</h3><p>After initializing the UART interface, the display, and the NFC reader, the program waits for the receipt of a LoRa packet containing a local timestamp, which supplies the ESP32 with current time data. From this point on, the reading unit waits for a <strong>Mifare Classic NFC card</strong> to be placed on the reader. With these cards, each block consists of three data sectors and one sector dedicated to access control information. In terms of programming, sectors 4, 5, 6, 8, 9, and 10 are utilized for our data. For our “PoC” (Proof of Concept), we do not employ any access protection; consequently, these sectors must be freely readable and writable.</p><p>To populate our cards with test data, type “<strong>WRITE</strong>” into the Serial Monitor. This initiates a guided dialogue in which you sequentially enter the name (maximum 20 characters), the room number (maximum 2 characters), the card’s validity period (from–to; exactly 8 characters in the format DD.MM.YY), and a credit balance (maximum 8 characters, e.g., 123.45). If you prefer to use the two pre-configured test datasets, use the commands “WRITE1” or “WRITE2,” respectively.</p><p>To determine whether a card is “Accepted” or “Rejected” later in the process, I have implemented a very simple verification mechanism within the controller:<strong> if the room number is “12,” the access request is granted</strong>; for any other entry in the “Room” field, access is denied.</p><p>Once a card is placed on the reader, its contents are read, displayed in a structured format on the screen, and then transmitted via LoRa. After a brief waiting period, the standby screen is displayed once again. Since only small amounts of data are being transmitted, we receive a very rapid response from the controller — essentially a simple “Yes” or “No.” I also include the sequential request number in the transmission to facilitate correlation, although I do not currently process or evaluate this specific piece of information. The result is displayed on the screen — either with a green icon (access granted) or a red icon (access denied); after a brief waiting period, the idle screen reappears.</p><h3>How does the controller section work?</h3><p>After initializing the display and the LoRa chip, the board establishes a connection to the Wi-Fi router and synchronizes its system time with a <strong>Network Time Protocol (NTP)</strong> server. Thanks to the <strong>POSIX configuration string</strong>, the ESP32 can now calculate the local time and display it on its standby screen. Every minute, the controller transmits a timestamp containing the current local time via LoRa. In a practical application, this function would typically be executed — for instance — upon a request from a new card reader, or once nightly.</p><p>From this point on, the board awaits the receipt of a LoRa packet containing access credentials; following a brief validation check (verifying both the packet length and the “magic bytes” at the beginning and end), the data is read and displayed in a structured format on the screen. Access authorization is verified using a very simple logic: if the room number is “12,” access is granted; for any other value, it is denied. The result of this verification is displayed on the screen and transmitted back to the card reader unit via a LoRa packet; subsequently, the device returns to its standby state.</p><blockquote>Note regarding both programs: Since I was too lazy to rewrite both programs from scratch, I slightly modified existing programs; as a result, they contain — in part — additional (unused) functions.</blockquote><h3>Summary</h3><p>The interplay between the two technologies — NFC and LoRa — is easy to implement using an ESP32; it enables, for instance, the operation of access control systems across a wide spatial area while still maintaining “network” access from the controller to every individual reader.</p><h3>Source code of the app</h3><p>You find the <a href="https://github.com/AndroidCrypto/ESP32_NFC_meets_LoRa">complete code of the apps</a>, the <a href="https://github.com/AndroidCrypto/TFT_eSPI">modified TFT_eSPI library</a> and the device-display settings file in my GitHub repositories.</p><p>Happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=138ba35588ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>