<?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 Aditya Bangde on Medium]]></title>
        <description><![CDATA[Stories by Aditya Bangde on Medium]]></description>
        <link>https://medium.com/@adityabangde?source=rss-2be6af53912d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jXgAu1iiXmRDZ6X9</url>
            <title>Stories by Aditya Bangde on Medium</title>
            <link>https://medium.com/@adityabangde?source=rss-2be6af53912d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:17:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityabangde/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[Deploying a PPO-Trained Bipedal Walker on an STM32: From Reinforcement Learning to Real-Time…]]></title>
            <link>https://medium.com/@adityabangde/deploying-a-ppo-trained-bipedal-walker-on-an-stm32-from-reinforcement-learning-to-real-time-470ab3c54e92?source=rss-2be6af53912d------2</link>
            <guid isPermaLink="false">https://medium.com/p/470ab3c54e92</guid>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[edge-computing]]></category>
            <dc:creator><![CDATA[Aditya Bangde]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 03:36:52 GMT</pubDate>
            <atom:updated>2025-12-07T03:36:52.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a PPO-Trained Bipedal Walker on an STM32: From Reinforcement Learning to Real-Time Control</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSWK9i9U-TEI7JFhI-YQiw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@vishnumaiea?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Vishnu Mohanan</a> on <a href="https://unsplash.com/photos/green-and-black-computer-motherboard-yQpAaMsQzYE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Story</h3><p>I’ve been working with the open-source leg OSL prosthesis from the University of Michigan, and part of my job was customizing ACT models for control. These models are powerful, but they come with a catch they need serious hardware. GPU, TPU, or at least something with enough horsepower to run a model at a decent speed. That’s fine for research, but not for a device that someone actually wears.</p><p>A prosthetic leg, a robot arm, or even a small mobile robot is basically an edge device. It runs on batteries. It moves around. You can’t plug a long power cable into it and walk around the room that would look ridiculous. So the question is obvious:<br> <strong>How do we run intelligent control models on hardware that’s tiny, low-power, and battery-friendly?</strong></p><p>At first, I thought about using a Raspberry Pi maybe a Pi 5, 4, or even a Zero. But then another question came up:<br> <strong>How low can we actually go? Could we push this all the way down to a microcontroller?<br></strong>I searched around for examples. I found some articles about running neural networks on microcontrollers, but nothing that involved a NN that can run a robot, and definitely nothing running <strong>PPO</strong> on something as small as a microcontroller. So instead of waiting for someone else to try it, I decided to test it myself.</p><p>And that’s how this project started and how you ended up reading this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*tM_7RfolyQOHjSZ6z7aEFw.gif" /></figure><h3>Quick Start</h3><p>Before we jump into the details, here’s a quick overview of what this project actually does. I’ll also try to answer the same questions that came to my mind while building it, so you understand not only <em>how</em> it works but <em>why</em> each step exists.</p><p>If you want to follow along, start by cloning the repo:</p><pre>git clone https://github.com/yourusername/BipedalWalker-PPO-STM32.git<br>cd BipedalWalker-PPO-STM32</pre><p>You can create a virtual environment (recommended but not mandatory):</p><p>Then install all dependencies:</p><pre>pip install -r requirements.txt</pre><p>Whether you use a venv or run everything directly on your system Python doesn’t matter whatever feels best for you.<br> Inside the repo, I’ve added all the required files, and you can refer to them or modify them however you like.</p><h3>Project Flow (High-Level Steps)</h3><h4>1. Train the Bipedal Walker using train_ppo.py</h4><p>Run the training script and make sure to adjust file paths if needed.<br> The script saves the model inside the save/ folder.</p><p>I added a simple milestone system: every 200 steps, the script saves a new checkpoint.<br> I stopped my run after 200 steps (yes, I got lazy), which is why the GIF you see of the walker might look a bit funny.</p><h4>2. Test the Model using test_ppo.py</h4><p>This script loads your trained PPO policy and runs it in the Bipedal Walker environment so you can see how well it performs before converting anything.</p><h4>3. Convert the Model from .h5 to TFLite using convert_to_tflite.py</h4><p>The .h5 file contains everything needed for training, optimizer states, gradients, metadata, checkpoints, and so on. But for inference on a microcontroller, we only need the final network architecture and its weights.</p><p>TFLite removes all the training-related data and keeps only what’s necessary to run the model. The result is a much smaller, lightweight file that’s ideal for low-power edge devices.</p><h4>4. Convert the TFLite model into model.h</h4><p>After getting the .tflite file, we convert it into a .h file (a C/C++ header).<br><strong>Why do this?<br></strong>Because the STM32 firmware expects the model to be included as a raw byte array. When you open the .h file, you’ll see it’s literally just a long list of numbers these are the binary contents of your TFLite model.</p><p>This way, we don’t need to write extra C++ code to interpret or parse anything. TensorFlow Lite Micro can directly read this array and run inference.</p><h3>STM32 Deployment: Putting the Brain on the Board</h3><h4>Setting Up the STM32 Project in STM32CubeMX and STM32CubeIDE</h4><p>On the STM32 side, we start exactly like any normal firmware project:<br> create a new project in <strong>STM32CubeMX</strong>, pick your board, and set up the clocks and UART as usual.</p><p><strong>For this project I used:</strong><br><strong>Board:</strong> Nucleo-H743ZI2<br><strong>MCU:</strong> STM32H743ZI2<br><strong>Flash:</strong> 2 MB (the whole firmware + model uses ~150 KB)<br><strong>RAM:</strong> 512 KB (the model + TFLite Micro use ~45 KB)<br><strong>Clock:</strong> 480 MHz</p><p>This is definitely not the smallest STM32 in the world, but it’s still very much a microcontroller, and it shows that a small neural network can comfortably fit in this class of device.<br>Once the clocks and UART are configured for your board, we can prepare the project for TensorFlow Lite Micro.</p><h4>Converting the Project to C++</h4><p>TensorFlow Lite Micro is written in <strong>C++</strong>, but CubeMX generates project code in C.<br> To make both work together, we need the toolchain to compile the project as C++ while still supporting the existing C HAL files.</p><p><strong>STM32CubeIDE makes this easy:</strong><br>1. Right–click your project’s .ioc file.<br>2. Select <strong>“Convert to C++”</strong>. (You can refer to the image below.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0qaNCzwwPJA-cT_sYw0fA.png" /></figure><p>This switches the build system to use the C++ compiler (g++) so the project can include and compile TFLite Micro’s C++ sources, while keeping all CubeMX generated .c files valid.</p><h4>Keeping main.c and Adding main2.cpp</h4><p>CubeMX regenerates main.c whenever you update peripherals. If you rename it to main.cpp or put TFLite code inside it, you risk losing everything on the next code generation.</p><p><strong>The safer pattern is:</strong><br>1. keep main.c untouched,<br>2. add your own C++ module for TensorFlow Lite Micro.<br><strong>Create:</strong><br>1.Core/Src/main2.cpp (your C++ implementation)<br>2.Core/Inc/main2.h (header exposed to C code)</p><p>main.c will call simple wrapper functions from main2.h, while all TensorFlow Lite Micro logic stays isolated inside main2.cpp.</p><h4><strong>Bridging C and C++ with </strong><strong>extern &quot;C&quot;</strong></h4><p>Because C++ changes symbol names (name mangling), C code can’t directly call C++ functions.<br> Using extern &quot;C&quot; tells the compiler to use C-style naming so both sides can link cleanly.</p><pre>//main2.h<br><br>#ifndef MY_MODULE_H_<br>#define MY_MODULE_H_<br><br>#ifdef __cplusplus<br>extern &quot;C&quot; {<br>#endif<br><br>void MyModule_Init(void);<br>void MyModule_Process(int value);<br>int MyModule_GetResult(void);<br><br>#ifdef __cplusplus<br>}<br>#endif<br><br><br>#endif</pre><p>This header is seen by main.c (which is C code), so the function declarations must have C-style linkage. That’s why we wrap them in extern &quot;C&quot; when compiled under C++.</p><pre>//main2.cpp<br><br>extern &quot;C&quot; {<br>#include &quot;main.h&quot;   // HAL headers as C<br>}<br><br>#include &quot;main2.h&quot;<br><br>extern &quot;C&quot; void MyModule_Init(void) {<br>    // TFLite Micro initialization here<br>}<br><br>extern &quot;C&quot; void MyModule_Process(int value) {<br>    // Run inference or handle data<br>}<br><br>extern &quot;C&quot; int MyModule_GetResult(void) {<br>    return 42;<br>}</pre><p>Here, main2.cpp can use full C++ features, include TensorFlow Lite Micro headers, create interpreters, tensors, etc.<br> The functions marked extern &quot;C&quot; are the ones we expose back to the C world.</p><pre>//main.c<br><br>#include &quot;main2.h&quot;<br><br>int main(void)<br>{<br>  HAL_Init();<br>  SystemClock_Config();<br>  MX_USART3_UART_Init();<br><br>  MyModule_Init();<br><br>  while (1)<br>  {<br>    MyModule_Process(100);<br>    int result = MyModule_GetResult();<br>  }<br>}</pre><p>This keeps main.c nice and clean. It does what it’s good at: hardware setup, HAL initialization, and calling into our module.<br>All the more complex stuff (neural network, TFLite buffers, UART protocol, etc.) lives in modern C++ code in main2.cpp.</p><p><strong>Why This Structure Works<br></strong>1.<strong> </strong>CubeMX can regenerate code safely without touching your C++ files.<br>2. TFLite Micro stays fully in C++, where it belongs.<br>3. HAL and peripheral setups remain in simple C, which CubeMX manages well.<br>4. extern &quot;C&quot; creates a clean interface between the two worlds.</p><p>This setup keeps the firmware stable, modular, and easy to extend as you integrate more neural network features.</p><h4>Uff, that was exhausting if you’ve made it this far, take a break! Spoiler alert: you only did 10% of the work… just kidding, we’re almost done.</h4><h3>Adding TensorFlow Lite Micro to the STM32 Project</h3><p>We’ll create a self-contained tflm_tree folder that holds all the TensorFlow Lite Micro source files our STM32 project needs. You could manually collect every .cc and .h file from the TFLM repo, but that’s painful and time-consuming. The commands below automate the whole process and generate the folder for you.</p><pre># From your firmware / STM32 project directory<br>git clone https://github.com/tensorflow/tflite-micro.git --depth 1<br>cd tflite-micro<br><br># Build for Cortex-M (here using a generic Cortex-M7 target)<br>make -f tensorflow/lite/micro/tools/make/Makefile \<br>  TARGET=cortex_m_generic \<br>  TARGET_ARCH=cortex-m7 \<br>  microlite<br><br># Generate a standalone library tree for the STM32 project<br>python3 tensorflow/lite/micro/tools/project_generation/create_tflm_tree.py \<br>  ../tflm_tree</pre><p>Once the tflm_tree folder is created, simply drop it into your STM32 project directory so the compiler can see all required library files. (You can refer to the image below.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAkreYNbFeJPKQg64L56yg.png" /></figure><p><strong>Small gotcha:</strong><br> Sometimes this process misses a .h or .cc file. If STM32CubeIDE throws “file not found” during build, just grab the missing file from the TFLite Micro repo <a href="https://github.com/tensorflow/tflite-micro">https://github.com/tensorflow/tflite-micro</a> and drop it into the appropriate place inside tflm_tree/.</p><h4>Adding TFLite Micro Include Paths in STM32CubeIDE</h4><p>We need to tell the compiler <strong>where the TensorFlow Lite Micro headers live</strong>, otherwise the project won’t build. Adding these paths ensures the compiler can locate the .h files during compilation and that the linker can correctly resolve references to the corresponding .cc source files inside tflm_tree.</p><p><strong>To add the include paths in STM32CubeIDE:<br></strong>Right–click your project → Properties → C/C++ Build → Settings → MCU G++ Compiler → Include paths (You can refer to the image below.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhwLVqf_5LpR9tMKaUMKJg.png" /></figure><pre>../tflm_tree<br>../tflm_tree/tensorflow<br>../tflm_tree/tensorflow/lite<br>../tflm_tree/tensorflow/lite/micro<br>../tflm_tree/tensorflow/lite/micro/kernels<br>../tflm_tree/third_party/flatbuffers/include<br>../tflm_tree/third_party/gemmlowp<br>../tflm_tree/third_party/kissfft<br>../tflm_tree/third_party/ruy</pre><p>Once these paths are in place, main2.cpp can #include TensorFlow Lite Micro headers without errors, and the build system can properly compile and link all required TFLite Micro components.</p><h4>Build and Flash</h4><p>Time for the drum roll… <br> Hit Build in STM32CubeIDE, and when everything turns green, go ahead and flash it to the board using Debug or Run.</p><p>This is the moment where all that code finally comes alive on real hardware. Now, with your microcontroller connected, run the Python script python test_stm32_serial.py</p><p>Sit back and watch your robot start doing parkour, powered by a neural network running on a tiny STM32.</p><h4><strong>Watch Out for These Common Gotchas</strong></h4><p>No module named ‘Box2D’</p><pre>pip install Box2D</pre><p><strong>Serial port not found<br></strong>Windows → try COM3, COM4, etc.<br>Linux → usually /dev/ttyACM*</p><p><strong>STM32 build errors</strong><br> Double-check that all required TFLite Micro include paths are added to the project.<br><strong>Still running into issues? I’ve got your back drop the error in the comments and we’ll figure it out together.</strong></p><h3>Final Notes</h3><p>Thanks for reading! This project brings together tools from <a href="https://gymnasium.farama.org/"><strong>OpenAI Gymnasium</strong></a>, <a href="https://www.tensorflow.org/lite/microcontrollers"><strong>TensorFlow Lite Micro</strong></a>, and <a href="https://www.st.com/"><strong>STMicroelectronics</strong></a> huge credit to these ecosystems for enabling real innovation at the edge. <br>If you’re working in embedded AI, robotics, prosthetics, microcontrollers, FPGA/ASIC design, or edge computing, feel free to connect with me on <a href="https://www.linkedin.com/in/aditya-bangde-372447178/"><strong>LinkedIn</strong></a> or follow me on <a href="https://medium.com/@adityabangde"><strong>Medium</strong></a>. <br>More hardware-focused content is on the way, including projects in MCUs, FPGA, VLSI, and a fun upcoming article where I break down <strong>quantum computing</strong> in the simplest possible way. Stay tuned and if this repo helped you in any way, don’t forget to ⭐ it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=470ab3c54e92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flashing Firmware to an ESP32 Using Another ESP32]]></title>
            <link>https://medium.com/@adityabangde/flashing-firmware-to-an-esp32-using-another-esp32-d4798ddce70b?source=rss-2be6af53912d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4798ddce70b</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <dc:creator><![CDATA[Aditya Bangde]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 08:48:57 GMT</pubDate>
            <atom:updated>2024-12-31T08:48:57.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VC5-6U_P9WtY7AQ2yGwUkQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@f12r">Fahim Muntashir</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-piece-of-electronics-on-a-table-M02I8Ab_TT4">Unsplash</a></figcaption></figure><p>I was working on a project that relied on OTA (Over-the-Air) updates to remotely manage an ESP32. Initially, everything seemed fine — I even tested the code thoroughly before uploading it. However, one wrong OTA update caused the remote ESP32 to get stuck in a reset loop. This highlighted a critical issue: no matter how much you test beforehand, there are edge cases that only real-world, physical testing can uncover.</p><p>Additionally, OTA on ESP32 has inherent limitations. It creates two partitions: one for the application firmware and another for the OTA firmware, leaving little room for larger firmware updates. If your firmware size exceeds the partition capacity, the update simply fails. These challenges forced me to think of an alternative.</p><p>The solution? Connecting one ESP32 to another. While it doubles the hardware cost, it provides significant advantages. One ESP32 serves as the OTA device, downloading and flashing firmware to the other. This approach eliminates the need for large OTA partitions and ensures that hardware-specific application code runs reliably. Plus, it supports dynamic functionality without the need for overly complex and adaptable code. It’s a win-win for application-specific and dynamic setups alike!</p><h3>What the Code Does</h3><p>I’ll cover the details in a separate article, but for now, here’s a simplified explanation of how the code works. The code enables programming one ESP32 using another by establishing direct communication with the target ESP32’s bootloader. Here’s a step-by-step overview of the process</p><ol><li><strong>Entering Bootloader Mode:</strong> The target ESP32 is prepared for flashing by pulling the <strong>BOOT_PIN</strong> LOW and toggling the <strong>EN_PIN</strong> to reset the device. This places the ESP32 into bootloader mode, ready to accept commands from the master ESP32.</li><li><strong>Synchronizing with the Bootloader:</strong> The master ESP32 sends a <strong>SYNC command</strong> to establish communication with the target. This acts as a handshake, ensuring the target ESP32 is responsive and ready for flashing.</li><li><strong>Configuring the SPI Flash:</strong> Using the <strong>SPI_ATTACH command</strong>, the master configures the target ESP32’s flash memory. This step prepares the hardware to receive and write the incoming firmware data.</li><li><strong>Initializing the Flash Process:</strong> The <strong>FLASH_BEGIN command</strong> tells the target ESP32 how much data to expect, where to store it in memory, and what block sizes will be used. This setup ensures the flashing process is smooth and organized.</li><li><strong>Transferring Firmware in Chunks:</strong> The firmware is broken into small chunks (usually 1 KB) and sent using the <strong>FLASH_DATA command</strong>. Each chunk is validated with a checksum and encoded using the SLIP protocol to ensure accurate data transmission.</li><li><strong>Completing the Flashing Process:</strong> Finally, the <strong>FLASH_END command</strong> signals the target that the process is complete. The ESP32 can optionally reboot itself to start running the newly uploaded firmware.</li></ol><h3>Let’s Walk Through a Step-by-Step Guide to Set Up and Program ESP32 with Another ESP32</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*GdBrDscSmwVDLqAKPX0pEQ.png" /></figure><pre>| **Master ESP32 Pin** | **Target ESP32 Pin** |<br>|-----------------------|----------------------|<br>| RX2 (GPIO 16)         | TX0                 |<br>| TX2 (GPIO 17)         | RX0                 |<br>| GND                   | GND                 |<br>| VIN                   | VIN                 |<br>| GPIO 25               | GPIO 0 (BOOT)       |<br>| GPIO 26               | EN                  |</pre><p>The connections described above allow the master ESP32 to automatically put the target ESP32 into boot mode using GPIO 25 and GPIO 26, which are connected to the target ESP32’s GPIO 0 (BOOT) and EN pins, respectively.</p><p><strong>If GPIO 0 is not available on your ESP32 target board, you may need to solder a connection between master esp32 GPIO 25 and BOOT button.</strong></p><p>Alternatively, you can manually put the target ESP32 into boot mode (download mode) by following these steps:</p><ol><li>Press and hold the BOOT button.</li><li>While holding the BOOT button, press and release the RESET button.</li><li>Release the BOOT button.</li></ol><p>This will successfully place the target ESP32 into boot mode.</p><h4>Preparing the Firmware for the Target ESP32</h4><p>We will create a basic firmware to flash onto the target ESP32 for testing purposes. This simple code will help ensure that the target ESP32 is functioning correctly.</p><pre>void setup() {<br>  // Initialize serial communication at 115200 baud rate<br>  Serial.begin(115200);<br>}<br><br>void loop() {<br>  // Print the message &quot;Successful OTA Update&quot; to the serial monitor<br>  Serial.println(&quot;Successfully flashed the firmware to the target ESP32&quot;);<br>  <br>  // Wait for one second before repeating the loop<br>  delay(1000);<br>}</pre><p>follow these steps:</p><p>Open Arduino IDE and copy the above code into a new sketch. Save the sketch with an appropriate name.</p><p>Select the ESP32 board by going to Tools &gt; Board &gt; ESP32 Dev Module.</p><p>Choose the partition scheme <strong>Default 4MB with SPIFFS (1.2MB app/1.5MB SPIFFS)</strong>. You can select any partition scheme, but ensure that the chosen scheme has sufficient space to accommodate the firmware upload.</p><p>Compile the code by clicking on the checkmark icon (Verify) or by going to Sketch &gt; Verify/Compile.</p><p>After compilation, go to Sketch &gt; Export Compiled Binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*OSnLYPU2rnM9LvzvwhoWHw.png" /></figure><p>A .bin file will be generated in the same location where you saved the test code. You can rename the file to any name you prefer; for example, I renamed it to <strong>Firmware.bin</strong>.</p><p><strong>Next, follow these steps:</strong></p><ol><li>Create a folder named <strong>data</strong> in the master ESP32 code directory.</li><li>Copy the generated .bin file (e.g., <strong>Firmware.bin</strong>) into the <strong>data</strong> folder.</li><li>Use the <strong>ESP32 Filesystem Uploader</strong> to upload the .bin file to the master ESP32’s <strong>SPIFFS</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*2h7S-N6d3YZzLCgY4cvUig.png" /></figure><p>If the <strong>ESP32 File System Uploader</strong> option is not available, follow the tutorial provided at <a href="https://github.com/me-no-dev/arduino-esp32fs-plugin">this GitHub repository</a> to install and configure the plugin.</p><h4>Master ESP32 Setup and Flash Firmware</h4><p>Below is the main code that needs to be uploaded to the master ESP32. In the function espflasher.espFlashBinFile(&quot;/firmware.bin&quot;), provide the binary file name as the input.</p><p>Additionally, ensure that the SPIFFS library is included in the ESP32 project, as shown in the code.</p><p><strong>You can download the code from my GitHub repository: </strong><a href="https://github.com/adityabangde/ESP32-Flasher.git"><strong>GitHub Repository Link.</strong></a></p><pre>#include &quot;esp32_flasher.h&quot;<br><br>ESP32Flasher espflasher;<br><br>void setup() {<br>  Serial.begin(115200);         // Start communication With IDE to see whats going on<br>  delay(5000);                  // wait 5 seconds before Starting<br>  if (SPIFFS.begin(true))       //Must begin SD CARD before trying to flash Wifi module, will fail if not connected<br>  {<br>    Serial.println(&quot;spiffs begin&quot;);<br><br>    espflasher.espFlasherInit();//sets up Serial communication to another esp32<br><br>    int connect_status = espflasher.espConnect();<br><br>    if (connect_status != SUCCESS) {<br>      Serial.print(&quot;Cannot connect to target&quot;);<br>    }<br>    Serial.print(&quot;Connected to target\n&quot;);<br><br>    espflasher.espFlashBinFile(&quot;/firmware.bin&quot;);<br>  }<br>}<br><br>void loop() {<br>  // put your main code here, to run repeatedly:<br><br>}</pre><p>Copy the code into the Arduino IDE, choose the correct ESP32 board, select the partition scheme and port. Upload the code to your Master ESP32, then open the serial monitor to witness the enchantment unfold before your eyes!</p><h4>Master and Target ESP32 Serial Monitor Outputs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psR7nuSjLS-rF7f7WYXuQA.png" /><figcaption>Master Esp32 output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*qaRSJH2aUXYMNb07mnZZSw.png" /><figcaption>Target Esp32 output</figcaption></figure><h4>conclusion</h4><p>And there you have it! With some wiring magic, SPIFFS sorcery, and a touch of ESP32 wizardry, your firmware will leap from master to target like a well-trained ninja. Flash responsibly — no ESP32s were harmed in the making of this tutorial! 🚀. Stay tuned, as I’ll dive into how the code works in the next article! 🔧📚</p><h4>Hold tight for the next adventure as we explore the exciting blend of Digital Signal Processing, Neural Networks, Embedded Systems, and VHDL — coming soon!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4798ddce70b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convolution for dummies!]]></title>
            <link>https://medium.com/@adityabangde/convolution-for-dummies-ac1ed043b91b?source=rss-2be6af53912d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac1ed043b91b</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Aditya Bangde]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 02:45:57 GMT</pubDate>
            <atom:updated>2024-12-31T08:56:38.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpU__jkFVGuOKJvf_W1mqA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bkaraivanov?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Bozhin Karaivanov</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-sheet-of-paper-with-numbers-on-it-5z70PsbFCMM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4><strong>Once upon a time</strong></h4><p>A buddy of mine shows up out of nowhere and asks, “What’s the deal with convolution in Convolutional Neural Networks?” I tried to explain, but let’s just say I wasn’t exactly clear. I could picture convolutions in my head, but putting it into words? Not so much!</p><p>So, I went on a wild internet search, but all I found were articles buried in jargon, talking about combining two functions to make a third. Really? After sifting through all that, I realized we need simple, relatable explanations. So, let’s break it down — no fancy stuff, just the basics. Let’s dive in!</p><h4>Definition</h4><p>here’s a simplified convolution equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRpzLUpEcCbZ5DgeGeWuAg.png" /></figure><p>In simple terms, you can think of convolution as a more sophisticated version of multiplication. Just for now, read the points below, and with an example, we’ll understand what each element means. After that, everything will start to make sense.</p><p><strong>y[n]:</strong> This is the result (or output) of the convolution at the point <strong><em>n</em></strong>. Think of it as the “final answer” you’re calculating at time step<em> </em><strong><em>n</em></strong>.</p><p><strong>x[k]:</strong> This represents the input signal, indexed by <strong><em>k</em></strong>. It’s one of the signals involved in the convolution process. Essentially, it’s the signal you’re applying a transformation to.</p><p><strong>h[n−k]:</strong> This is the system’s impulse response (or filter), flipped and shifted by <strong><em>n−k</em></strong>. It defines how the system reacts to the input. The shift <strong><em>n−k</em></strong> aligns the function with the input signal at different points.</p><p><strong>∑k=−∞ to ∞:</strong> This represents the summation. You’re adding up the product of <strong><em>x[k]</em></strong> and the shifted version of <strong><em>h</em></strong> over all possible values of <strong><em>k</em></strong>. For finite-length signals, the summation typically covers a smaller range.</p><h4>Real World Example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*PyRG8vIailAUj6cddd_6Mw.png" /><figcaption>This graph was generated using Python’s Matplotlib library.</figcaption></figure><pre>original_data = [98.55, 91.84, 87.04, 85.83, 79.63, 75.67, 66.58, 65.05,60.56,<br>53.74, 47.15, 43.91, 37.57, 33.22, 24.81, 23.28,13.74, 10.66, 4.94, 0.00]</pre><p>The data presented here is obtained from a LIDAR sensor, which measures water levels ranging from 0 (indicating empty) to 100 (indicating full). In the graph, this data is visualized by the blue line, which clearly exhibits some noise.</p><p>Now, imagine you want to control a motor using an Arduino based on this data. For instance, you might write a condition such as</p><pre>if(value == 0) { <br>turnOnTheMotor(); <br>}<br>else {<br>turnOffTheMotor();<br>}<br><br>OR<br><br>if(value &lt; 5) { <br>turnOnTheMotor(); <br>}<br>else {<br>turnOffTheMotor();<br>}</pre><p>However, due to the fluctuations or noise in the sensor readings, the values may drop to 0 or below 5 momentarily, then suddenly rise to 6, only to fall back to 4. In this scenario, the motor would turn on and off repeatedly, which is not ideal.</p><p>Our goal is to ensure the motor operates smoothly and consistently, avoiding any unintended triggering caused by noisy data fluctuations.</p><h4><strong>Conditioning the data for our intended use</strong></h4><p>To ensure smooth motor operation, we need to eliminate noise from the data. We will do this by averaging the data in windows of 4 values, shifting the window by one value at a time, and calculating the average again until we reach the end. This process is essentially the <strong>Moving Average</strong>.</p><p>We begin by adding <strong>edge padding </strong>to the data to ensure that the averaging process doesn’t result in fewer values. If you try applying the moving average to the 20 values without padding, you’ll end up with only 16 values. With edge padding, we add threevalues at the beginning, identical to the first value, that are <strong>[98.55, 98.55, 98.55]</strong></p><pre>original_data_with_edge_padding = [98.55, 98.55, 98.55, 98.55, 91.84, 87.04, <br>85.83, 79.63, 75.67, 66.58, 65.05, 60.56, 53.74, 47.15, 43.91, 37.57, <br>33.22, 24.81, 23.28, 13.74, 10.66, 4.94, 0.00]</pre><h4>A different viewpoint</h4><p>For first window, we would calculate <strong>(98.55 + 98.55 + 98.55 + 98.55)/4 = 98.55 </strong>Alternatively, we can express this as: <strong>98.55/4+98.55/4+98.55/4+98.55/4 </strong>Or, using multiplication: <strong>1/4 = 0.25 98.55×0.25+98.55×0.25+98.55×0.25+98.55×0.25</strong></p><p>Either way, we will still get the same result:<strong> 98.55.</strong></p><p>Now, if we separate the<strong> 0.25</strong> values and consider them as one signal <strong>[0.25, 0.25, 0.25, 0.25]</strong>, and slide this over our data (which is treated as another signal), we can perform the <strong>Moving Average</strong>. The final result, as shown in the GIF below, represents this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kw5IcwH_fSnpR8upG6-utQ.gif" /><figcaption>The above animation was created using the Python Manim library.</figcaption></figure><p>After plotting the resulting data, we obtain the smooth red line shown in the graph above. With this smooth data, we can now directly apply our code logic to control the motor, turning it on and off seamlessly.</p><h4>Relating Our Example to Mathematical Equations</h4><p>We performed what could be called “<strong>fancy multiplication</strong>,” which is essentially convolution. This process involves sliding a window, multiplying values within it, and summing up to get a result at each step. For example, with the expression <strong>8.55×0.25+98.55×0.25+98.55×0.25+91.84×0.25</strong></p><p>Here, <strong><em>n</em></strong> ranges from 0 to 19 (20 values total). We have the original data <strong><em>x</em></strong>, where <strong>x[0] = 98.55 x[1] = 91.84 x[2] = 87.04</strong> ...and so on with padding added on the left so <strong>x[-3] = 98.55, x[-2] = 98.55, x[-2] = 98.55</strong> and our original signal starts from <strong>x[0]</strong></p><p>For the kernel <strong><em>h[k]</em></strong> <strong><em>k</em></strong> ranges from 0 to 3, with values <strong>h[0] = 0.25 h[1] = 0.25 h[2] = 0.25 h[3] = 0.25</strong></p><p>Apply convolution formula <strong><em>y[n] = Σ h[k] × x[n-k]</em></strong> <strong>NOTE — The convolution formula can actually be written both ways!</strong></p><p>For <strong>y[0]</strong> (where <strong>n = 0</strong>): <strong>h[0]×x[0–0] + h[1]×x[0-1] + h[2]×x[0-2] + h[3]×x[0–3] = 0.25×98.55 + 0.25×98.55 + 0.25×98.55 + 0.25×98.55 = 98.55</strong></p><p>For <strong>y[1] </strong>(where <strong>n = 1</strong>): <strong>y[1] = h[0]×x[1–0] + h[1]×x[1–1] + h[2]×x[1–2] + h[3]×x[1–3] =</strong> <strong>0.25×91.84 + 0.25×98.55 + 0.25×98.55 + 0.25×98.55 = 96.9</strong></p><p>For<strong> y[2] </strong>(where <strong>n = 2</strong>): <strong>y[2] = h[0]×x[2–0] + h[1]×x[2–1] + h[2]×x[2–2] + h[3]×x[2–3] = 0.25×87.04 + 0.25×91.84 + 0.25×98.55 + 0.25×98.55 = 94.00</strong></p><p>We repeated this process for all values until the end, where the array <strong>[0.25,0.25,0.25,0.25]</strong> represents <strong><em>h[k]</em></strong>, and the original data is represented as <strong><em>x[k]</em></strong>. The output is represented by <strong><em>y[n]</em></strong>. Essentially, we averaged the values within a window at each step, then shifted the window and repeated the averaging, and so on.</p><p><strong>Wait, are we missing something?</strong> Yes! Instead of using <strong><em>h[k]</em></strong>, we actually need <strong><em>h[n−k].</em></strong> <strong>Why does this matter?</strong> Let’s break it down: If we flip <strong><em>h[k]</em></strong> which becomes <strong><em>h[-k]</em></strong>(the filter signal), in our case [0.25,0.25,0.25,0.25], we get the same value because it’s symmetric. However, when we use <strong><em>h[n−k]</em></strong>, we are shifting the signal by n times. This shifted signal allows us to begin averaging from the starting value.</p><h4><strong>Understanding Signal Flipping Through the HELLOWORLD Analogy</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1IwhCPlzsGga5HwEQDUDQ.gif" /><figcaption>The above animation was created using the Python Manim library.</figcaption></figure><p>Let’s understand this through an analogy. Imagine you have recorded the signal <strong>[H, E, L, L, O, W, O, R, L, D]</strong>, where at the 1st second, you record and save ‘H’, at the 2nd second ‘E’, and so on, all saved in memory. Now, you want to feed this signal into your system for sound recognition processing, which uses the convolution method (sliding window).</p><p>Our sound system processes the entire <strong>“HELLOWORLD”</strong> signal at once. In this system, ‘H’ from <strong>“HELLO”</strong> represents the present value, while <strong>‘D’</strong> from <strong>“WORLD”</strong> represents the future value. To properly process the sound, we need to consider both the present and future values in the correct order.</p><p>If we slide the <strong>“HELLOWORLD”</strong> window without flipping the signal, we might start with <strong>‘D’</strong> (which is a future value) rather than <strong>‘H’</strong> (the present value), which would cause errors in processing. Flipping the signal ensures that we align the “<strong>present</strong>” values of the input signal (starting with <strong>‘H’</strong>) with the corresponding response of the system. This way, the convolution will start with <strong>‘H’</strong> and slide through the sequence correctly, preserving the natural flow from present to future.</p><h4>Bottom line</h4><p>Flipping helps ensure that we’re always aligning corresponding points in time between two signals, especially when we want the current time step (or present value) of one signal to align with the current time step of the other. Without flipping, we might accidentally align future values from one signal with present values from the other, leading to incorrect results. Flipping one of the signals prevents this mismatch, ensuring that the signals are aligned correctly during the convolution process as we slide them across each other.</p><h4>So, we finally cracked the code!</h4><p>We figured out why we slide a window — it’s the only way out of the “math jungle.” We learned what <strong>y[n]</strong>, <strong>x[k]</strong>, and <strong>h[n-k]</strong> are (spoiler alert: they’re just fancier names for our signals), and we understood why we did all that summation (because, apparently, math loves to add things up).</p><p>And let’s not forget the ultimate trick: flipping and shifting the filter. It’s like giving our signal a little somersault before it goes on stage — and now we know why it matters!</p><p>Mission accomplished — let’s move on before the math gets any more dramatic!</p><h4>Hold tight for the next adventure as we explore the exciting blend of Digital Signal Processing, Neural Networks, Embedded Systems, and VHDL — coming soon!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac1ed043b91b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ESP32 Firmware Updates from GitHub: A Simple OTA Solution]]></title>
            <link>https://medium.com/@adityabangde/esp32-firmware-updates-from-github-a-simple-ota-solution-173a95f4a97b?source=rss-2be6af53912d------2</link>
            <guid isPermaLink="false">https://medium.com/p/173a95f4a97b</guid>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[esp32-programming]]></category>
            <category><![CDATA[over-the-air-programming]]></category>
            <dc:creator><![CDATA[Aditya Bangde]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 15:33:02 GMT</pubDate>
            <atom:updated>2024-03-15T17:00:10.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghP9GkP97sgJ_60XNHT-Tg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@vishnumaiea?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Vishnu Mohanan</a> on <a href="https://unsplash.com/photos/a-white-board-with-a-bunch-of-wires-attached-to-it-r98pDCvbcfM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the world of embedded systems, <strong>Over-The-Air (OTA)</strong> updates are essential. They allow developers to remotely update device software without physical access. ESP32, known for its versatility, offers OTA capabilities, simplifying the update process.</p><p>However, implementing OTA updates isn’t always straightforward. Many articles discuss ESP32 OTA code, often involving storing firmware in SPIFFS or on an SD card. Remote access typically requires setting up and hosting a server, which involves coding and costs.</p><p>This article presents a solution: leveraging GitHub for OTA updates. By storing firmware binaries on GitHub, we sidestep the complexities of hosting servers and writing API code. Instead, we write ESP32 code to fetch and install updates directly from GitHub, streamlining the process.</p><h3><strong>Let’s Walk Through Every Step: Simplifying ESP32 OTA Updates with GitHub.</strong></h3><h4><strong>1. First, we’ll write a basic code and use it to upload onto the ESP32 via OTA</strong></h4><p>Below is the code for a simple serial print program that will print “Successful OTA Update” every one second to indicate a successful OTA update</p><pre>void setup() {<br>  // Initialize serial communication at 115200 baud rate<br>  Serial.begin(115200);<br>}<br><br>void loop() {<br>  // Print the message &quot;Successful OTA Update&quot; to the serial monitor<br>  Serial.println(&quot;Successful OTA Update&quot;);<br>  <br>  // Wait for one second before repeating the loop<br>  delay(1000);<br>}</pre><p>follow these steps:</p><ol><li>Open Arduino IDE and copy the above code into a new sketch.</li><li>Save the sketch with an appropriate name.</li><li>Select the ESP32 board by going to Tools &gt; Board &gt; ESP32 Dev Module.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*zH8b0ckK7WosllhO3b-doA.png" /></figure><p>Choose the partition scheme Default 4MB with spiffs (1.2MB app/1.5MB spiffs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8uVqEacva74tXwaIu2ZASA.png" /></figure><p>Compile the code by clicking on the checkmark icon (Verify) or by going to Sketch &gt; Verify/Compile.</p><p>After compilation, go to Sketch &gt; Export Compiled Binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*OSnLYPU2rnM9LvzvwhoWHw.png" /></figure><p>A .bin file will be generated and saved in the same location where you saved your Arduino sketch.</p><h4><strong>2. Next, we’ll upload the .bin file to GitHub and delve into the GitHub raw file URL HTTP request header using Postman together.</strong></h4><p>You can find tons of good articles, like <a href="https://docs.github.com/en/get-started/start-your-journey/uploading-a-project-to-github"><strong>this one</strong></a>, to guide you on creating a repository on GitHub and uploading files.</p><p>Now we need to construct a GitHub raw file link to access our binary file directly. When referring to a “<strong>GitHub raw file</strong>,” it means accessing the unformatted content of a file hosted on GitHub. GitHub provides a specific URL pattern for this purpose. Here’s how to construct the URL:</p><p><a href="https://raw.githubusercontent.com/%7Busername%7D/%7Brepository%7D/%7Bbranch%7D/%7Bfilepath"><strong>https://raw.githubusercontent.com/{username}/{repository}/{branch}/{filepath</strong></a><strong>}</strong></p><ul><li>{username}: Your GitHub username or organization name that owns the repository.</li><li>{repository}: The name of your GitHub repository.</li><li>{branch}: The branch name where the file is located (e.g., main, master, dev, etc.).</li><li>{filepath}: The path to your binary file within the repository.</li></ul><p>For example, if you have a binary file named ota_code.bin located in the dev branch of your GitHub repository adityabangde/ESP32-OTA-Update-via-GitHub, the corresponding raw file URL will be:</p><p><a href="https://raw.githubusercontent.com/adityabangde/ESP32-OTA-Update-via-GitHub/dev/ota_code.bin"><strong>https://raw.githubusercontent.com/adityabangde/ESP32-OTA-Update-via-GitHub/dev/ota_code.bin</strong></a></p><h4>3. We have our URL, and now we’ll use Postman to view the HTTP request header.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6LNIpflyGR-Nrmmg81FHg.png" /></figure><ol><li>Open the Postman application and click on the <strong>“+” </strong>icon to create a new request.</li><li>Paste the URL into the URL box in the newly opened window.</li><li>Select the GET request method from the dropdown menu next to the URL box.</li><li>Click on the “Code” button (highlighted box) in the Postman interface to view the code snippet.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*5O8CDMZvdBTQnJR-yZLd9Q.png" /></figure><ol><li>In the code snippet window, select “HTTP” from the dropdown menu to view the HTTP request header.</li></ol><p>We will use the HTTP request header generated by Postman in our code.</p><h4>4. Finally, we’ll construct all necessary functions one by one to complete our main code.</h4><p>We will include all the necessary libraries needed for our code</p><pre>#include &lt;WiFi.h&gt;<br>#include &lt;SPIFFS.h&gt;<br>#include &quot;Update.h&quot;<br>#include &lt;WiFiClientSecure.h&gt;<br><br>// Define WiFi credentials<br>#define ssid &quot;SSID&quot;<br>#define password &quot;PASSWORD&quot;<br><br>// Define server details and file path<br>#define HOST &quot;raw.githubusercontent.com&quot;<br>#define PATH &quot;/adityabangde/ESP32-OTA-Update-via-GitHub/dev/ota_code.bin&quot;<br>#define PORT 443<br><br>// Define the name for the downloaded firmware file<br>#define FILE_NAME &quot;firmware.bin&quot;</pre><p>The <strong>SPIFFS.h</strong> library helps manage files in ESP32’s flash memory, acting like a traditional file system. It’s handy for storing and organizing data without external storage devices. <strong>Update.h</strong> enables OTA updates for ESP32, letting you update firmware without USB connections or re-flashing. For secure connections, ESP32’s <strong>WiFiClientSecure.h</strong> class is essential, especially for HTTPS connections using SSL/TLS. By using <strong>client.setInsecure(),</strong> we bypass SSL/TLS certificate verification, simplifying secure connection handling during development.</p><pre>void connectToWiFi() {<br>  // Begin connecting to WiFi using the provided SSID and password<br>  WiFi.begin(ssid, password);<br><br>  // Display connection progress<br>  Serial.print(&quot;Connecting to WiFi&quot;);<br>  <br>  // Wait until WiFi is connected<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  <br>  // Print confirmation message when WiFi is connected<br>  Serial.println(&quot;WiFi connected&quot;);<br>}</pre><p>This function <strong>connectToWiFi()</strong> initiates a connection to a WiFi network using the specified <strong>SSID</strong> and <strong>password</strong>. It continuously checks for the WiFi connection status until it successfully connects (<strong>WL_CONNECTED</strong>). During the connection process, it prints progress dots (.) to the serial monitor. Once the connection is established, it prints &quot;<strong>WiFi connected</strong>&quot; to indicate a successful connection.</p><pre>void getFileFromServer() {<br>  WiFiClientSecure client;<br>  client.setInsecure(); // Set client to allow insecure connections<br><br>  if (client.connect(HOST, PORT)) { // Connect to the server<br>    Serial.println(&quot;Connected to server&quot;);<br>    client.print(&quot;GET &quot; + String(PATH) + &quot; HTTP/1.1\r\n&quot;); // Send HTTP GET request<br>    client.print(&quot;Host: &quot; + String(HOST) + &quot;\r\n&quot;); // Specify the host<br>    client.println(&quot;Connection: close\r\n&quot;); // Close connection after response<br>    client.println(); // Send an empty line to indicate end of request headers<br><br>    File file = SPIFFS.open(&quot;/&quot; + String(FILE_NAME), FILE_WRITE); // Open file in SPIFFS for writing<br>    if (!file) {<br>      Serial.println(&quot;Failed to open file for writing&quot;);<br>      return;<br>    }<br><br>    bool endOfHeaders = false;<br>    String headers = &quot;&quot;;<br>    String http_response_code = &quot;error&quot;;<br>    const size_t bufferSize = 1024; // Buffer size for reading data<br>    uint8_t buffer[bufferSize];<br><br>    // Loop to read HTTP response headers<br>    while (client.connected() &amp;&amp; !endOfHeaders) {<br>      if (client.available()) {<br>        char c = client.read();<br>        headers += c;<br>        if (headers.startsWith(&quot;HTTP/1.1&quot;)) {<br>          http_response_code = headers.substring(9, 12);<br>        }<br>        if (headers.endsWith(&quot;\r\n\r\n&quot;)) { // Check for end of headers<br>          endOfHeaders = true;<br>        }<br>      }<br>    }<br><br>    Serial.println(&quot;HTTP response code: &quot; + http_response_code); // Print received headers<br><br>    // Loop to read and write raw data to file<br>    while (client.connected()) {<br>      if (client.available()) {<br>        size_t bytesRead = client.readBytes(buffer, bufferSize);<br>        file.write(buffer, bytesRead); // Write data to file<br>      }<br>    }<br>    file.close(); // Close the file<br>    client.stop(); // Close the client connection<br>    Serial.println(&quot;File saved successfully&quot;);<br>  }<br>  else {<br>    Serial.println(&quot;Failed to connect to server&quot;);<br>  }<br>}</pre><ul><li>The function <strong>getFileFromServer()</strong> establishes a insecure connection to the server using HTTPS.</li><li>It sends an HTTP GET request to retrieve the specified file (<strong>PATH</strong>) from the server (<strong>HOST</strong> and <strong>PORT</strong>).</li><li>The received HTTP response headers are read until a blank line (<strong>\r\n\r\n</strong>) indicates the end of headers.</li><li>The raw binary data following the headers is read and written to a file in SPIFFS in chunks of 1KB.</li><li>The file is closed, and the client connection is stopped after the download is complete.</li></ul><p>Make sure to replace <strong>HOST, </strong><strong>PORT, </strong><strong>PATH</strong>, and <strong>FILE_NAME</strong> with your actual server details and file information.</p><pre>void performOTAUpdateFromSPIFFS() {<br>  // Open the firmware file in SPIFFS for reading<br>  File file = SPIFFS.open(&quot;/&quot; + String(FILE_NAME), FILE_READ);<br>  if (!file) {<br>    Serial.println(&quot;Failed to open file for reading&quot;);<br>    return;<br>  }<br><br>  Serial.println(&quot;Starting update..&quot;);<br>  size_t fileSize = file.size(); // Get the file size<br>  Serial.println(fileSize);<br><br>  // Begin OTA update process with specified size and flash destination<br>  if (!Update.begin(fileSize, U_FLASH)) {<br>    Serial.println(&quot;Cannot do the update&quot;);<br>    return;<br>  }<br><br>  // Write firmware data from file to OTA update<br>  Update.writeStream(file);<br><br>  // Complete the OTA update process<br>  if (Update.end()) {<br>    Serial.println(&quot;Successful update&quot;);<br>  }<br>  else {<br>    Serial.println(&quot;Error Occurred:&quot; + String(Update.getError()));<br>    return;<br>  }<br><br>  file.close(); // Close the file<br>  Serial.println(&quot;Reset in 4 seconds....&quot;);<br>  delay(4000);<br>  ESP.restart(); // Restart ESP32 to apply the update<br>}</pre><ul><li>This function <strong>performOTAUpdateFromSPIFFS()</strong> performs an OTA update using firmware stored in SPIFFS.</li><li>It opens the firmware file in read mode (<strong>FILE_READ</strong>) from SPIFFS and checks if the file is opened successfully.</li><li>It begins the OTA update process by specifying the firmware size and flash destination (<strong>U_FLASH</strong>).</li><li>The firmware data is then written from the file to the OTA update process using <strong>Update.writeStream(file)</strong>.</li><li>After completing the update, it checks for success using <strong>Update.end()</strong>. If successful, it prints a success message; otherwise, it prints the error code.</li><li>Finally, it closes the file, delays for 4 seconds to allow the message to be displayed, and restarts the ESP32 to apply the update.</li></ul><h4>Here is the entire code</h4><pre>#include &lt;WiFi.h&gt;<br>#include &lt;SPIFFS.h&gt;<br>#include &quot;Update.h&quot;<br>#include &lt;WiFiClientSecure.h&gt;<br><br>// Define WiFi credentials<br>#define ssid &quot;SSID&quot;<br>#define password &quot;PASSWORD&quot;<br><br>// Define server details and file path<br>#define HOST &quot;raw.githubusercontent.com&quot;<br>#define PATH &quot;/adityabangde/ESP32-OTA-Update-via-GitHub/dev/ota_code.bin&quot;<br>#define PORT 443<br><br>// Define the name for the downloaded firmware file<br>#define FILE_NAME &quot;firmware.bin&quot;<br><br>void setup() {<br>  Serial.begin(115200);<br><br>  if (!SPIFFS.begin(true)) {<br>    Serial.println(&quot;SPIFFS Mount Failed&quot;);<br>    return;<br>  }<br><br>  connectToWiFi();<br>  getFileFromServer();<br>  performOTAUpdateFromSPIFFS();<br>}<br><br>void loop() {<br>  // Nothing to do here<br>}<br><br>void connectToWiFi() {<br>  // Begin connecting to WiFi using the provided SSID and password<br>  WiFi.begin(ssid, password);<br><br>  // Display connection progress<br>  Serial.print(&quot;Connecting to WiFi&quot;);<br>  <br>  // Wait until WiFi is connected<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  <br>  // Print confirmation message when WiFi is connected<br>  Serial.println(&quot;WiFi connected&quot;);<br>}<br><br><br>void getFileFromServer() {<br>  WiFiClientSecure client;<br>  client.setInsecure(); // Set client to allow insecure connections<br><br>  if (client.connect(HOST, PORT)) { // Connect to the server<br>    Serial.println(&quot;Connected to server&quot;);<br>    client.print(&quot;GET &quot; + String(PATH) + &quot; HTTP/1.1\r\n&quot;); // Send HTTP GET request<br>    client.print(&quot;Host: &quot; + String(HOST) + &quot;\r\n&quot;); // Specify the host<br>    client.println(&quot;Connection: close\r\n&quot;); // Close connection after response<br>    client.println(); // Send an empty line to indicate end of request headers<br><br>    File file = SPIFFS.open(&quot;/&quot; + String(FILE_NAME), FILE_WRITE); // Open file in SPIFFS for writing<br>    if (!file) {<br>      Serial.println(&quot;Failed to open file for writing&quot;);<br>      return;<br>    }<br><br>    bool endOfHeaders = false;<br>    String headers = &quot;&quot;;<br>    String http_response_code = &quot;error&quot;;<br>    const size_t bufferSize = 1024; // Buffer size for reading data<br>    uint8_t buffer[bufferSize];<br><br>    // Loop to read HTTP response headers<br>    while (client.connected() &amp;&amp; !endOfHeaders) {<br>      if (client.available()) {<br>        char c = client.read();<br>        headers += c;<br>        if (headers.startsWith(&quot;HTTP/1.1&quot;)) {<br>          http_response_code = headers.substring(9, 12);<br>        }<br>        if (headers.endsWith(&quot;\r\n\r\n&quot;)) { // Check for end of headers<br>          endOfHeaders = true;<br>        }<br>      }<br>    }<br><br>    Serial.println(&quot;HTTP response code: &quot; + http_response_code); // Print received headers<br><br>    // Loop to read and write raw data to file<br>    while (client.connected()) {<br>      if (client.available()) {<br>        size_t bytesRead = client.readBytes(buffer, bufferSize);<br>        file.write(buffer, bytesRead); // Write data to file<br>      }<br>    }<br>    file.close(); // Close the file<br>    client.stop(); // Close the client connection<br>    Serial.println(&quot;File saved successfully&quot;);<br>  }<br>  else {<br>    Serial.println(&quot;Failed to connect to server&quot;);<br>  }<br>}<br><br>void performOTAUpdateFromSPIFFS() {<br>  // Open the firmware file in SPIFFS for reading<br>  File file = SPIFFS.open(&quot;/&quot; + String(FILE_NAME), FILE_READ);<br>  if (!file) {<br>    Serial.println(&quot;Failed to open file for reading&quot;);<br>    return;<br>  }<br><br>  Serial.println(&quot;Starting update..&quot;);<br>  size_t fileSize = file.size(); // Get the file size<br>  Serial.println(fileSize);<br><br>  // Begin OTA update process with specified size and flash destination<br>  if (!Update.begin(fileSize, U_FLASH)) {<br>    Serial.println(&quot;Cannot do the update&quot;);<br>    return;<br>  }<br><br>  // Write firmware data from file to OTA update<br>  Update.writeStream(file);<br><br>  // Complete the OTA update process<br>  if (Update.end()) {<br>    Serial.println(&quot;Successful update&quot;);<br>  }<br>  else {<br>    Serial.println(&quot;Error Occurred:&quot; + String(Update.getError()));<br>    return;<br>  }<br><br>  file.close(); // Close the file<br>  Serial.println(&quot;Reset in 4 seconds....&quot;);<br>  delay(4000);<br>  ESP.restart(); // Restart ESP32 to apply the update<br>}</pre><p>Copy the code into the Arduino IDE, choose the correct ESP32 board, select the partition scheme and port as shown in the image guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsBKcNmYTMD1PjigFq4pQA.png" /></figure><p>Upload the code to your ESP32, then open the serial monitor to witness the enchantment unfold before your eyes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*ETu7_300LgOVkJWjKqJ-bw.png" /></figure><h3><strong>5. Conclusion</strong></h3><p>we’ve learned how to update ESP32 firmware wirelessly using GitHub and HTTP requests. By storing firmware in SPIFFS and leveraging libraries, remote updates become seamless. This empowers developers to enhance devices with ease and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=173a95f4a97b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>