<?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 Rafiul islam on Medium]]></title>
        <description><![CDATA[Stories by Rafiul islam on Medium]]></description>
        <link>https://medium.com/@rafiulislam25?source=rss-17efd2adef50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*znkj6DMeApLFu3ER05F2PA.jpeg</url>
            <title>Stories by Rafiul islam on Medium</title>
            <link>https://medium.com/@rafiulislam25?source=rss-17efd2adef50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:00:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafiulislam25/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[I Built an Early-Warning Device for Load Shedding. Here’s What I Got Wrong.]]></title>
            <link>https://rafiulislam25.medium.com/i-built-an-early-warning-device-for-load-shedding-heres-what-i-got-wrong-2d09e4ea9191?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d09e4ea9191</guid>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 13:32:47 GMT</pubDate>
            <atom:updated>2026-12-04T13:32:47.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taLqb0JU8mRBu4AlA12ZkA.jpeg" /><figcaption><strong>EdgeVolt Prototype. Dashboard values are mock data.</strong></figcaption></figure><p><em>EdgeVolt: the project, the reason behind it, the mistakes, the lessons, and the roadmap for the next 30 days.</em></p><p><em>By Md. Rafiul Islam · Department of IoT and Robotics Engineering, University of Frontier Technology, Bangladesh (UFTB)</em></p><h3>What is EdgeVolt?</h3><p>EdgeVolt is a low-cost IoT device, plus the software around it, that does two things for a household or a small workplace in Bangladesh:</p><ol><li>It <strong>raises an alarm within one second</strong> when the supply sags or drops, even when there is no internet.</li><li>It <strong>estimates the chance that a power outage will begin in the next 30 minutes</strong>, using its own measurements.</li></ol><p>The project at a glance:</p><ul><li><strong>What:</strong> an ESP32 node that measures voltage, current, frequency, temperature and humidity once per second.</li><li><strong>Cost:</strong> about BDT 2,000 (roughly USD 17) per node.</li><li><strong>Brain:</strong> a tiny decision tree on the device for instant alerts, and an XGBoost model on a server for the 30-minute forecast.</li><li><strong>What you see:</strong> a live dashboard with trends, anomalies, outage risk and an estimated cost of each outage in BDT.</li><li><strong>Status:</strong> the software is complete. The machine-learning results come from a 60-day <em>simulated</em> benchmark with 92 outage events. The hardware is assembled; calibration and real-data collection are in progress.</li><li><strong>Open source (MIT):</strong> <a href="https://github.com/rafiul254/EdgeVolt">rafiul254/EdgeVolt: Edge-Intelligent Load Shedding Prediction and Real-Time Monitoring System for Bangladesh Micro-Level Distribution Grids.</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EuUzGQJZ3lmwPz_S.jpg" /><figcaption><strong>The real bench prototype</strong></figcaption></figure><h3>Why I built it</h3><p><strong>The everyday problem.</strong> Rolling load shedding interrupts supply for hours at a time in peak months. Estimates in the literature we reviewed put the national cost at roughly USD 1–2 billion a year (treat that figure as indicative). Mitigation is centralized and schedule-based. A household at the end of the line gets no advance warning, and voltage-quality problems such as sags and brownouts go unrecorded below the substation.</p><p><strong>The thirty minutes.</strong> The number that kept coming back to me was not a billion dollars. It was thirty minutes. Thirty minutes is enough to save your work, switch off sensitive equipment, charge a phone or start a backup. Today nobody gets them.</p><p><strong>The gap in existing work.</strong> Before building, we reviewed the literature. Demand-forecasting research is strong, but it is centralized and does not tell a single household that its supply is about to drop. IoT power-quality analyzers exist, but they monitor and do not predict. Edge computing for grid analytics exists too. In the studies we reviewed, none combined three things in one low-cost design: <strong>a node at the consumer, a 30-minute outage prediction, and alerts that keep working offline.</strong> That combination is what EdgeVolt tries to deliver.</p><p><strong>Why the intelligence has to live on the device.</strong> During load shedding the router often goes down with everything else. A cloud-only monitor goes silent at exactly the moment you need it. Deciding locally also gives sub-second response, a tiny data stream instead of raw waveforms, and better privacy.</p><p><strong>Where it came from.</strong> EdgeVolt started as an IoT Architecture course project at the University of Frontier Technology, Bangladesh (UFTB). The extended abstract was later accepted at the <strong>IEEE Computer Society Bangladesh Chapter Symposium 2026</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4P03iH-tKk1bXvmJ7HiL0g.png" /><figcaption>Poster of Edgevolt</figcaption></figure><h3>How it works, the short version</h3><p>I think of it as a <strong>reflex</strong> and a <strong>foresight</strong>.</p><ul><li><strong>The reflex (on the ESP32).</strong> Every 200 milliseconds, exactly ten cycles of 50 Hz mains, the firmware computes RMS voltage, current and frequency. A depth-3 decision tree classifies each second: <em>outage</em> below 170 V, <em>sag</em> below 198 V or a drop of more than 6 V within a minute, otherwise <em>normal</em>. It drives a buzzer and LEDs with no network at all.</li><li><strong>The foresight (on the server).</strong> Readings travel over MQTT into InfluxDB. An XGBoost model looks at 54 features built from the last hour (rolling statistics, rates of change, lags, time of day) and answers one question: <em>will an outage begin within 30 minutes?</em></li></ul><p>The design rule is simple: <strong>train big in the cloud, run small at the edge.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68DeaPz7q1B-bY-6CePXqw.png" /><figcaption>Architecture of Edgevolt</figcaption></figure><p><strong>The hardware in four sentences.</strong> The ZMPT101B voltage module is connected in parallel across live and neutral. The SCT-013–030 clamp, 1 V at 30 A with the burden built in, goes around <strong>one</strong> insulated conductor only. An ESP32 cannot read negative voltages, so two resistors and a capacitor lift the current signal onto a 1.65 V mid-rail. The node runs from a power bank, because the device that records an outage has to survive it.</p><p><strong>The evaluation, honestly.</strong> Real labelled data takes weeks, so I built a 60-day simulated benchmark first. The model never trains on minutes already inside an outage, and the split is strictly chronological, never shuffled. Outages are only 3.7% of test minutes, so a model that always says <em>all clear</em> is already 96.3% accurate and useless. I therefore report precision, recall and PR-AUC:</p><ul><li>Tuned threshold: <strong>precision 0.77, recall 0.30</strong>.</li><li>Sensitive threshold: <strong>precision 0.18, recall 0.88</strong>.</li><li><strong>PR-AUC 0.484</strong> against 0.037 for pure chance, about thirteen times better.</li><li>For gradual outages the probability crosses the alert line about <strong>13 minutes</strong> before onset. In one replay, at 20:41 the voltage was about 213 V and the model already said 72%. The simulated outage began at 20:56.</li><li>Sudden outages with no warning sign cannot be predicted from local measurements. That is exactly why the reflex exists.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oy80M1Glb1ymADVgfNUg4A.png" /><figcaption><strong>Mean predicted probability versus minutes until the outage begins</strong></figcaption></figure><h3>What I got wrong</h3><p>A project write-up that only says what went right is not worth reading. Here is what went wrong, what it would have caused, and how it was fixed.</p><p><strong>1. I assumed the wrong current sensor.</strong> The first design assumed an SCT-013–000 (100 A : 50 mA) with an external burden resistor. The clamp in my hand was an SCT-013–030: 1 V at 30 A, with the burden already built in. Same family, completely different circuit and formula. <em>Consequence:</em> wrong current readings by a large factor. <em>Fix:</em> the firmware now uses 30 A per volt and no external burden.</p><p><strong>2. A wiring diagram put the burden in the wrong place.</strong> One diagram we worked from placed the burden resistor in series with the sensor instead of across it. <em>Consequence:</em> a wrongly scaled signal that could also push the ADC pin out of range. <em>Fix:</em> caught in review. Lesson: diagrams, including AI-generated ones, need the same scrutiny as code.</p><p><strong>3. I did not check the voltage module’s supply.</strong> The ZMPT101B output sits near half of its supply voltage. On 5 V that is about 2.5 V, and the peaks can exceed what an ESP32 input tolerates. On 3.3 V some modules cannot swing far enough and clip. <em>Fix:</em> the design uses 3.3 V, with a divider required if you use 5 V. The supply and waveform must still be verified on the exact board.</p><p><strong>4. “Works offline” did not work offline.</strong> The firmware claimed offline alerting, but its main loop waited for Wi-Fi and MQTT. In a real blackout, the router dies and the alarms would have gone silent with it. <em>Fix:</em> non-blocking networking, so sampling and alarms never wait for the network.</p><p><strong>5. My data validator threw away the outages.</strong> A sanity check rejected any voltage below 150 V, which is exactly what an outage looks like. <em>Fix:</em> the validator now checks physical sanity only and keeps sags and outages.</p><p><strong>6. My evaluation was leaky.</strong> Shuffled cross-validation on overlapping rolling features lets the model peek at its own future, and training on minutes already inside an outage turns <em>will it go out?</em> into <em>is it out?</em> <em>Fix:</em> strictly chronological splits, in-outage rows removed, and the threshold tuned on validation data only.</p><p><strong>7. A health check that always said “up”.</strong> The database ping returned false instead of raising an error, so the dashboard reported a healthy database even when it was down. <em>Fix:</em> check the returned value.</p><p><strong>8. Numbers in my own write-up did not match the data.</strong> A README said the voltage was about 230 V at the 20:41 replay. The data says about 213 V. A summary said “twelve times” the random baseline, but 0.484 divided by 0.037 is about thirteen. A draft said “median lead time” when what I had measured was where the mean probability crosses the alert threshold. Another draft said hardware commissioning was complete while calibration was still pending. <em>Fix:</em> recompute and re-word every number.</p><p><strong>9. I almost led with accuracy.</strong> My first headline was 97.1% accuracy. Since 96.3% of test minutes are normal, that number says very little. <em>Fix:</em> precision, recall and PR-AUC lead the results, and accuracy is shown only with that context.</p><p><strong>10. An illustration can look like evidence.</strong> My banner image shows a polished dashboard with readings like 229.8 V. It is an illustration, not a measurement. <em>Fix:</em> it is labelled as a concept illustration, with real photos of the real prototype next to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PxxSiZZlZk_uMsIs58lZw.png" /></figure><h3>What I learned</h3><ul><li><strong>Accuracy is a trap on rare events.</strong> When 96% of the data is normal, a useless model scores 96%. Report precision, recall and PR-AUC, and say which threshold you chose and why.</li><li><strong>Time only moves forward, and so must your split.</strong> If your features overlap in time, shuffling leaks the future into training.</li><li><strong>Design for the failure you are predicting.</strong> A load-shedding monitor that dies with the grid or the router is a contradiction. That is why the node runs on a power bank and alerts offline.</li><li><strong>Read the label of the exact part in your hand.</strong> SCT-013–000 and SCT-013–030 look alike and behave nothing alike. So do 5 V and 3.3 V modules.</li><li><strong>Silent bugs are the dangerous ones.</strong> Loud bugs get fixed. Review the physical interface and the evaluation protocol with the same suspicion you give the model.</li><li><strong>Simulation proves a method, not the world.</strong> It is valuable, but label it clearly, and note which assumptions you built in.</li><li><strong>Recompute every number before you publish it,</strong> including the ones that came from a tool or an assistant.</li><li><strong>Mains electricity is not a toy.</strong> Safety design comes before the demo, not after it.</li><li><strong>Honesty builds trust.</strong> Putting the limitations next to the results makes the results more credible, not less.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2xka_bcxBBnL8BpbTT5eg.png" /></figure><h3>Roadmap: the next 30 days and beyond</h3><p>The next milestone is to replace “validated on a simulator” with “measured on a real socket”. The plan, in order:</p><p><strong>Phase 1: Commissioning (days 1–3).</strong> Calibrate voltage against a multimeter and current against a load of known power. Build an enclosed, fused and insulated mains-side adapter, and have a qualified person inspect it. Targets: voltage within ±2% and current within ±10% on a known load.</p><p><strong>Phase 2: Burn-in (week 1).</strong> Run the node 24/7 and fix every dropout. Target: fewer than 1% unexplained gaps.</p><p><strong>Phase 3: Collection (weeks 2–4).</strong> Continuous one-hertz logging together with an event journal.</p><p><strong>Phase 4: Analysis (final days).</strong> Retrain, compare against baselines, update the report and abstract.</p><p><strong>Upgrades I must make before collecting:</strong></p><ul><li><strong>Keep the logging chain alive during outages.</strong> The ESP32 survives on a power bank, but the router and server die too, so the most important data would never arrive. The fix is a small DC UPS for the router and/or buffering data on the ESP32 and uploading it after reconnection.</li><li><strong>Real timestamps.</strong> Use NTP instead of stamping data on arrival, with an optional RTC for offline periods.</li><li><strong>A 24/7 server</strong> (a Raspberry Pi or mini-PC) with automatic restarts and nightly backups.</li><li><strong>A proper event journal.</strong> One row per outage with start time, end time and type: scheduled load shedding, fault or controlled test. An automatic detector flags voltage below 170 V for at least 10 seconds.</li><li><strong>Natural and controlled events kept separate.</strong> Switching a breaker off is perfect for testing sensing and alarm latency, but it creates sudden events with no natural precursor. It must never be used to “prove” the forecaster.</li></ul><p><strong>How I will evaluate on real data:</strong></p><ul><li>Time-based splits only, never shuffled.</li><li>Honest baselines: always-no, a time-of-day prior, and any published utility schedule. If the model cannot beat the time prior, that is a finding worth reporting.</li><li>Event-level metrics: how many outages were warned in time, the lead-time distribution, and false alarms per day.</li><li>A threshold chosen by cost (what a false alarm costs versus a missed outage), tuned on validation data only.</li><li>A fresh measurement of the gradual versus sudden share, because the simulator’s 65% is an assumption.</li><li>If the month produces too few natural events (fewer than about 20), I will say so and avoid strong forecasting claims.</li></ul><p><strong>Beyond the month:</strong></p><ul><li>Real power and power factor, plus harmonic analysis.</li><li>Multiple nodes and feeder-level correlation, with weather and utility-schedule features.</li><li>A compact model running on the ESP32 itself.</li><li>Alerts to a phone (Telegram or SMS), over-the-air firmware updates and Grafana dashboards.</li><li>Security: MQTT authentication and TLS, rotated tokens, and no anonymous broker.</li><li>An enclosure, a fused mains adapter and a proper PCB in place of the breadboard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sm01pt99cCB94nhluFXYWQ.png" /><figcaption>Roadmap</figcaption></figure><h3>Try it, stay safe, and say hello</h3><p>Everything is open source under the MIT licence: firmware, backend, dashboard, models, wiring guide and the roadmap above. You can run the full dashboard with a replay demo, with no hardware at all:</p><pre>git clone https://github.com/rafiul254/EdgeVolt.git &amp;&amp; cd EdgeVolt<br>python -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -r requirements.txt<br>uvicorn backend.main:app --port 8000<br>streamlit run dashboard/app.py</pre><p><strong>GitHub:</strong> <a href="https://github.com/rafiul254/EdgeVolt">rafiul254/EdgeVolt: Edge-Intelligent Load Shedding Prediction and Real-Time Monitoring System for Bangladesh Micro-Level Distribution Grids.</a></p><p><strong>A note on safety.</strong> This project touches 220–240 V mains. Never push bare wires into a multiplug or onto a breadboard. Keep every mains-side connection insulated, fused and enclosed, and keep the low-voltage electronics physically separate. Clamp the current sensor around one insulated conductor, and never cut or strip a live cable to do it. If you are unsure, ask a qualified electrician.</p><h3><strong>To close. </strong>The lights will keep going out. Our job as engineers is to make sure that next time, someone sees it coming, and to be exact about how well we can do that today.</h3><p><em>If you work on smart grids, edge AI or embedded systems, I would love your feedback: what would you test first on real data?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d09e4ea9191" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Not Every Chapter Is About Winning]]></title>
            <link>https://rafiulislam25.medium.com/not-every-chapter-is-about-winning-c1e63f1677ff?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e63f1677ff</guid>
            <category><![CDATA[students]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[mental-health]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 19:01:15 GMT</pubDate>
            <atom:updated>2026-10-15T19:01:15.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vm3TxnzHU-jjdJRNwngBkA.jpeg" /><figcaption>Failure??</figcaption></figure><p><em>On rejection, self-doubt, and choosing to keep going</em></p><p>Most of the time, when I post on social media, I share the good parts: the competitions I joined, the opportunities I got, the small milestones I’m proud of. Today I want to share the side of my life that rarely makes it to the timeline.</p><p>The last two to three months have been some of the hardest I’ve had.</p><h3>What those months looked like</h3><p>I participated in around 15 competitions. Some selected me. In others, I was out in the first round. A few I missed completely because they clashed with university exams and classes. Some came so close that I could almost touch them, but I couldn’t make them work.</p><p>I applied for jobs and internships, sat through interviews, and hoped for good news. Most of the time, it didn’t come. And when an opportunity did come, practical limits, like not being able to work remotely, made it hard to move forward.</p><p>At the same time, I’m trying to figure out my future. The job market feels uncertain. I dream of going abroad for higher studies, but visa complications and documentation challenges make that dream feel further away than I’d like. And on top of everything, I lost someone from my heart. Suddenly, even the things I used to enjoy felt a little different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*znzNpjhac9UmnD_Dj6IlPA.jpeg" /><figcaption>Real life difficulties</figcaption></figure><h3>The questions that follow</h3><p>When disappointments arrive from so many directions at once, you start questioning yourself.</p><p><em>Am I doing enough? Am I on the right path? What am I actually doing with my life? Will things ever get better?</em></p><p>Honestly, I don’t have all the answers. Some days I feel frustrated, lost, and exhausted from trying so hard without getting the results I hoped for. It feels like everyone else is moving forward while I’m standing still.</p><h3>What I’m slowly learning</h3><p>I’m not saying I’ve figured it out, but a few things are becoming clearer:</p><p><strong>1. Rejection is not a verdict on your worth.</strong> A “no” from a competition, a company, or a committee tells you about one decision on one day. It doesn’t define you.</p><p><strong>2. Effort and outcome are two different things.</strong> You can do everything right and still not get the result. Your responsibility is the effort. The outcome is not entirely in your control.</p><p><strong>3. Slow progress is still progress.</strong> Some chapters take longer than we planned. That doesn’t mean the story is over.</p><p><strong>4. Comparison lies.</strong> Everyone’s timeline looks perfect from the outside, because we mostly post our wins. I know, because I’ve done the same.</p><p>Just because things aren’t working out doesn’t mean I’m a failure. Maybe I haven’t achieved what I wanted yet. Maybe my plans will take longer than expected. But I’m still here. Still learning. Still trying.</p><h3>Where my faith comes in</h3><p>I believe in Allah, and that belief is what holds me steady when everything else feels uncertain.</p><p>I may not understand why certain things are happening right now. I may not know where this road leads. But I trust that Allah knows what I cannot see. So I make dua for patience to keep going, strength to handle what I can’t change, and wisdom to recognize the opportunities that are truly meant for me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuP00EWU3WOdo8bFWoTwJg.jpeg" /></figure><h3>If you’re going through a hard phase too</h3><p>Maybe you’re struggling with your career, failing competitions, getting rejected from jobs, losing someone you love, or watching your dreams get delayed. Maybe you just feel lost about your future.</p><p>It’s okay to feel tired. It’s okay to feel disappointed. You don’t have to pretend everything is fine.</p><p>Take a breath. Give yourself time. Learn from your mistakes, try again, and keep moving forward, even if your progress feels painfully slow. You don’t have to figure out your entire life today.</p><p>Do what you can. Give your best. Keep improving. Make dua, put your trust in Allah, and leave the outcome in His hands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmAqK8pKD9N18zXs5EiOsA.jpeg" /><figcaption>How to overcome your hard phase</figcaption></figure><h3>Why I’m sharing this</h3><p>I’m not sharing this because I’ve figured everything out. I’m sharing it because I’m still figuring it out. I don’t want to show only the version of me that wins. I want to be honest about the version that struggles, questions everything, and still chooses to believe.</p><p>Maybe one day, I’ll look back at this phase and understand why I had to go through it.</p><p>Until then, I’ll keep trying.</p><p><strong>Insha’Allah, better days will come. God knows best.</strong>🤍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZFW1cgwkywVHVczi2rRXg.jpeg" /><figcaption>Your better days will come, keep figuring out!</figcaption></figure><h3>Author:</h3><p><strong><em>Rafiul Islam</em></strong><em> is a B.Sc. IoT &amp; Robotics Engineering student at the University of Frontier Technology, Bangladesh.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e63f1677ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ClassPulse: I Built an AI-Power System That Detects If Students Are Sleeping in Class]]></title>
            <link>https://rafiulislam25.medium.com/classpulse-i-built-an-ai-power-system-that-detects-if-students-are-sleeping-in-class-6cba2f8d9c5c?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cba2f8d9c5c</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[yolov8]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 16:27:31 GMT</pubDate>
            <atom:updated>2026-09-09T16:27:31.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJgpC7ijvr0pRjiloBhrjg.jpeg" /><figcaption>ClassPulse</figcaption></figure><h4>How I combined YOLOv8 Pose Estimation, Flask, MQTT, and ESP32 to build a real-time classroom attention monitoring system — with no wearables, no student-side hardware, just a webcam.</h4><h3>The Problem Nobody Talks About</h3><p>Every teacher has experienced it. You’re mid-lecture, explaining a concept you’ve spent hours preparing, and you glance across the room — half the class is looking at their phones, one student is quietly sleeping in the back row, and two others are having a side conversation.</p><p>The hard truth: <strong>teachers have no scalable way to know when they’re losing the class.</strong></p><p>Eye contact helps, but it doesn’t scale. In a classroom of 40 students, you can’t monitor everyone simultaneously while teaching. And by the time you notice attention has dropped, ten minutes of valuable lecture time has already been lost.</p><p>This is the problem ClassPulse was built to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92GGofaEPj_skdvgi-xjpw.jpeg" /><figcaption>The problem that ClassPulse solves</figcaption></figure><h3>What Is ClassPulse?</h3><p>ClassPulse is a real-time AI-powered classroom attention monitoring system that uses a single webcam to detect student engagement — classifying each student as <strong>Attentive</strong>, <strong>Distracted</strong>, <strong>Sleeping</strong>, or <strong>Using a Phone</strong> — and delivers instant feedback to the teacher through a live web dashboard and an IoT hardware alert system on their desk.</p><p>No wearables. No student-side hardware. No special cameras. Just a laptop and a webcam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnvD-G1oCh8MyYlLV4pqdA.jpeg" /></figure><h3>System Architecture</h3><p>Before diving into the code, here’s the high-level picture of how everything connects:</p><pre>[Laptop Camera]<br>      │<br>      ▼<br>[Python Backend]<br>  ├── YOLOv8-pose  → 17 keypoints per student<br>  ├── YOLOv8n      → phone detection<br>  └── AttentionEngine → head pose + eye state → score 0–100<br>      │<br>      ├──► Flask Web Server<br>      │     ├── MJPEG stream  → live annotated video in browser<br>      │     ├── SSE endpoint  → real-time stats to dashboard<br>      │     └── SQLite        → session logs + report generation<br>      │<br>      └──► MQTT Broker (Mosquitto)<br>                │<br>                ▼<br>           ESP32 IoT Node<br>           ├── RGB LED  → colour based on attention %<br>           └── Buzzer   → tones for alerts</pre><p>The system has three distinct layers: the <strong>detection layer</strong> (Python + YOLO), the <strong>presentation layer</strong> (Flask + Chart.js dashboard), and the <strong>IoT feedback layer</strong> (MQTT + ESP32).</p><h3>The Core Problem: How Do You Measure “Attention”?</h3><p>This was the hardest design decision. Attention is inherently subjective and internal — you can’t directly measure whether someone is paying attention. But you <em>can</em> measure observable proxies:</p><ol><li><strong>Head orientation</strong> — Is the student facing the teacher/board?</li><li><strong>Eye state</strong> — Are their eyes open?</li><li><strong>Head movement</strong> — Are they looking sideways or down?</li><li><strong>Device use</strong> — Is there a phone in their hand?</li></ol><p>YOLOv8-pose gives us 17 body keypoints per detected person. The ones we care about most are the face keypoints:</p><pre>KP_NOSE      = 0<br>KP_LEFT_EYE  = 1<br>KP_RIGHT_EYE = 2<br>KP_LEFT_EAR  = 3<br>KP_RIGHT_EAR = 4</pre><p>Each keypoint has three values: (x, y, confidence). The confidence value — often overlooked — turns out to be crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6QZMkqPqigZGPjuUyhuuA.jpeg" /><figcaption>Attention Measure</figcaption></figure><h3>Head Pose Estimation from Keypoints</h3><p>Standard head pose estimation uses 3D facial landmarks, depth cameras, or complex PnP solvers. I wanted something that runs in real-time on a laptop CPU/GPU with just a 2D webcam feed.</p><p>The insight: when you face a camera directly, your nose sits roughly between your two eyes. When you turn your head, the nose shifts laterally relative to the eye midpoint. This geometric relationship gives us <strong>yaw</strong> (left-right rotation):</p><pre>def estimate_head_pose(kp):<br>    eye_mid  = (pt(LEFT_EYE) + pt(RIGHT_EYE)) / 2<br>    eye_span = np.linalg.norm(pt(LEFT_EYE) - pt(RIGHT_EYE))</pre><pre>    # Nose offset from eye midpoint → yaw angle<br>    horiz_offset = pt(NOSE)[0] - eye_mid[0]<br>    yaw = np.degrees(np.arctan2(horiz_offset, eye_span * 0.6))</pre><pre>    # Nose below eye midpoint → head dropped (pitch)<br>    vert_offset = pt(NOSE)[1] - eye_mid[1]<br>    pitch = np.degrees(np.arctan2(vert_offset, eye_span * 0.5))</pre><pre>    return yaw, pitch</pre><p>For <strong>pitch</strong> (up-down tilt): when a student drops their head to sleep, the nose moves below the eye midpoint. Measuring this vertical offset gives a reliable sleeping detection signal without any ML model training.</p><p>Edge cases handled:</p><ul><li><strong>Only ears visible, no face</strong> → head turned nearly 90°, yaw set to ±80°</li><li><strong>Shoulders visible, no face</strong> → completely bent forward/sleeping</li><li><strong>Single ear only</strong> → severe profile view, high yaw assigned</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Do7JGUE-lSlU-6MrQ_NM3A.jpeg" /><figcaption>Head pose</figcaption></figure><h3>Eye State — Without 6-Point EAR</h3><p>The classic Eye Aspect Ratio (EAR) algorithm uses 6 facial landmarks per eye to detect blinks and closed eyes. YOLOv8-pose only gives us the eye <em>center</em> point, not 6 landmarks.</p><p>The workaround: <strong>closed eyelids physically occlude the eye landmark</strong>, reducing its detection confidence. When a student’s eyes are open, the eye keypoint confidence is high. When closed, it drops relative to the nose confidence (which stays stable).</p><pre>def estimate_eye_state(kp):<br>    avg_eye_conf  = (kp[LEFT_EYE][2] + kp[RIGHT_EYE][2]) / 2<br>    nose_conf     = kp[NOSE][2]</pre><pre>    # Ratio drops when eyes close → eyelids occlude the landmark<br>    ratio = avg_eye_conf / max(nose_conf, 0.01)<br>    eyes_open = ratio &gt; 0.40<br>    return ratio, eyes_open</pre><p>This isn’t as precise as 6-point EAR, but it works reliably enough to catch prolonged eye closure (sleeping), which is what we care about. A rolling streak counter tracks consecutive closed-eye frames:</p><pre># After 8 consecutive frames of closed eyes → SLEEPING<br>if closed_eye_streak &gt;= EAR_CLOSED_FRAMES:<br>    score = min(score, 12)<br>    state = &#39;SLEEPING&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ML4WUnmpiq3m4M88ArYDw.jpeg" /><figcaption>Eye State Detection</figcaption></figure><h3>The Attention Score</h3><p>Everything combines into a 0–100 score:</p><pre>Face visible at all         → +25 pts<br>Yaw &lt; 25° (facing forward)  → +45 pts<br>Yaw &lt; 50° (slight turn)     → +20 pts<br>Yaw ≥ 50° (looking away)    →  +0 pts<br>Pitch &lt; -30° (head down)    → cap at 12<br>Eyes open                   → +20 pts<br>Eyes closed long             → cap at 12</pre><pre>Confidence scaling:<br>  avg_face_confidence maps [0.35 → 1.0] to [0.5 → 1.0]<br>  Dark/low-quality camera → score scaled down automatically</pre><pre>Phone detected nearby:<br>  Hard cap at 25, state forced to PHONE</pre><p>The confidence scaling was a critical fix. Without it, a dark camera or distant student would generate guessed keypoints at low confidence — and the algorithm would naively report high scores. Now, uncertainty in the detection is explicitly reflected in a lower attention score.</p><h3>The Real-Time Dashboard</h3><p>The dashboard is a Flask app with two key streaming mechanisms:</p><p><strong>MJPEG stream</strong> for the annotated video:</p><pre>@app.route(&#39;/video_feed&#39;)<br>def video_feed():<br>    return Response(<br>        detector.gen_frames(),<br>        mimetype=&#39;multipart/x-mixed-replace; boundary=frame&#39;<br>    )</pre><p><strong>Server-Sent Events (SSE)</strong> for live stats — chosen over WebSockets because SSE is unidirectional (server → client), simpler to implement with Flask, and perfectly suited for a dashboard that only needs to receive data:</p><pre>@app.route(&#39;/stream&#39;)<br>def stream():<br>    def event_gen():<br>        while True:<br>            data = detector.get_stats()<br>            yield f&#39;data: {json.dumps(data)}\n\n&#39;<br>            time.sleep(0.8)<br>    return Response(event_gen(), mimetype=&#39;text/event-stream&#39;)</pre><p>The frontend JavaScript listens to the SSE stream and updates Chart.js charts, student status rows, and the attention gauge — all without any page reload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUjUy5y7Oayc2gjUSkbLKA.jpeg" /><figcaption>Dashboard Cycle</figcaption></figure><h3>IoT Layer — ESP32 + RGB LED + Passive Buzzer</h3><p>The dashboard is useful for the teacher at their computer, but what about when they’re walking around the room? The ESP32 node on the teacher’s desk provides ambient feedback:</p><p>Attention % RGB LED Buzzer ≥ 70% Solid Green Silent 45–69% Blue slow blink Silent &lt; 45% Solid Red Warning beep Alert (danger) Purple flash ×4 Triple alarm</p><p>The ESP32 subscribes to two MQTT topics:</p><ul><li>classpulse/stats → updates the LED colour</li><li>classpulse/alert → triggers the alarm sequence</li></ul><p>One design decision worth noting: <strong>the ESP32 uses LEDC PWM</strong> (not the standard tone() function) because the tone() function conflicts with the ESP32Servo library when both are used simultaneously. LEDC channels are explicitly assigned to avoid this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xxEuGNOMzxxQabRcxg2YA.jpeg" /><figcaption>IoT Layer</figcaption></figure><h3>Persistent Tracking with YOLOv8</h3><p>One challenge with multi-person detection is maintaining consistent student IDs across frames. Without tracking, the same student might be labelled S1 in one frame and S3 in the next.</p><p>YOLOv8’s built-in tracker solves this:</p><pre>pose_results = pose_model.track(<br>    frame,<br>    persist=True,    # maintains IDs across frames<br>    verbose=False,<br>    device=&#39;0&#39;,      # GPU<br>)</pre><p>The persist=True flag tells the tracker to maintain a consistent ID for each detected person across the video stream. This also enables the eye-streak counter to work correctly — we need to know that the student who had closed eyes in the last 7 frames is the same person in the current frame.</p><h3>Results and Observations</h3><p>Testing the system on myself and a few friends, the detection worked reliably under these conditions:</p><ul><li><strong>Normal room lighting</strong> → accurate state detection</li><li><strong>Glasses</strong> → no significant impact on keypoint detection</li><li><strong>Turning 30° sideways</strong> → correctly classified as DISTRACTED</li><li><strong>Head fully dropped</strong> → reliably caught as SLEEPING within 1–2 seconds</li><li><strong>Phone held at desk level</strong> → YOLOv8n detected it ~80% of the time</li><li><strong>Dark room / laptop camera</strong> → confidence scaling kicked in, prevented false ATTENTIVE scores</li></ul><p>At ~1.5 FPS on CPU (shared GPU: ~8–12 FPS), the system is fast enough for a classroom monitoring use case where decisions are made over 5–10 second windows, not individual frames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbP0Ta9nmAGvwJk0H2wT6w.jpeg" /><figcaption>Result</figcaption></figure><h3>Key Takeaways</h3><p><strong>1. Confidence values are data, not noise.</strong> Most YOLO tutorials ignore keypoint confidence scores. Using them as a camera quality signal was the key insight that made the algorithm robust to poor lighting.</p><p><strong>2. Geometric approaches beat model training for constrained problems.</strong> Head pose from keypoint geometry — no training data, no additional model, works out of the box.</p><p><strong>3. SSE &gt; WebSockets for one-way dashboards.</strong> Simpler, Flask-native, no socket management needed.</p><p><strong>4. MQTT decouples the system cleanly.</strong> The Python backend doesn’t know or care about the ESP32. New IoT devices can subscribe to the same topics without changing the backend.</p><p><strong>5. Physical feedback matters.</strong> The LED + buzzer combination proved surprisingly useful in testing — glancing at a green LED tells you more faster than looking at a dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ln3M2-IKPnHgZvvUXytYLg.jpeg" /><figcaption>Key takeaways</figcaption></figure><h3>What’s Next</h3><ul><li>Multi-camera support for larger classrooms</li><li>Face recognition for named per-student reports</li><li>Engagement trend analysis over multiple sessions</li><li>Mobile app for teacher alerts</li></ul><h3>Source Code</h3><p>Full source code, wiring diagrams, and setup guide available on GitHub: <a href="http://rafiul254/ClassPulse">rafiul254/ClassPulse: Real-time classroom attention monitoring using YOLOv8 Pose + Flask + ESP32 IoT</a></p><h3>Author:</h3><p><em>Rafiul Islam is a B.Sc. IoT &amp; Robotics Engineering student at the University of Frontier Technology, Bangladesh, and currently student Researcher @ELITE ResearchLab. He creates IoT and AI project tutorials on YouTube at @PinToCloud_by Rafi.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cba2f8d9c5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Full-Stack IoT E-Commerce Platform from Scratch — Here’s Everything I Learned]]></title>
            <link>https://rafiulislam25.medium.com/i-built-a-full-stack-iot-e-commerce-platform-from-scratch-heres-everything-i-learned-4bade127302b?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bade127302b</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 18:20:10 GMT</pubDate>
            <atom:updated>2026-09-01T18:20:10.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVSC77Jx9rzJ4nTQpSp1_Q.jpeg" /><figcaption>TechMorph-IoT</figcaption></figure><h3>I Built a Full-Stack IoT E-Commerce Platform from Scratch — Here’s Everything I Learned</h3><p><em>From a blank folder to a live, deployed website with an AI chatbot — the real story of building TechMorph-IoT.</em></p><h3>The Idea</h3><p>As an IoT and Robotics Engineering student in Bangladesh, I have one constant frustration: finding authentic, quality components is a nightmare. Local shops have limited stock, pricing is inconsistent, and you never quite know if what you’re getting is genuine.</p><p>So I decided to build the solution myself.</p><p>TechMorph IoT is a full-stack e-commerce platform built specifically for the Bangladeshi maker and engineering community — a place to buy Arduino, ESP32, Raspberry Pi, sensors, and IoT kits with confidence. But what started as a simple CRUD app became one of the most technically challenging and rewarding projects I’ve ever worked on.</p><p>This is the honest story of how I built it — the architecture decisions, the bugs that kept me up at night, and the solutions I found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17wSbp5AxW2ouETBs8Vf_g.jpeg" /><figcaption>Structure of Techmorph-iot</figcaption></figure><h3>What I Built</h3><p>Before diving into the challenges, here’s what TechMorph IoT includes at launch:</p><p><strong>Frontend (Next.js 14)</strong></p><ul><li>Full product catalogue with filters, search and pagination</li><li>Cart and wishlist (localStorage-based — works without backend)</li><li>Multi-step checkout with bKash, Nagad and COD simulation</li><li>Google OAuth via NextAuth.js</li><li>Admin dashboard with order and product management</li><li>TechBot — an AI shopping assistant powered by Groq (Llama 3)</li><li>Dark/Light mode with CSS variable theming</li><li>Bangla/English language toggle</li><li>Fully responsive, mobile-first design</li></ul><p><strong>Backend (Node.js + Express + Prisma + PostgreSQL)</strong></p><ul><li>JWT-based authentication with bcrypt password hashing</li><li>Product, category, order, cart, coupon and newsletter APIs</li><li>Rate limiting and security middleware</li><li>Deployed on Render with Neon (serverless PostgreSQL)</li></ul><p><strong>Live at:</strong> <a href="https://techmorph-iot.vercel.app/">techmorph-iot.vercel.app</a></p><h3>The Tech Stack — And Why I Chose It</h3><p>I chose <strong>Next.js 14</strong> with the App Router for the frontend. Coming from a background in embedded systems and IoT, web development was already a stretch — but Next.js made it manageable. The App Router’s file-based routing, built-in API routes, and server-side rendering meant I could build a production-quality app without setting up a separate frontend server.</p><p><strong>TypeScript</strong> was non-negotiable. When you’re managing product types, order structures, user roles and API responses across a large codebase, having the compiler catch type mismatches saves hours.</p><p><strong>Tailwind CSS</strong> gave me the design velocity I needed. Combined with Framer Motion for animations, I built the cyberpunk aesthetic — dark backgrounds, neon purple and cyan accents, glassmorphism cards — entirely through utility classes.</p><p>For the backend, <strong>Express.js with Prisma</strong> was a deliberate choice. Prisma’s type-safe ORM and clean migration system meant I could iterate on the database schema quickly without worrying about raw SQL errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*zG5yrGHantBjSNp1fC82qQ.jpeg" /><figcaption>Pros &amp; Cons</figcaption></figure><h3>Challenge 1: Product Images — Three Weeks of Frustration</h3><p>This was the problem I spent the most time on, and the solution I’m most proud of.</p><p>I wanted real product images — Arduino boards, ESP32 modules, sensors — the kind you see on RoboticsBD or SparkFun. My first approach was Wikipedia Commons, which has excellent open-source photos of electronics.</p><p>The issue: Wikipedia returns <strong>HTTP 403</strong> for any server-side image request. Next.js image optimization proxies images through its own server, and Wikipedia blocks those requests entirely. I tried:</p><ul><li>Direct Wikipedia URLs — 403</li><li>wsrv.nl image proxy — worked briefly, then failed</li><li>SparkFun CDN — 403</li><li>Adafruit CDN — 403</li><li>Arduino official store CDN — 403</li><li>RoboticsBD — 403</li><li>Components101–403</li></ul><p>I wrote a Python script, a Node.js script, and tried every User-Agent and Referer header combination I could think of. All 403.</p><p>The key insight came after two weeks: the images load perfectly from a <strong>browser</strong>, because browsers make requests from personal IP addresses that Wikipedia doesn’t block. The problem was only with server-side requests.</p><p>I built a scripts/download-images.js that users run once from their own machine — it downloads Wikipedia images to public/products/ using browser-like headers. From a personal IP, Wikipedia doesn&#39;t block it.</p><p>But there was still a gap: when local images aren’t downloaded, the Unsplash fallback photos were completely wrong. A laptop for Arduino Nano. A cosmetics bottle for the HC-SR04 ultrasonic sensor. The fallback photo IDs I picked from memory were simply the wrong images.</p><p><strong>The permanent solution:</strong> I generated professional <strong>cyberpunk-styled SVG illustrations</strong> for all 15 products. Each SVG includes the product name, key specifications, category icon, and a matching neon glow color scheme. They load instantly, always look correct, require no external dependencies, and actually match the site’s aesthetic. No more random food images on electronics listings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dS1kFmPH9_bCDmkHXLhOUA.jpeg" /><figcaption>Challenge-1</figcaption></figure><h3>Challenge 2: Authentication That Kept Breaking</h3><p>The authentication system gave me more bugs per line of code than anything else.</p><p><strong>Problem 1: Users getting logged out randomly</strong></p><p>The refreshUser function in my AuthContext was calling the backend API to verify the JWT token on every page load. If the backend was temporarily down — which happens on Render&#39;s free tier when it goes to sleep — the function caught a network error and cleared the token from localStorage. Users would come back to a logged-out state for no apparent reason.</p><p>Fix: Only clear the token on HTTP 401 (Unauthorized). Network errors and 500s should keep the user logged in, restoring their session from localStorage while the backend wakes up.</p><pre>} catch (err) {<br>  const status = err?.response?.status;<br>  if (status === 401) {<br>    // Only clear on genuine unauthorized response<br>    localStorage.removeItem(&#39;token&#39;);<br>    setUser(null);<br>  }<br>  // Network errors — keep user logged in from localStorage<br>}</pre><p><strong>Problem 2: Demo credentials stopped working after logout</strong></p><p>My demo login flow tried the real backend API first, and if that returned a 401 (because the demo user exists in the database but something failed), it fell through to an error instead of the demo fallback.</p><p>Fix: Check demo credentials <strong>before</strong> the API call. If email and password match the hardcoded demo users, use them immediately. This guarantees demo credentials always work regardless of backend state.</p><p><strong>Problem 3: NextAuth.js SessionProvider in App Router</strong></p><p>Next.js 14’s App Router doesn’t allow SessionProvider (a client component) to be used directly in the root layout.tsx (a server component). The app crashed with a hydration error.</p><p>Fix: A thin wrapper component:</p><pre>// components/providers/SessionProviderWrapper.tsx<br>&#39;use client&#39;;<br>import { SessionProvider } from &#39;next-auth/react&#39;;<br>export function SessionProviderWrapper({ children }) {<br>  return &lt;SessionProvider&gt;{children}&lt;/SessionProvider&gt;;<br>}</pre><p>Simple, but took an embarrassingly long time to find.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uoa8tXTItjugMXlwIY0-dQ.jpeg" /><figcaption>Challenge-2</figcaption></figure><h3>Challenge 3: The Cart That Crashed the Backend</h3><p>Early in development, adding items to the cart was throwing a Prisma error:</p><pre>PrismaClientKnownRequestError: <br>Foreign key constraint failed on the field: CartItem_productId_fkey</pre><p>The issue: my mock product IDs were simple strings like &quot;1&quot;, &quot;2&quot;, &quot;3&quot;. But the database schema used UUIDs as primary keys. When the cart tried to create a CartItem with productId: &quot;1&quot;, Prisma rejected it because no product with that ID existed in the database.</p><p>I could have fixed this by using the seeded products’ real UUIDs — but that would couple the frontend too tightly to specific database records.</p><p><strong>Better fix:</strong> Move the cart entirely to localStorage. The cart doesn&#39;t need a database for its core function. Users can add, remove and update quantities without any API call. The backend cart only matters when we need server-side order history, which we handle separately at checkout.</p><p>This also made the app more resilient — the cart works even when the backend is offline.</p><h3>Challenge 4: Dark Mode That Didn’t Work</h3><p>Implementing the dark/light theme toggle seemed simple. Add a class to the &lt;html&gt; element, write CSS selectors. Done, right?</p><p>Not quite. The problem was that most of my components used hardcoded Tailwind classes like bg-[#0b0f19] and text-white. These don&#39;t respond to CSS class changes.</p><p>I tried several approaches:</p><ul><li>Tailwind’s dark: prefix — only works if you use the class-based strategy consistently everywhere</li><li>CSS-in-JS — too heavy for this project</li><li>Conditional class names — too verbose</li></ul><p><strong>The solution that actually worked:</strong> CSS custom properties injected via JavaScript.</p><pre>const applyTheme = (theme: &#39;dark&#39; | &#39;light&#39;) =&gt; {<br>  const root = document.documentElement;<br>  if (theme === &#39;dark&#39;) {<br>    root.style.setProperty(&#39;--bg-primary&#39;, &#39;#0b0f19&#39;);<br>    root.style.setProperty(&#39;--text-primary&#39;, &#39;#F1F5F9&#39;);<br>  } else {<br>    root.style.setProperty(&#39;--bg-primary&#39;, &#39;#f0f4ff&#39;);<br>    root.style.setProperty(&#39;--text-primary&#39;, &#39;#0f172a&#39;);<br>  }<br>};</pre><p>Then in components, use style={{ backgroundColor: &#39;var(--bg-primary)&#39; }} instead of hardcoded Tailwind colors. The theme toggle now injects CSS variables directly — instant, consistent, no flash.</p><h3>Challenge 5: The Sections.tsx Bug at Line 20</h3><p>This one was embarrassingly subtle.</p><pre>ReferenceError: s is not defined</pre><p>The error pointed to a stray s character — a single letter — sitting at the bottom of a context file after the export statement. It had been silently introduced during one of the many file edits. The TypeScript compiler didn&#39;t catch it because s could be interpreted in multiple ways. Next.js caught it at runtime.</p><p>The broader lesson: always check what’s at the very end of your files. Stray characters from copy-paste or editing are invisible in a busy code editor but fatal at runtime.</p><h3>Challenge 6: Blog Posts Giving 404 Errors</h3><p>I built an internal blog system with a blog/[slug]/page.tsx route. The problem: I was generating slugs from blog post titles, but the actual blog content lived on my Medium profile. Internal routes pointed to pages that didn&#39;t exist.</p><p>The fix was rethinking the architecture entirely. Instead of building a CMS, I linked each blog card directly to the Medium post URL. Clicking a blog post opens Medium in a new tab. No more 404s, and my Medium profile gets real traffic.</p><p>For the internal blog/[slug] route, I added a redirect page that auto-forwards to the Medium URL after 2 seconds — so any existing links still work gracefully.</p><h3>Challenge 7: Deploying Without Shell Access</h3><p>When deploying the backend to Render’s free tier, I discovered that the Shell feature (for running node prisma/seed.js) requires a paid plan.</p><p>The solution was surprisingly simple: run the seed from my local machine against the production database directly.</p><pre>DATABASE_URL=&quot;postgresql://user:pass@neon-host/neondb?sslmode=require&quot; node prisma/seed.js</pre><p>Neon (my PostgreSQL host) is completely separate from Render. My local machine can connect to Neon just as well as Render can. The seed ran in seconds.</p><h3>Challenge 8: Google OAuth on Production</h3><p>After deploying to Vercel, Google login showed:</p><pre>Error 400: redirect_uri_mismatch</pre><p>The OAuth client was configured with only http://localhost:3000/api/auth/callback/google. The production URL https://techmorph-iot.vercel.app/api/auth/callback/google wasn&#39;t registered.</p><p>Fix: Add the production URL to both <strong>Authorized JavaScript origins</strong> and <strong>Authorized redirect URIs</strong> in Google Cloud Console. Also update NEXTAUTH_URL in Vercel&#39;s environment variables to the production domain.</p><h3>Adding the AI Chatbot — TechBot</h3><p>Once the core platform was working, I wanted to add something that would make TechMorph IoT stand out as a portfolio project: an AI shopping assistant.</p><p>I built <strong>TechBot</strong> — a floating chat widget that knows everything about the store. It can answer questions about products and prices, recommend the right kit for a project, explain shipping and payment policies, and even help with basic IoT technical questions.</p><p>The system prompt gives the model full context about all 15 products with prices, shipping rules, coupon codes, payment methods and return policy. The model handles the rest — including auto-detecting whether to respond in English, Bengali, or Banglish based on how the user writes.</p><p>For the AI model, I chose <strong>Groq’s Llama 3</strong> over paid alternatives. Groq’s free tier is generous, the API is OpenAI-compatible (easy to integrate), and the response speed is genuinely impressive — faster than most paid models.</p><pre>const res = await fetch(&#39;https://api.groq.com/openai/v1/chat/completions&#39;, {<br>  method: &#39;POST&#39;,<br>  headers: { &#39;Authorization&#39;: `Bearer ${process.env.GROQ_API_KEY}` },<br>  body: JSON.stringify({<br>    model: &#39;llama3-8b-8192&#39;,<br>    messages: [{ role: &#39;system&#39;, content: SYSTEM_PROMPT }, ...conversationHistory],<br>    max_tokens: 500,<br>  }),<br>});</pre><h3>What I Learned</h3><p>Building TechMorph-IoT from scratch changed how I think about software development.</p><p><strong>External dependencies will always surprise you.</strong> Wikipedia blocks server-side image requests. Google OAuth needs production URLs registered. Render’s free tier sleeps. Neon needs SSL. Plan for every external service to behave unexpectedly.</p><p><strong>Build for offline first.</strong> Moving the cart to localStorage was the right architectural decision not just for the P2003 bug, but for resilience. Features that don’t need a server shouldn’t use one.</p><p><strong>Read the error message literally.</strong> The redirect_uri_mismatch error told me exactly what was wrong. The P2003 error told me exactly which constraint failed. Half of my debugging time was spent looking in the wrong place instead of reading what the error actually said.</p><p><strong>CSS variables beat utility class conditionals.</strong> For dynamic theming, injecting CSS custom properties via JavaScript is cleaner, more performant, and easier to maintain than managing conditional class strings.</p><p><strong>Done is better than perfect.</strong> This project has rough edges. The product images are SVG illustrations rather than real photos. The bKash payment is simulated. The blog redirects to Medium instead of hosting content internally. But it’s live, it works, and it demonstrates every skill I was trying to show — full-stack development, database design, authentication, API integration, deployment, and AI. Ship it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EICiqVMKfeL54RYliIlIQ.jpeg" /><figcaption>Learnings from techmorph-iot</figcaption></figure><h3>The Stack at a Glance</h3><p><strong>Frontend</strong><br>Next.js 14 · TypeScript · Tailwind CSS · Framer Motion</p><p><strong>Authentication</strong><br>NextAuth.js · JWT · bcryptjs</p><p><strong>AI Chatbot</strong><br>Groq API · Llama 3 · Free AI API</p><p><strong>Backend</strong><br>Node.js · Express.js</p><p><strong>Database</strong><br>PostgreSQL · Prisma ORM</p><p><strong>Hosting &amp; Deployment</strong><br>Vercel — Frontend<br>Render — Backend<br>Neon — Database</p><p><strong>Live:</strong> <a href="https://techmorph-iot.vercel.app/">TechMorph IoT — Connecting Ideas, Powering Innovation</a> <strong>Source code: </strong><a href="https://github.com/rafiul254/Techmorph-iot">rafiul254/Techmorph-iot: A full-stack IoT e-commerce platform built for the Bangladeshi maker and engineering community.</a></p><h3><strong>Author:</strong></h3><p><em>Rafiul Islam is an IoT &amp; Robotics Engineering student at the University of Frontier Technology, Bangladesh. He writes about IoT, embedded systems, Artificial Intelligence, full-stack development and the intersection of hardware and software.</em></p><p><a href="https://github.com/rafiul254"><em>GitHub</em></a><em> · </em><a href="https://linkedin.com/in/rafiul-islam-25sep92004"><em>LinkedIn</em></a><em> · </em><a href="https://youtube.com/@pintocloud"><em>YouTube @PinToCloud</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bade127302b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI-Powered Banglish Keyboard That Converts Text Instantly — Here’s How]]></title>
            <link>https://rafiulislam25.medium.com/i-built-an-ai-powered-banglish-keyboard-that-converts-text-instantly-heres-how-4d5eed0a1dae?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d5eed0a1dae</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 15:08:07 GMT</pubDate>
            <atom:updated>2026-07-28T15:08:07.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KB0jzLLJ_j3nck178A2og.jpeg" /><figcaption>Banglish Keyboard &amp; Converter</figcaption></figure><h3>I Built an AI-Powered Banglish Keyboard That Converts Text Instantly — Here’s How</h3><p><em>From a simple idea to a dual-platform tool powered by Groq AI</em></p><p><em>By Rafiul Islam — IoT &amp; Robotics Engineer</em></p><h3>The Problem Every Bangladeshi Faces</h3><p>If you’re Bangladeshi, you know exactly what Banglish is — even if you’ve never heard the word.</p><p>It’s how we type every single day:</p><blockquote>“ami aj office theke fire khub tired, ektu rest nibo. kal meeting ache, presentation ready korte hobe raat er moddhe”</blockquote><p>Bengali words written in English script, mixed with actual English words — that’s Banglish. We do it on WhatsApp, Messenger, Facebook, everywhere.</p><p>The problem? When you actually need proper বাংলা Unicode text — for formal writing, social media captions, or sending to someone who can’t read Banglish — you have to manually retype everything. Or use a translator that doesn’t understand our informal mixed language at all.</p><p>Google Translate fails at Banglish. Avro keyboard helps with typing বাংলা but doesn’t convert existing Banglish text. Nothing solved this specific problem.</p><p>So I built a tool that does exactly that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVKtLG83NliZZsKq71VbXQ.jpeg" /></figure><h3>What I Built</h3><p><strong>AI Banglish Keyboard</strong> is a dual-platform tool — a Windows desktop app and an Android app — that converts Banglish text to proper বাংলা Unicode or clean English, powered by Groq AI.</p><p><strong>Desktop version:</strong></p><ul><li>Runs silently in the system tray</li><li>Press Ctrl+Shift+B → any Banglish text in any app converts to বাংলা</li><li>Press Ctrl+Shift+E → converts to English</li><li>Works in WhatsApp Web, Chrome, Notepad, VS Code — literally anywhere</li></ul><p><strong>Android version:</strong></p><ul><li>Standalone converter app</li><li>Type Banglish → tap a button → instant conversion</li><li>Copy or share directly to WhatsApp, Messenger, anywhere</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQauL_CEBq_V9vQD3D90Rg.jpeg" /><figcaption>Keyboard Workflow</figcaption></figure><h3>Why Groq AI?</h3><p>I initially planned to use the Anthropic Claude API, but it requires a paid subscription. Then I discovered <strong>Groq</strong> — a free AI inference platform that offers blazing fast response times and a generous free tier.</p><p><strong>Groq free tier limits:</strong></p><ul><li>30 requests/minute</li><li>14,400 requests/day</li><li>Cost: $0 forever</li></ul><p>The model I chose: llama-3.3-70b-versatile — one of the best open-source LLMs available, running on Groq&#39;s custom LPU hardware for incredibly fast inference.</p><p>The key insight was that this isn’t a simple translation task. Banglish conversion requires:</p><ol><li><strong>Transliteration</strong> — Roman script → Bengali script</li><li><strong>Semantic understanding</strong> — understanding informal language and slang</li><li><strong>Context preservation</strong> — keeping the tone, emotion, and meaning intact</li></ol><p>Rule-based systems fail at this. LLMs excel at it.</p><h3>The System Prompt — Most Important Part</h3><p>The quality of conversion depends entirely on how well you instruct the AI. Here’s the system prompt I crafted after multiple iterations:</p><pre>You are a specialized Banglish text converter for Bangladeshi users.</pre><pre>DEFINITION:<br>Banglish = Bengali language written in English/Roman script,<br>mixed with actual English words.<br>This is exactly how Bangladeshis type in social media,<br>WhatsApp, Messenger, etc.</pre><pre>STRICT RULES:<br>1. Preserve original meaning, tone, and emotion exactly<br>2. Handle informal language, slang, and code-mixing naturally<br>3. For বাংলা target: Use proper Unicode Bengali script only<br>4. For English target: Write natural, grammatically correct English<br>5. Return ONLY the converted text — zero explanations, zero extra text</pre><p><strong>Example input:</strong></p><blockquote><em>“bhai ki korcho, urgent call daw ektu, onek important kotha ache”</em></blockquote><p><strong>→ বাংলা output:</strong></p><blockquote><em>“ভাই কী করছ, একটু আর্জেন্ট কল দাও, অনেক গুরুত্বপূর্ণ কথা আছে”</em></blockquote><p><strong>→ English output:</strong></p><blockquote><em>“Bro what are you doing, give me an urgent call, I have something very important to discuss”</em></blockquote><p>The LLM handles slang, informal contractions, and mixed language naturally — something no rule-based system could do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRHA17PSqI_6Zia7686DWw.jpeg" /><figcaption>Prompt structure</figcaption></figure><h3>Desktop App Architecture</h3><p>The desktop app is built in Python with a modular structure:</p><pre>desktop/<br>├── main.py                 ← Entry point<br>├── config/<br>│   └── settings.py        ← JSON config manager<br>├── core/<br>│   ├── ai_converter.py    ← Groq API integration<br>│   ├── hotkey_manager.py  ← Global hotkey listener<br>│   └── clipboard_manager.py<br>└── ui/<br>    ├── tray_icon.py       ← System tray icon<br>    └── settings_window.py ← Tkinter settings GUI</pre><h3>The Conversion Flow</h3><p>When a hotkey is pressed, this is what happens under the hood:</p><pre>Hotkey detected (Ctrl+Shift+B)<br>        ↓<br>Backup current clipboard content<br>        ↓<br>Simulate Ctrl+A → Ctrl+C (select all + copy)<br>        ↓<br>Read text from clipboard<br>        ↓<br>Send to Groq API with system prompt<br>        ↓<br>Receive converted text<br>        ↓<br>Put converted text in clipboard<br>        ↓<br>Simulate Ctrl+V (paste back)<br>        ↓<br>Restore original clipboard content</pre><p>The entire flow is invisible to the user — they just press a hotkey and see the text transform.</p><h3>Groq API Integration</h3><pre>from groq import Groq, AuthenticationError, RateLimitError</pre><pre>def convert_banglish(text: str, target: str = &quot;bangla&quot;) -&gt; str:<br>    config  = load_config()<br>    api_key = config.get(&quot;api_key&quot;, &quot;&quot;).strip()</pre><pre>    client = Groq(api_key=api_key)</pre><pre>    response = client.chat.completions.create(<br>        model=&quot;llama-3.3-70b-versatile&quot;,<br>        max_tokens=1000,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>            {&quot;role&quot;: &quot;user&quot;,   &quot;content&quot;: user_prompt},<br>        ]<br>    )</pre><pre>    return response.choices[0].message.content.strip()</pre><h3>System Tray Icon</h3><p>The tray icon is generated dynamically using Pillow — no external icon file needed:</p><pre>def _make_icon(color: str = &quot;#7c3aed&quot;) -&gt; Image.Image:<br>    img = Image.new(&quot;RGBA&quot;, (64, 64), (0, 0, 0, 0))<br>    d = ImageDraw.Draw(img)<br>    d.ellipse([2, 2, 62, 62], fill=color)<br>    return img</pre><h3>Packaging as EXE</h3><pre>pip install pyinstaller<br>pyinstaller --onefile --windowed --name=&quot;AI-Keyboard&quot; main.py</pre><p>This creates a standalone .exe that runs without Python installed — making distribution simple.</p><h3>Android App Architecture</h3><p>The Android app is a straightforward Kotlin app using the Groq REST API directly via OkHttp.</p><pre>app/src/main/<br>├── kotlin/com/rafiul/<br>│   ├── MainActivity.kt     ← Main converter UI<br>│   ├── SettingsActivity.kt ← API key settings<br>│   └── AIConverter.kt      ← Groq REST API client<br>└── res/<br>    ├── layout/<br>    │   ├── activity_main.xml<br>    │   └── activity_settings.xml<br>    └── values/themes.xml</pre><h3>API Call in Kotlin</h3><p>Groq is OpenAI-compatible, so the REST call is straightforward:</p><pre>val body = JSONObject().apply {<br>    put(&quot;model&quot;, &quot;llama-3.3-70b-versatile&quot;)<br>    put(&quot;max_tokens&quot;, 1000)<br>    put(&quot;messages&quot;, JSONArray().apply {<br>        put(JSONObject().apply {<br>            put(&quot;role&quot;, &quot;system&quot;)<br>            put(&quot;content&quot;, SYSTEM_PROMPT)<br>        })<br>        put(JSONObject().apply {<br>            put(&quot;role&quot;, &quot;user&quot;)<br>            put(&quot;content&quot;, userMsg)<br>        })<br>    })<br>}.toString()</pre><pre>val request = Request.Builder()<br>    .url(https://medium.com/&quot;https://api.groq.com/openai/v1/chat/completions&quot;)<br>    .addHeader(&quot;Authorization&quot;, &quot;Bearer $apiKey&quot;)<br>    .addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    .post(body.toRequestBody(&quot;application/json&quot;.toMediaType()))<br>    .build()</pre><h3>Async Handling with Coroutines</h3><pre>imeScope.launch {<br>    val result = aiConverter.convert(fullText, targetBangla)<br>    withContext(Dispatchers.Main) {<br>        result.onSuccess { converted -&gt;<br>            binding.tvOutput.text = converted<br>        }<br>        result.onFailure { error -&gt;<br>            binding.tvStatus.text = &quot;${error.message}&quot;<br>        }<br>    }<br>}</pre><p>All network calls happen on Dispatchers.IO — the main thread is never blocked.</p><h3>Key Technical Challenges</h3><h3>Challenge 1 — Clipboard Race Condition</h3><p>The biggest challenge on desktop was timing. When you simulate Ctrl+C, the clipboard isn&#39;t updated instantly — there&#39;s a small OS delay. My initial code was reading an empty clipboard.</p><p><strong>Fix:</strong> Added a small time.sleep(0.25) after the copy simulation to let the OS clipboard settle before reading.</p><pre>keyboard.press_and_release(&quot;ctrl+c&quot;)<br>time.sleep(0.25)  # Critical — wait for OS clipboard<br>text = pyperclip.paste()</pre><h3>Challenge 2 — Android Gradle Compatibility</h3><p>Setting up the Android project in IntelliJ IDEA (instead of Android Studio) caused multiple Gradle version conflicts. The root build.gradle.kts was applying the Kotlin plugin twice — once from the buildscript and once from the plugins block.</p><p><strong>Fix:</strong> Used the legacy buildscript approach instead of the version catalog:</p><pre>buildscript {<br>    dependencies {<br>        classpath(&quot;com.android.tools.build:gradle:8.1.0&quot;)<br>        classpath(&quot;org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.0&quot;)<br>    }<br>}</pre><h3>Challenge 3 — Banglish Prompt Engineering</h3><p>Early versions of the system prompt produced inconsistent results — sometimes returning explanations along with the converted text, sometimes adding quotation marks.</p><p><strong>Fix:</strong> Added explicit constraints to the system prompt:</p><pre>Return ONLY the converted text —<br>zero explanations, zero quotes, zero extra text</pre><p>This single addition made results 100% consistent.</p><h3>Distribution Strategy</h3><p>Platform Format Cost Windows GitHub Releases (.exe) Free Android GitHub Releases (.apk) Free Android F-Droid (planned) Free Android Amazon Appstore (planned) Free</p><p>No Play Store ($25 fee) needed — GitHub Releases handles direct APK distribution perfectly for an open-source project.</p><h3>What I Learned</h3><p><strong>1. Prompt engineering is a real skill</strong> The difference between a mediocre and excellent AI response is almost entirely in how you frame the prompt. Iterating on the system prompt was as important as writing the actual code.</p><p><strong>2. Free AI APIs are genuinely capable now</strong> Groq’s free tier with llama-3.3–70b-versatile handles Banglish conversion better than I expected. The days of needing expensive API access for quality AI are over.</p><p><strong>3. Cross-platform is harder than it looks</strong> Building the same feature for both Windows Python and Android Kotlin forced me to think about the same problem in two completely different paradigms. It made me a better engineer.</p><p><strong>4. Clipboard manipulation is trickier than expected</strong> OS-level clipboard operations have timing dependencies that aren’t obvious. Always add delays when simulating keyboard/clipboard operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcWm26PjQEbH2E7MO5v2zQ.jpeg" /></figure><h3>What’s Next</h3><ul><li><strong>Flutter version</strong> — single codebase for both Android and iOS</li><li><strong>Conversion history</strong> — save past conversions locally</li><li><strong>Auto-detect mode</strong> — automatically detect if text is Banglish and offer conversion</li><li><strong>Offline fallback</strong> — basic rule-based conversion when no internet available</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaUVF-PMTOrTRvDIpqR5Ew.jpeg" /></figure><h3>Try It Yourself</h3><p><strong>GitHub:</strong> <a href="https://github.com/rafiul254/AI_Power-Banglish-keyboard">github.com/rafiul254/AI_Power-Banglish-keyboard</a></p><p><strong>Get free Groq API key:</strong> <a href="https://console.groq.com/">console.groq.com</a></p><p>The entire project is open source under MIT license — fork it, improve it, make it your own.</p><h3><strong>Thanks for reading!</strong></h3><p><em>Follow me:</em> <a href="https://github.com/rafiul254"><em>GitHub</em></a><em> · </em><a href="https://www.linkedin.com/in/rafiul-islam-25sep92004"><em>LinkedIn</em></a><em> · </em><a href="https://www.youtube.com/@PinToCloud"><em>YouTube</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d5eed0a1dae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Bike Security System with GPS and GSM on ESP32 — Here’s What I Learned (Including What…]]></title>
            <link>https://rafiulislam25.medium.com/i-built-a-bike-security-system-with-gps-and-gsm-on-esp32-heres-what-i-learned-including-what-7992b614514f?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/7992b614514f</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[bike-security]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 18:38:29 GMT</pubDate>
            <atom:updated>2026-07-27T18:38:29.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*as3-bCX2Xl3j7SlnzpI3Pw.png" /><figcaption>MotoSentinel</figcaption></figure><h3>I Built a Bike Security System with GPS and GSM on ESP32 — Here’s What I Learned (Including What Failed)</h3><p><em>A hands-on journey through RFID authentication, GPS tracking, vibration detection, and the honest story of a GSM module that refused to cooperate.</em></p><blockquote><strong><em>TL;DR:</em></strong><em> I built a multi-layer motorcycle security system on ESP32 for my university microcontroller course. RFID, GPS, vibration detection, and relay immobilizer all worked perfectly. The GSM SMS alert module failed due to a power supply mistake. I’m documenting both the wins and the failure — because that’s how real embedded systems engineering works.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrLgHPeTPDi4GK916sp37A.jpeg" /><figcaption>Prototype</figcaption></figure><h3>The Problem I Was Trying to Solve</h3><p>Motorcycle theft is a serious issue in Bangladesh. Walk around any urban area and you’ll see bikes secured with nothing more than a basic mechanical lock — the kind that can be bypassed in under a minute with the right tools.</p><p>The statistics are grim. Thousands of motorcycles are stolen every year. Once a bike is gone, the owner has almost no way to track it down. There are no alerts, no location data, no remote kill switch.</p><p>I’m a Second-year IoT &amp; Robotics Engineering student at UFTB, and when our CSE-212 Microprocessor &amp; Microcontroller Sessional required a hands-on project, I knew exactly what I wanted to build.</p><p>Not a blinking LED. Not a temperature sensor dashboard.</p><p>A real security system. Something that could actually protect a vehicle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDMJouJx-JAeRwaE22TR9w.jpeg" /><figcaption>Why I built this project…?</figcaption></figure><h3>What I Set Out to Build</h3><p>My goal was a multi-layer security system with five core capabilities:</p><ol><li><strong>RFID Authentication</strong> — Only an authorized card can start the bike</li><li><strong>Vibration Detection</strong> — Any movement on a locked bike triggers an alarm</li><li><strong>GPS Tracking</strong> — Real-time location available on demand</li><li><strong>GSM Alerts</strong> — Instant SMS to the owner when theft is detected</li><li><strong>Engine Immobilizer</strong> — A relay cuts the ignition circuit when the system is locked</li></ol><p>I called it <strong>MotoSentinel v1. Now I try to build</strong> v2.0, but more on that later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nryzVCGuGka9ih2l0PRPHg.jpeg" /></figure><h3>Hardware Selection</h3><p>The first decision was the microcontroller. My course material covered both Arduino Mega and ESP32. After comparing the two, ESP32 was the obvious choice:</p><p>Spec Arduino Mega ESP32 Processor 16 MHz 240 MHz RAM 8 KB 520 KB WiFi None Built-in Bluetooth None Built-in Deep Sleep No Yes (10 µA) Cost Higher Lower</p><p>The ESP32 DevKit V1 (38-pin) gave me everything I needed and more.</p><h3>Full Component List</h3><p>Component Role Protocol ESP32 DevKit V1 Main controller — RFID RC522 Card authentication SPI GPS Neo-6M Location tracking UART2 SIM800L GSM Module SMS alerts UART1 SW-420 Vibration Sensor Theft detection GPIO Interrupt 5V Relay Module Engine immobilizer Digital OUT Active Buzzer Local alarm Digital OUT Logic Level Converter 3.3V ↔ 5V Passive LM2596 Buck Converter × 2 Voltage regulation Power 18650 Battery × 2 Power supply (7.4V) Power</p><p><strong>Total cost: approximately 2,500 BDT (~$23 USD)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmdetSnxhgNi8-B3CLe74A.jpeg" /><figcaption>Comparison between Arduino mega VS ESP32</figcaption></figure><h3>System Architecture</h3><h3>The State Machine</h3><p>The core of the software is a simple three-state machine:</p><pre>STATE_LOCKED ←──────────────────── Auth RFID scan<br>     │                                    │<br>     │ Auth RFID scan              STATE_UNLOCKED<br>     │                                    │<br>     ▼                                    │<br>STATE_ALARM ◄── Vibration detected        │<br>     │                             Auth RFID scan<br>     └──────────── Auth RFID scan ────────┘</pre><ul><li><strong>STATE_LOCKED</strong>: Relay open (ignition cut), vibration sensor armed</li><li><strong>STATE_UNLOCKED</strong>: Relay closed (ignition connected), sensors passive</li><li><strong>STATE_ALARM</strong>: Buzzer active, SMS sent, relay open (emergency lock)</li></ul><p>This design means the bike physically cannot start without the authorized RFID card, and any unauthorized movement triggers an immediate response.</p><h3>Communication Protocols in Use</h3><p>This project ended up being a practical demonstration of three different communication protocols running simultaneously on one microcontroller:</p><p><strong>SPI (Serial Peripheral Interface)</strong> — for the RFID RC522 reader. Four-wire, full-duplex, fast. I used GPIO 5 (CS), 4 (RST), 18 (CLK), 23 (MOSI), and 19 (MISO).</p><p><strong>UART (Universal Asynchronous Receiver-Transmitter)</strong> — for both GPS and GSM, on two separate hardware UART ports. GPS on UART2 (GPIO 16/17), GSM on UART1 (GPIO 13/14), both at 9600 baud.</p><p><strong>GPIO Interrupt</strong> — for the vibration sensor. Instead of polling the sensor in the main loop (which would cause delays and missed detections), I attached an external interrupt to GPIO 25 with a FALLING edge trigger. The ISR sets a flag, and the main loop handles the response.</p><pre>void IRAM_ATTR vibrationISR() {<br>  vibrationDetected = true;<br>}</pre><pre>// In setup():<br>attachInterrupt(digitalPinToInterrupt(VIBRATION), vibrationISR, FALLING);</pre><p>The IRAM_ATTR attribute is important on ESP32 — it places the ISR in IRAM (instruction RAM) so it executes even when flash cache is busy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBPAot2XY4l6Zq-dkWBeiQ.jpeg" /><figcaption>System Architecture</figcaption></figure><h3>Pin Connections</h3><h3>ESP32 Pin Assignment</h3><pre>GPIO 4  → RFID RST<br>GPIO 5  → RFID CS (SDA)<br>GPIO 13 → GSM RX (UART1) via LLC<br>GPIO 14 → GSM TX (UART1) via LLC<br>GPIO 16 → GPS TX (UART2 RX) via LLC<br>GPIO 17 → GPS RX (UART2 TX) via LLC<br>GPIO 18 → SPI CLK (RFID)<br>GPIO 19 → SPI MISO (RFID)<br>GPIO 23 → SPI MOSI (RFID)<br>GPIO 25 → SW-420 DO (Interrupt)<br>GPIO 26 → Relay IN<br>GPIO 27 → Buzzer (+)<br>5V pin  → Buck Converter #1 output<br>3.3V    → RFID VCC, Sensor VCC, LLC LV<br>GND     → All components (common ground)</pre><h3>Power Supply Design</h3><p>One of the trickier parts of this build was power. The 18650 batteries in series give 7.4V, but different components need different voltages:</p><ul><li><strong>ESP32</strong>: 5V input (regulated to 3.3V internally)</li><li><strong>GPS</strong>: 5V</li><li><strong>Relay</strong>: 5V</li><li><strong>RFID</strong>: 3.3V</li><li><strong>SIM800L</strong>: 4V (this one is critical — more on this later)</li></ul><p>I used two LM2596 buck converters:</p><ul><li><strong>Buck #1</strong>: 7.4V → 5V (for ESP32, GPS, Relay)</li><li><strong>Buck #2</strong>: 7.4V → 4V (dedicated for SIM800L)</li></ul><p>The ESP32’s onboard AMS1117 regulator handles the 5V → 3.3V conversion for the 3.3V components.</p><h3>What Worked Beautifully</h3><h3>RFID Authentication</h3><p>The RC522 reader connected directly to ESP32’s SPI bus at 3.3V — no logic level converter needed since both operate at the same voltage. The first time I scanned a card and saw the UID appear in Serial Monitor, I genuinely felt like a hacker.</p><p>The system stores the authorized UID in ESP32’s flash memory using the Preferences API, so the registration survives power cycles:</p><pre>void saveAuthorizedUID(String uid) {<br>  prefs.begin(&quot;bikeapp&quot;, false);<br>  prefs.putString(&quot;uid&quot;, uid);<br>  prefs.end();<br>}</pre><p><strong>Registration flow</strong>: First card scan on a fresh system automatically registers that card as authorized and sends a confirmation SMS (when GSM is working). Every subsequent scan of the same card toggles lock/unlock. Any unknown card triggers the alarm.</p><h3>GPS Tracking</h3><p>The Neo-6M module was surprisingly satisfying to work with. After taking the setup outdoors and waiting about three minutes for a cold start satellite fix, the coordinates started flowing in with four satellites locked.</p><p>Using the TinyGPS++ library, parsing NMEA sentences becomes straightforward:</p><pre>void updateGPS() {<br>  unsigned long start = millis();<br>  while (millis() - start &lt; 300) {<br>    while (Serial2.available() &gt; 0) {<br>      gps.encode(Serial2.read());<br>    }<br>  }<br>  if (gps.location.isValid()) {<br>    currentLat = gps.location.lat();<br>    currentLng = gps.location.lng();<br>    gpsFixed   = true;<br>  }<br>}</pre><p>The location string I format for SMS includes a direct Google Maps link:</p><pre>📍 Location:<br>Lat: 23.810331<br>Lng: 90.412521<br>Sats: 6<br>Maps: maps.google.com?q=23.810331,90.412521</pre><p><strong>One important note:</strong> GPS does not work indoors. For testing and demos, I took the unit outside. This is not a bug — it’s physics.</p><h3>Vibration Detection</h3><p>The SW-420 sensor with interrupt-driven detection was one of my favorite parts of this build. The response is genuinely fast — tap the chassis and the alarm triggers almost instantly.</p><p>The potentiometer on the sensor module lets you tune sensitivity. For the demo, I set it fairly sensitive. For a real deployment, you’d tune it to ignore minor vibrations (wind, passing trucks) and only trigger on the kind of sharp movement that indicates someone grabbing the bike.</p><p>The debounce logic prevents the alarm from re-triggering repeatedly:</p><pre>if (now - lastVibrationTime &lt; VIB_DEBOUNCE_MS) return;<br>lastVibrationTime = now;</pre><h3>Engine Immobilizer (Relay)</h3><p>The relay module provides a satisfying physical click when it switches. In the demo, I connected an LED across the COM and NC terminals to represent the ignition circuit.</p><ul><li><strong>Locked state</strong>: Relay open → LED off → bike cannot start</li><li><strong>Unlocked state</strong>: Relay closed → LED on → bike can start</li></ul><p>In a real installation, the relay would be wired in series with the motorcycle’s ignition circuit. The implementation is straightforward, but the concept is powerful — no RFID card, no ignition.</p><h3>What Failed — and Why</h3><p>Here is where I’m going to be completely honest, because I think this is the most valuable part of the article.</p><h3>The SIM800L GSM Problem</h3><p>The SIM800L module never reliably sent SMS messages. After extensive debugging, I identified the root cause:</p><p><strong>The SIM800L requires up to 2A of peak current during network registration and transmission.</strong> My setup had two problems:</p><ol><li>The capacitor I used at the SIM800L’s power pins was <strong>220µF</strong> — the recommended minimum is <strong>1000µF</strong>, positioned as close as possible to the VCC and GND pins.</li><li>The LM2596 buck converter, while rated for 2A continuous, struggled to supply the instantaneous 2A current spike the module demands during transmission. Voltage sag during the spike caused the module to crash and restart.</li><li>The symptoms were classic: the SIM800L LED would blink normally (indicating network registration), but the moment it attempted to send an SMS, the voltage would drop and the module would reset.</li></ol><p><strong>What I would do differently:</strong></p><ul><li>Use a 1000µF+ low-ESR capacitor directly at the module’s power pins</li><li>Use a higher-rated power supply or a dedicated capacitor bank</li><li>Consider switching to a more power-efficient GSM module like the A6 or A7</li></ul><p>The honest lesson here is that power supply design is often the hardest part of embedded systems work. The digital logic is well-documented. Power behavior under load is where projects succeed or fail.</p><h3>Serial Monitor Debugging</h3><p>One feature I’m genuinely proud of is the Serial Monitor debug interface. During development and demo, typing single characters triggers specific actions:</p><pre>d → Print full system status<br>l → Force lock<br>u → Force unlock<br>a → Trigger test alarm<br>s → Send test SMS<br>g → Read and print GPS coordinates<br>c → Clear registered RFID card</pre><p>This made live demonstrations much cleaner. Instead of physically scanning cards and shaking the chassis repeatedly, I could walk a viewer through the state machine in under a minute.</p><h3>Key Learnings</h3><p><strong>1. Power supply design is non-negotiable.</strong> Every component’s peak current requirements must be accounted for — not just idle current. The SIM800L’s 2A spike is the most common point of failure in GSM projects, and it caught me too.</p><p><strong>2. External interrupts over polling.</strong> Using a hardware interrupt for the vibration sensor gave near-instant response. Polling in the main loop would have introduced latency and potentially missed fast-touch events.</p><p><strong>3. Test each module independently first.</strong> Before integrating everything, I tested RFID, GPS, and GSM as separate units. This made it much easier to isolate the power issue with the SIM800L later.</p><p><strong>4. Document as you build.</strong> Writing this article forced me to articulate things I had only intuited during the build. If you’re working on a project, keep notes — not just for others, but for yourself in three months.</p><h3>What’s Coming in Version 2.0</h3><p>The GSM failure was a significant lesson, but it also opened the door to a better architecture. In v2.0, I’m replacing the SIM800L entirely with:</p><ul><li><strong>WiFi + Telegram Bot API</strong> — free, reliable, works anywhere there’s internet. No SIM card, no monthly cost.</li><li><strong>1.8&quot; TFT ST7735 display</strong> — live status on the device itself</li><li><strong>Deep Sleep mode</strong> — 10× battery life improvement</li><li><strong>Single buck converter</strong> — simpler power supply, fewer failure points</li></ul><p>The core security logic (RFID, GPS, vibration, relay) stays exactly the same. The communication layer gets a complete overhaul.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54-bRCLf5iJzY63suLjT_A.jpeg" /><figcaption>Version 2 plan</figcaption></figure><h3>Conclusion</h3><p>Building <strong>MotoSentinel v1.0 </strong>was one of the most educational experiences of my Second year of engineering. I learned more from the GSM failure than from everything that worked correctly.</p><p>The system demonstrates four communication protocols running simultaneously on a single microcontroller, interrupt-driven real-time response, persistent storage across power cycles, and a clean state machine architecture.</p><p>The GSM module didn’t work. That’s the honest truth. But I know exactly why, I know how to fix it, and v2.0 will be better because of that failure.</p><p>If you’re a student working on embedded systems and everything is going smoothly — you’re probably not pushing hard enough. The hard problems are where the learning happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAV9GVKSPJrgcE0i7DL_Jw.jpeg" /><figcaption>From Smartguard bd to MotoSentinel</figcaption></figure><h3>Resources</h3><ul><li><strong>GitHub Repository</strong>: <a href="https://github.com/rafiul254/MotoSentinel_A-Bike-Security-System">rafiul254/MotoSentinel_A-Bike-Security-System: An intelligent multi-layer Bike security system built on ESP32 + RFID Authentication + GPS Tracking + GSM module + WiFi/Telegram Alerts + TFT Display</a></li><li><strong>ESP32 Datasheet</strong>: espressif.com/en/products/socs/esp32</li><li><strong>MFRC522 Library</strong>: github.com/miguelbalboa/rfid</li><li><strong>TinyGPS++ Library</strong>: github.com/mikalhart/TinyGPSPlus</li><li><strong>SIM800L Power Issue</strong>: A common embedded systems debugging topic — search “SIM800L brownout”</li></ul><p><em>Thanks for reading! If you’re working on a similar project or have questions about any part of the build, drop a comment below. I read everything.</em></p><p><em>Follow me for v2.0 — coming soon with WiFi, Telegram, and a proper display.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7992b614514f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypt_AccessIQ: Building a Full-Stack IoT Access Control System with ESP32, Firebase, and React]]></title>
            <link>https://rafiulislam25.medium.com/crypt-accessiq-building-a-full-stack-iot-access-control-system-with-esp32-firebase-and-react-09d68e6e8618?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/09d68e6e8618</guid>
            <category><![CDATA[rfid]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 08:05:57 GMT</pubDate>
            <atom:updated>2026-06-08T08:05:57.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6mpFbeSssVN3A5eK9AehQ.jpeg" /><figcaption>IoT Access Control System</figcaption></figure><p><em>A complete technical deep-dive — from hardware wiring to cloud dashboard — including every mistake I made along the way.</em></p><h3>Introduction</h3><p>What starts as “I’ll just wire up an RFID reader” can quickly become a multi-day journey through SPI bus conflicts, display register overrides, and clone chip quirks. This article documents exactly how I built <strong>Crypt_AccessIQ</strong> — a production-grade IoT access control system — as a B.Sc. student in IoT &amp; Robotics Engineering.</p><p>By the end of this article, you’ll know how to build a system that:</p><ul><li>Scans RFID cards and grants or denies access in real-time</li><li>Tracks attendance with entry/exit timestamps and duration</li><li>Enforces time-based access schedules per user</li><li>Triggers security alarms on repeated failed attempts</li><li>Syncs all data to Firebase Realtime Database</li><li>Displays live logs and analytics on a React dashboard</li></ul><h3>System Architecture</h3><pre>RFID Card<br>    ↓<br>RC522 Reader (SPI)<br>    ↓<br>ESP32 DevKit V1<br>    ├── TFT 1.8&quot; Display (VSPI)  → Local visual feedback<br>    ├── Active Buzzer             → Audio feedback<br>    └── Firebase Realtime DB     → Cloud sync (WiFi)<br>                                        ↓<br>                                 React Dashboard<br>                           (Live logs, Attendance,<br>                            Analytics, Admin Panel,<br>                            Security Monitor</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B34zoChRVs47hnCxewUT8g.jpeg" /><figcaption>System Architecture</figcaption></figure><h3>Hardware</h3><h3>Components</h3><p>ESP32 DevKit V1 240MHz (WiFi + BT; Main controller) , RC522 RFID Module (13.56 MHz, MIFARE Card reader) , 1.8&quot; TFT LCD (ILI9341, 240×320 Local display), Active Buzzer 5V (Audio feedback), RFID Cards / Key fobs MIFARE Classic 1K Access credentials</p><p><strong>Total cost:</strong> ~৳500–700 BDT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*MYrW3EILoZ_u7zmQK3XjmQ.jpeg" /><figcaption>Full hardware setup</figcaption></figure><h3>Wiring</h3><h4>RC522 → ESP32<br>VCC ──────────────── 3.3V<br>GND ────────────────GND<br>SDA / SS ───────────────GPIO 21 (Chip Select)<br>RST ──────────────── GPIO 22 (Reset)<br>MOSI ───────────────GPIO 23 (SPI Data Out)<br>MISO ────────────────GPIO 19 (SPI Data In)<br>SCK ────────────────GPIO 18 (SPI Clock)<br>IRQ ── not connected</h4><h4>TFT LCD → ESP32<br>VCC ────────3.3V (check your module — some accept 5V)<br>GND ───────GND<br>CS ───── GPIO 15 (TFT Chip Select)<br>DC / RS ────GPIO 2 (Data / Command select)<br>RST ─────GPIO 4 (Reset)<br>MOSI / SDA ─── GPIO 23 (shared with RC522)<br>SCK / CLK ─── GPIO 18 (shared with RC522)<br>MISO ──── GPIO 19 (shared with RC522)</h4><h4>Buzzer → ESP32<br>+ (positive) ──────────────── GPIO 32<br>− (negative) ──────────────── GND</h4><h3>Software Architecture</h3><h3>ESP32 Firmware (PlatformIO + C++)</h3><pre>esp32_project/<br>├── platformio.ini<br>├── include/<br>│   ├── config.h       ← WiFi, Firebase keys, pin defs<br>│   └── user_cache.h   ← User struct, Firebase cache<br>└── src/<br>    └── main.cpp       ← Main firmware</pre><p><strong>Libraries used:</strong></p><ul><li>miguelbalboa/MFRC522 @ 1.4.10</li><li>mobizt/Firebase-ESP-Client</li><li>bodmer/TFT_eSPI</li><li>bblanchon/ArduinoJson</li><li>arduino-libraries/NTPClient</li></ul><h3>React Dashboard</h3><pre>Dashboard/<br>└── src/<br>    ├── App.js           ← Tab navigation<br>    ├── firebase.js      ← Firebase config + helpers<br>    └── components/<br>        ├── Overview.jsx     ← Live log + stats<br>        ├── Attendance.jsx   ← Daily records<br>        ├── Analytics.jsx    ← Charts (Recharts)<br>        ├── AdminPanel.jsx   ← User CRUD<br>        └── Security.jsx     ← Alarm + wrong attempts</pre><h3>Firebase Data Structure</h3><pre>rfid/<br>├── latest/<br>│   ├── uid: &quot;A3:B2:C1:D0&quot;<br>│   ├── name: &quot;Rahim Ahmed&quot;<br>│   ├── status: &quot;GRANTED&quot;<br>│   └── time: &quot;09:15:30&quot;<br>│<br>├── logs/<br>│   ├── 0/ → { uid, name, role, status, reason, time, date }<br>│   ├── 1/ → { ... }<br>│   └── ...<br>│<br>├── users/<br>│   └── A3B2C1D0/ → { name, role, active, startHour, endHour, days[] }<br>│<br>├── attendance/<br>│   └── 2025-01-15/<br>│       └── A3B2C1D0/ → { entry, exit, duration, status }<br>│<br>└── security/<br>    ├── wrongAttempts: 2<br>    ├── alarmActive: false<br>    └── lastDeniedUID: &quot;FF:EE:DD:CC&quot;</pre><h3>Key Code Highlights</h3><h3>1. Correct SPI Initialization Order</h3><p>The most critical fix in the entire project. TFT and RC522 share the same VSPI bus. The order matters enormously.</p><pre>void setup() {<br>    // Step 1: Hold ALL CS pins HIGH before anything touches SPI<br>    pinMode(PIN_SD_CS,   OUTPUT); digitalWrite(PIN_SD_CS,   HIGH);<br>    pinMode(PIN_RFID_SS, OUTPUT); digitalWrite(PIN_RFID_SS, HIGH);</pre><pre>    // Step 2: RC522 FIRST — PCD_Init() calls SPI.begin() internally<br>    rfid.PCD_Init();<br>    delay(200);</pre><pre>    // Step 3: TFT after RC522<br>    tft.init();<br>    tft.setRotation(0);</pre><pre>    // Step 4: MADCTL override — fixes horizontal mirror on clone modules<br>    tft.startWrite();<br>    tft.writecommand(0x36);  // MADCTL register<br>    tft.writedata(0x08);     // BGR=1, no axis flips<br>    tft.endWrite();<br>}</pre><h3>2. Clone-Compatible MFRC522 Constructor</h3><p>Many RC522 modules sold today are clones. They return 0x00 on the VersionReg instead of 0x91/0x92, but still work for card scanning. Using 4MHz SPI improves compatibility:</p><pre>MFRC522 rfid(PIN_RFID_SS, PIN_RFID_RST, SPI,<br>             SPISettings(4000000, MSBFIRST, SPI_MODE0));</pre><h3>3. Attendance Toggle Logic</h3><p>First scan of the day = Entry. Second scan = Exit. Third scan = new Entry cycle.</p><pre>void updateAttendance(const String&amp; uid, const String&amp; name, const String&amp; role) {<br>    String path = &quot;/rfid/attendance/&quot; + getDateStr() + &quot;/&quot; + uidToKey(uid);<br>    String entryTime = &quot;&quot;, exitTime = &quot;&quot;;</pre><pre>    // Read existing records<br>    if (Firebase.RTDB.getString(&amp;fbdo2, path + &quot;/entry&quot;))<br>        entryTime = fbdo2.stringData();<br>    if (Firebase.RTDB.getString(&amp;fbdo2, path + &quot;/exit&quot;))<br>        exitTime = fbdo2.stringData();</pre><pre>    if (entryTime.length() == 0) {<br>        // First scan → ENTRY<br>        Firebase.RTDB.setString(&amp;fbdo, path + &quot;/entry&quot;, getTimeStr());<br>        Firebase.RTDB.setString(&amp;fbdo, path + &quot;/status&quot;, &quot;In&quot;);</pre><pre>    } else if (exitTime.length() == 0) {<br>        // Second scan → EXIT + calculate duration<br>        Firebase.RTDB.setString(&amp;fbdo, path + &quot;/exit&quot;, getTimeStr());<br>        // Duration calculation...<br>        Firebase.RTDB.setString(&amp;fbdo, path + &quot;/status&quot;, &quot;Out&quot;);</pre><pre>    } else {<br>        // Both exist → new cycle<br>        Firebase.RTDB.setString(&amp;fbdo, path + &quot;/entry&quot;, getTimeStr());<br>        Firebase.RTDB.setString(&amp;fbdo, path + &quot;/exit&quot;, &quot;&quot;);<br>    }<br>}</pre><h3>4. Time-Based Access Check</h3><pre>bool checkTimeAccess(const User&amp; u) {<br>    if (!wifiOK) return true;  // Offline = bypass time check<br>    if (!u.days[getDayOfWeek()]) return false;  // Day check</pre><pre>    int cur   = timeClient.getHours() * 60 + timeClient.getMinutes();<br>    int start = u.startHour * 60 + u.startMin;<br>    int end   = u.endHour   * 60 + u.endMin;<br>    return (cur &gt;= start &amp;&amp; cur &lt;= end);<br>}</pre><h3>5. React Real-Time Listener</h3><pre>useEffect(() =&gt; {<br>    const logsRef = ref(db, &quot;/rfid/logs&quot;);<br>    const unsub = onValue(logsRef, (snapshot) =&gt; {<br>        const data = snapshot.val();<br>        if (!data) return;<br>        const arr = Object.entries(data)<br>            .map(([k, v]) =&gt; ({ _key: k, ...v }))<br>            .sort((a, b) =&gt; Number(b._key) - Number(a._key));<br>        setLogs(arr);<br>    });<br>    return () =&gt; unsub();<br>}, []);</pre><h3>The 5 Biggest Mistakes (And Fixes)</h3><h3>Mistake 1: Using GPIO5 for RC522 SDA</h3><p><strong>Problem:</strong> ESP32’s GPIO5 is a strapping pin. It must be HIGH during boot. Connecting RC522 SDA here pulls it LOW on card scan, causing boot issues and SPI failures. RC522 returned 0xFF (no response).</p><p><strong>Fix:</strong> Move SDA wire to GPIO21. 0xFF → 0x00 (at least the chip responds now).</p><h3>Mistake 2: Calling SPI.begin() After tft.init()</h3><p><strong>Problem:</strong> Both TFT_eSPI and MFRC522 internally call SPI.begin(). When called in the wrong order, ESP32&#39;s APB callback gets registered twice (addApbChangeCallback(): duplicate), and the SPI bus enters an inconsistent state. RC522 returns 0x00 — MISO stuck LOW.</p><p><strong>Fix:</strong> Let rfid.PCD_Init() call SPI.begin() first (internally). Don&#39;t add an explicit SPI.begin() yourself. Initialize TFT after RC522.</p><h3>Mistake 3: TFT Module’s SD Card Floating CS</h3><p><strong>Problem:</strong> The 2.4&quot; TFT module has an onboard SD card reader sharing the same MISO line (GPIO19). With SD_CS floating (unconnected), the SD card chip was occasionally asserting MISO LOW — interfering with RC522 reads.</p><p><strong>Fix:</strong> Connect SD_CS pin on TFT module to GPIO27. In code:</p><pre>pinMode(PIN_SD_CS, OUTPUT);<br>digitalWrite(PIN_SD_CS, HIGH);</pre><h3>Mistake 4: Wrong MADCTL for Display</h3><p><strong>Problem:</strong> tft.setRotation(0) should give normal portrait mode. But on this particular ILI9341 clone module, it renders text horizontally mirrored.</p><p><strong>Fix:</strong> Override MADCTL register directly after tft.init():</p><pre>tft.startWrite();<br>tft.writecommand(0x36);  // MADCTL<br>tft.writedata(0x08);     // BGR only, no axis flips<br>tft.endWrite();</pre><h3>Mistake 5: Default 20MHz SPI for Clone RC522</h3><p><strong>Problem:</strong> SPI_CLOCK_DIV4 on ESP32 = 80MHz/4 = 20MHz. Most clone RC522 chips (which return 0x00 on VersionReg) don&#39;t reliably communicate at 20MHz.</p><p><strong>Fix:</strong> Pass explicit SPISettings(4000000, MSBFIRST, SPI_MODE0) (4MHz) to the MFRC522 constructor.</p><h3>React Dashboard Features</h3><h3>Overview Tab</h3><p>Live access log with filter (ALL / GRANTED / DENIED), real-time stats cards, grant rate progress bar, and latest scan from Firebase /rfid/latest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xK6QRwQofOsTT5yvqHTg3g.png" /><figcaption>Overview</figcaption></figure><h3>Attendance Tab</h3><p>Date picker, daily attendance table with entry/exit/duration, in-progress indicator for users currently inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7veS5EZI6BzYDa7YKUEKJg.png" /><figcaption>Attendance Tab</figcaption></figure><h3>Analytics Tab</h3><p>Four chart views powered by Recharts:</p><ul><li><strong>Hourly Activity</strong> — bar chart of scans per hour (0–23)</li><li><strong>Weekly Trend</strong> — grouped bar (Granted vs Denied by day)</li><li><strong>Top Users</strong> — horizontal bar, ranked by scan count</li><li><strong>Grant vs Deny</strong> — donut chart with percentage</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*os93Ewl4U9mEj1B5wYY2jA.png" /><figcaption>Analytics Tab</figcaption></figure><h3>Admin Panel</h3><p>Full CRUD for users stored in Firebase /rfid/users. Fields: UID (8 hex chars), Name, Role, Active toggle, Allowed start/end time, Allowed days (clickable day grid). ESP32 auto-refreshes user list every 5 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHbSL_JZu8jUYQajbV-xrg.png" /><figcaption>Admin Panel</figcaption></figure><h3>Security Tab</h3><p>Wrong attempt counter with threshold progress bar, alarm status, denied access log with reason, and manual reset button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUgbJMN3-G73dMUItCJayA.png" /><figcaption>Security Tab</figcaption></figure><h3>Setup Guide</h3><h3>1. Firebase</h3><ol><li>Go to <a href="https://console.firebase.google.com/">console.firebase.google.com</a></li><li>Create project → Enable Realtime Database → Test mode</li><li>Set rules:</li></ol><pre>{<br>  &quot;rules&quot;: {<br>    &quot;rfid&quot;: { &quot;.read&quot;: &quot;true&quot;, &quot;.write&quot;: &quot;true&quot; }<br>  }<br>}</pre><ol><li>Project Settings → Web App → Copy firebaseConfig</li></ol><h3>2. ESP32 Firmware</h3><pre># Clone and open in VSCode<br>git clone https://github.com/your-username/Crypt_AccessIQ<br>cd Crypt_AccessIQ/esp32_project<br>code .</pre><p>Edit include/config.h:</p><pre>#define WIFI_SSID              &quot;YourWiFi&quot;<br>#define WIFI_PASSWORD          &quot;YourPassword&quot;<br>#define FIREBASE_API_KEY       &quot;AIzaSy...&quot;<br>#define FIREBASE_DATABASE_URL  &quot;https://your-project-rtdb.firebaseio.com&quot;</pre><p>Upload → Open Serial Monitor (115200) → Scan a card → Note UID.</p><h3>3. React Dashboard</h3><pre>cd react_dashboard<br>npm install<br># Edit src/firebase.js with your Firebase config<br>npm start</pre><p>Open <a href="http://localhost:3000/">http://localhost:3000</a> → Admin tab → Add User with the UID from Serial Monitor.</p><h3>Results</h3><p>After completing the project:</p><ul><li>Card scan to access grant/deny: <strong>&lt; 500ms</strong></li><li>Firebase sync latency: <strong>1–3 seconds</strong></li><li>React dashboard live update: <strong>&lt; 2 seconds</strong></li><li>Users supported: <strong>up to 30 (local cache) + unlimited in Firebase</strong></li><li>Works offline: <strong>Yes</strong> — access control functions without WiFi (no time check, no cloud sync)</li></ul><h3>Future Improvements</h3><ul><li>[ ] Telegram Bot notifications on access events</li><li>[ ] Servo/relay integration for physical door lock</li><li>[ ] Monthly attendance PDF export</li><li>[ ] OTA firmware updates</li><li>[ ] Face recognition fallback (ESP32-CAM)</li><li>[ ] Multi-door support</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRzPAOG35sHvQcvPtldZTg.jpeg" /><figcaption>Future Improvements</figcaption></figure><h3>Repository</h3><p><strong>GitHub:</strong> <a href="https://github.com/rafiul254/Crypt_AccessIQ">rafiul254/Crypt_AccessIQ: IoT Based Access Control System — an end-to-end smart access control solution that uses RFID cards to grant or deny entry, logs all events to Firebase Realtime Database in real time, and presents a live React dashboard for monitoring, analytics, and administration. ESP32 + Firebase + React</a></p><pre>rfid-access-control/<br>├── esp32_project/    ← PlatformIO firmware<br>├── Dashboard/        ← React frontend<br>├── README.md<br>└── .gitignore</pre><h3>Final Thoughts</h3><p>This project taught me more about SPI bus management, ESP32 internals, and hardware debugging than any course ever has. The RC522 that kept returning 0x00 wasn&#39;t broken — it was a clone chip running on a shared SPI bus with a floating SD card CS pin and a 20MHz clock it didn&#39;t like.</p><p>The display that showed mirrored text wasn’t wired wrong — it was an ILI9341 clone with a different MADCTL default that needed one byte override.</p><p>Hardware problems rarely have obvious error messages. You sit with the symptom, form a hypothesis, test it, and iterate. That loop — not the code — is the real skill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQk4pwH6sXQsFR8FTGBPDg.jpeg" /><figcaption>My Final Thoughts</figcaption></figure><p><em>Written by a B.Sc. student in IoT &amp; Robotics Engineering.</em> <em>Stack: ESP32 · RC522 · Firebase · React · PlatformIO · VSCode</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09d68e6e8618" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Fullscreen Animated GIF Player on ESP32 with ST7735 TFT Display]]></title>
            <link>https://rafiulislam25.medium.com/building-a-fullscreen-animated-gif-player-on-esp32-with-st7735-tft-display-6b6119696b3e?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b6119696b3e</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[platformio]]></category>
            <category><![CDATA[tft-display]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Fri, 29 May 2026 20:02:29 GMT</pubDate>
            <atom:updated>2026-05-29T20:02:29.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZmJ6AGkxW6fJK2_Dz_ccg.jpeg" /><figcaption>Fullscreen Animated GIF Player</figcaption></figure><h3>How I stored 6 Marvel &amp; Anime GIFs directly in ESP32 Flash memory — no SD card needed…!</h3><h3><strong>Introduction</strong></h3><p>As an IoT &amp; Robotics Engineering student, I’m always looking for ways to push microcontrollers beyond their typical use cases. For my latest project, I built a <strong>fullscreen animated GIF player</strong> running entirely on an ESP32 — displaying Marvel and Anime animations on a tiny 1.8&quot; TFT LCD display.</p><p>The challenge? Fitting 6 animated GIFs into the ESP32’s limited Flash memory with <strong>no SD card, no external storage</strong> — just the microcontroller and the display.</p><p>Here’s exactly how I built it, every problem I hit, and how I solved them.</p><h3>What I Built</h3><p>A standalone GIF animation player that:</p><ul><li>Plays <strong>6 animated GIFs</strong> fullscreen on a 1.8&quot; ST7735 TFT (160×128)</li><li>Stores all GIF data directly in <strong>ESP32 Flash (PROGMEM)</strong></li><li><strong>Auto-cycles</strong> every 8 seconds with a smooth wipe transition</li><li>Requires <strong>no SD card, no WiFi, no cloud</strong> — fully self-contained</li><li>Can be extended with any GIF using a custom Python converter script</li></ul><p><strong>Animations featured:</strong> Loki · Black Panther · Iron Man · Marvel · Demon Slayer · One Piece</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYqIVm8VTFbRYoyGa7p4nA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzq83er-WlYJig_bOJud3A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHap_tqzybbnx9o8vxDgpg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xe6ETVo9JG9tT_KU_YuKw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PTkCI-FSpQzp07C0Gq56Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAz58In1buZU-ujrq1kAQQ.jpeg" /><figcaption>6 Animated GIF</figcaption></figure><h3>Hardware Required</h3><p>Component Specification Microcontroller ESP32 Development Board Display ST7735 1.8&quot; TFT LCD (160×128, SPI) Jumper Wires Male-to-Female Breadboard Optional Power USB via ESP32</p><p><strong>Total cost estimate: ~500–700 BDT</strong> (locally sourced in Bangladesh)</p><h3>Pin Connections</h3><p>The ST7735 communicates over SPI. Here’s the exact wiring:</p><pre>ESP32                    ST7735 Display<br>──────────────────────────────────────────<br>GPIO 18  ─────────────  CLK / SCL<br>GPIO 23  ─────────────  SDA / MOSI<br>GPIO  5  ─────────────  CS<br>GPIO  2  ─────────────  RS / DC<br>GPIO  4  ─────────────  RST<br>3.3V     ─────────────  VCC<br>GND      ─────────────  GND</pre><blockquote><em>⚠️ </em><strong><em>Important:</em></strong><em> Always use </em><strong><em>3.3V</em></strong><em> for VCC. The ST7735 is NOT 5V tolerant — connecting to 5V will permanently damage the display. The ESP32 is a 3.3V device, so all GPIO signals are also 3.3V compatible — no level shifter needed.</em></blockquote><h3>The Core Challenge: Fitting GIFs in Flash</h3><p>ESP32 has <strong>4MB of Flash memory</strong>, but after the bootloader, partition table, and code, the available space for a typical min_spiffs partition is around <strong>1966 KB</strong>.</p><p>Here’s how I optimized 6 GIFs to fit:</p><p>GIF Original Size After Optimization Frames Loki ~2.1 MB 335 KB 30 Black Panther ~800 KB 211 KB 18 Iron Man ~450 KB 153 KB 18 Marvel ~600 KB 130 KB 20 Demon Slayer ~700 KB 152 KB 18 One Piece ~300 KB 147 KB 12 <strong>Total</strong> <strong>~5 MB</strong> <strong>1127 KB</strong></p><p>The optimization strategy involved three steps:</p><p><strong>1. Resolution scaling</strong> — Resizing each GIF to exactly 160×128 pixels (the display resolution) using Python’s Pillow library with LANCZOS resampling.</p><p><strong>2. Palette reduction</strong> — GIFs support up to 256 colors. Reducing to 96–128 colors per GIF significantly cuts file size while maintaining visual quality.</p><p><strong>3. Frame skipping</strong> — For high-frame-count GIFs like Loki (originally 89 frames), I kept every 3rd frame and adjusted the frame delay accordingly to maintain smooth motion perception.</p><h3>The Python Converter: gif_convert.py</h3><p>The key to this project is a custom Python script that converts any .gif file into a C header file containing the raw GIF bytes as a PROGMEM array.</p><pre># Core conversion logic<br>def convert(input_path, output_dir, colors, skip):<br>    img = Image.open(input_path)<br>    n_frames = getattr(img, &#39;n_frames&#39;, 1)</pre><pre>    frames = []<br>    canvas = Image.new(&quot;RGBA&quot;, img.size, (0,0,0,255))</pre><pre>    for i in range(n_frames):<br>        img.seek(i)<br>        frame = img.copy().convert(&quot;RGBA&quot;)<br>        canvas.paste(frame, (0,0), frame)</pre><pre>        if i % skip != 0:   # Frame skipping<br>            continue</pre><pre>        # Resize to exact display resolution<br>        resized = canvas.copy().resize((160, 128), Image.LANCZOS)</pre><pre>        # Reduce palette<br>        palette_frame = resized.convert(&#39;P&#39;,<br>            palette=Image.ADAPTIVE, colors=colors)<br>        frames.append(palette_frame)</pre><pre>    # Re-encode as optimized GIF<br>    buf = io.BytesIO()<br>    frames[0].save(buf, format=&#39;GIF&#39;, save_all=True,<br>        append_images=frames[1:], loop=0, optimize=True)</pre><pre>    # Write as C PROGMEM array<br>    gif_bytes = buf.getvalue()<br>    write_header(gif_bytes, var_name, output_h)</pre><p>The output .h file looks like this:</p><pre>#pragma once<br>#include &lt;pgmspace.h&gt;</pre><pre>// iron_man_marvel_gif.h | 160x128 | 18 frames | 153 KB<br>const uint8_t iron_man_marvel_gif_data[] PROGMEM = {<br>    0x47, 0x49, 0x46, 0x38, 0x39, 0x61, ...<br>    // Raw GIF bytes stored in Flash<br>};</pre><p>Usage is simple:</p><pre>pip install Pillow<br>python gif_convert.py iron_man.gif<br># Output: iron_man.h → copy to src/</pre><h3>The Display Driver: GIFDraw Callback</h3><p>The <strong>AnimatedGIF</strong> library by Larry Bank (bitbank2) decodes GIF frames and calls a user-defined callback for each row. This is where we write pixels to the TFT:</p><pre>void GIFDraw(GIFDRAW* pDraw) {<br>    uint8_t*  s       = pDraw-&gt;pPixels;   // decoded pixel row<br>    uint16_t* palette = pDraw-&gt;pPalette;  // RGB565 color palette</pre><pre>    int y = pDraw-&gt;iY + pDraw-&gt;y;<br>    if (y &gt;= SCREEN_H) return;</pre><pre>    int iWidth = pDraw-&gt;iWidth;<br>    static uint16_t rowBuf[160];</pre><pre>    // Convert palette indices → RGB565 pixels<br>    if (pDraw-&gt;ucHasTransparency) {<br>        uint8_t t = pDraw-&gt;ucTransparent;<br>        for (int i = 0; i &lt; iWidth; i++)<br>            rowBuf[i] = (s[i] == t) ? 0x0000 : palette[s[i]];<br>    } else {<br>        for (int i = 0; i &lt; iWidth; i++)<br>            rowBuf[i] = palette[s[i]];<br>    }</pre><pre>    // Push entire row via SPI in one burst — much faster than pixel-by-pixel<br>    tft.drawRGBBitmap(pDraw-&gt;iX, y, rowBuf, iWidth, 1);<br>}</pre><p>The key optimization here is drawRGBBitmap() — instead of calling drawPixel() 160 times per row (160 separate SPI transactions), we build the entire row in a buffer and push it in a single SPI burst. This is approximately <strong>10× faster</strong> and is what makes smooth playback possible.</p><h3>Non-Blocking Animation Loop</h3><p>A critical design decision was using playFrame(false, &amp;delayMs) instead of playFrame(true, NULL).</p><p>The true parameter makes the library handle frame delay internally — blocking the CPU for the entire delay duration. This means nothing else can run during that time.</p><p>With false, we get the frame delay back and handle it ourselves:</p><pre>void loop() {<br>    // Auto-change GIF every 8 seconds<br>    if (millis() - gifStartTime &gt;= GIF_PLAY_DURATION) {<br>        curIdx = (curIdx + 1) % GIF_COUNT;<br>        loadGif(curIdx);<br>        gifStartTime = millis();<br>        return;<br>    }</pre><pre>    // Non-blocking frame play<br>    int delayMs = 0;<br>    if (gifPlayer.playFrame(false, &amp;delayMs) == false) {<br>        gifPlayer.reset();  // Loop animation<br>    }</pre><pre>    // Wait for frame duration while checking auto-change timer<br>    unsigned long frameEnd = millis() + max(delayMs, 0);<br>    while (millis() &lt; frameEnd) {<br>        if (millis() - gifStartTime &gt;= GIF_PLAY_DURATION) break;<br>        delay(5);<br>    }<br>}</pre><p>This design allows the auto-change timer to interrupt mid-frame-delay — making the GIF switching feel responsive and immediate.</p><h3>Smooth Transition Effect</h3><p>Between GIFs, a fast wipe transition clears the screen without an abrupt flash:</p><pre>void transitionWipe() {<br>    for (int x = 0; x &lt; SCREEN_W; x += 8) {<br>        tft.fillRect(x, 0, 8, SCREEN_H, 0x0000);<br>        delayMicroseconds(400);<br>    }<br>}</pre><p>This draws 8-pixel vertical black bars sweeping left to right in about 80ms — fast enough to feel snappy, slow enough to look intentional.</p><h3>Problems I Hit (And Fixed)</h3><h3>Problem 1: ledcAttach not found</h3><p><strong>Root cause:</strong> My ESP32 Arduino core was version 2.x. The new ledcAttach() API only exists in core 3.x.</p><p><strong>Fix:</strong> Used the older API with compile-time version detection:</p><pre>#if ESP_ARDUINO_VERSION_MAJOR &gt;= 3<br>    ledcAttach(BUZZER, 2000, 8);<br>#else<br>    ledcSetup(0, 2000, 8);<br>    ledcAttachPin(BUZZER, 0);<br>#endif</pre><h3>Problem 2: iCanvasHeight undefined</h3><p><strong>Root cause:</strong> AnimatedGIF v2.2.1 removed the iCanvasHeight field from the GIFDRAW struct.</p><p><strong>Fix:</strong> Used the library method instead:</p><pre>// Before (broken):<br>int16_t offY = (SCREEN_H - pDraw-&gt;iCanvasHeight) / 2;</pre><pre>// After (correct):<br>int16_t offY = (SCREEN_H - gifPlayer.getCanvasHeight()) / 2;</pre><h3>Problem 3: Flash overflow (103.2% used)</h3><p><strong>Root cause:</strong> Total firmware was 2029 KB — exceeding the 1966 KB partition limit.</p><p><strong>Fix:</strong> Reduced GIF palette colors (256 → 96–128) and added frame skipping for high-frame-count GIFs. Final firmware: ~1459 KB.</p><h3>Problem 4: Upload serial noise at 921600 baud</h3><p><strong>Root cause:</strong> USB cable quality or CP2102 chip limitation causing data corruption at high speed.</p><p><strong>Fix:</strong> Reduced upload speed in platformio.ini:</p><pre>upload_speed = 460800</pre><h3>Project Structure</h3><pre>ESP32-GIF-Player/<br>├── src/<br>│   ├── main.cpp                         ← Main application<br>│   ├── angry_loki_gif.h                 ← GIF data (PROGMEM)<br>│   ├── black_panther_marvel_gif.h<br>│   ├── iron_man_marvel_gif.h<br>│   ├── marvel_cinematic_universe_...h<br>│   ├── demon_slayer_gif.h<br>│   └── one_piece_gif.h<br>├── gif_convert.py                       ← GIF → C header converter<br>├── platformio.ini                       ← Build config<br>└── README.md</pre><h3>Libraries Used</h3><p>Library, Author &amp; Purpose — AnimatedGIF, Larry Bank (bitbank2), GIF decode &amp; playback, Adafruit ST7735, Adafruit, TFT display driver, Adafruit GFX, Adafruit, Graphics primitives.</p><p>All installed automatically via platformio.ini:</p><pre>lib_deps =<br>    adafruit/Adafruit ST7735 and ST7789 Library @ ^1.10.4<br>    adafruit/Adafruit GFX Library @ ^1.11.9<br>    bitbank2/AnimatedGIF @ ^2.1.1</pre><h3>How to Add Your Own GIFs</h3><ol><li>Download a GIF from <a href="https://giphy.com/">Giphy</a> or convert a video clip at <a href="https://ezgif.com/video-to-gif">ezgif.com</a></li></ol><p>2. Run the converter</p><pre>pip install Pillow<br>python gif_convert.py your_animation.gif</pre><p>3. Copy the generated .h file to src/</p><p>4. In main.cpp, add:</p><pre>#include &quot;your_animation.h&quot;const GifEntry gifList[] = {<br>    // existing entries...<br>    { your_animation_data,<br>      sizeof(your_animation_data),<br>      &quot;Your Animation&quot; },<br>};</pre><p>5. Build and upload!</p><h3>Key Takeaways</h3><p><strong>What I learned from this project:</strong></p><ul><li><strong>PROGMEM management</strong> — Storing large binary data in Flash instead of RAM is essential on resource-constrained microcontrollers. RAM is precious (only 327 KB on ESP32); Flash is comparatively abundant.</li><li><strong>SPI optimization</strong> — Row-buffer SPI bursts (drawRGBBitmap) are dramatically faster than per-pixel writes. Always batch SPI transactions when possible.</li><li><strong>Non-blocking design</strong> — while(delay) loops are the enemy of responsive embedded systems. Always design loops to check conditions frequently.</li><li><strong>Flash partition planning</strong> — PlatformIO’s min_spiffs.csv partition gives more app space at the cost of SPIFFS storage. Choosing the right partition table for your use case matters.</li><li><strong>GIF format internals</strong> — GIF’s LZW compression, palette-based color model, and disposal methods are fascinating. The AnimatedGIF library handles the complexity, but understanding the format helped me optimize.</li></ul><h3>Demo &amp; Source Code</h3><p>🎥 <strong>Watch the demo:</strong> <a href="https://youtube.com/shorts/jHeiL1j6YvM?si=FgKD0m4RwCojAMcT">https://youtube.com/shorts/jHeiL1j6YvM?si=FgKD0m4RwCojAMcT</a></p><p>💻 <strong>Source code:</strong> <a href="https://github.com/rafiul254/ESP32-GIF-Player">https://github.com/rafiul254/ESP32-GIF-Player</a></p><p><em>If you found this helpful, follow me for more ESP32, Arduino, and IoT Engineering content. I document my entire learning journey as a IoT &amp; Robotics Engineering student.</em></p><p><em>Connect with me:</em> <em>🔗 LinkedIn: </em><a href="https://www.linkedin.com/in/rafiul-islam-25sep92004/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BqXeEkeRwQbu0KK09YMFqMg%3D%3D">https://www.linkedin.com/in/rafiul-islam-25sep92004</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b6119696b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Are Standing in the Middle of a Revolution — And Most People Haven’t Realized It Yet]]></title>
            <link>https://javascript.plainenglish.io/we-are-standing-in-the-middle-of-a-revolution-and-most-people-havent-realized-it-yet-6a9b291e1e3d?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a9b291e1e3d</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[revolution]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[iot-engineering-services]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Tue, 05 May 2026 19:58:16 GMT</pubDate>
            <atom:updated>2026-05-05T19:58:16.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buolyzCtQQyVR76E2qi35Q.jpeg" /><figcaption>Revolution of IoT &amp; Robotics</figcaption></figure><h3>We Are Standing in the Middle of a Revolution — And Most People Haven’t Realized It Yet</h3><p><em>Some changes come slowly. And some changes come in a way where you don’t even realize when the entire world has shifted.</em></p><p><em>IoT and robotics are exactly that second kind of change.</em></p><h3>Let’s Look Back for a Moment</h3><p>In 2008, for the first time in history, the number of connected devices on Earth surpassed the number of human beings.</p><p>Nobody really paid attention.</p><p>In 2012, Amazon deployed Kiva Robots inside their warehouses. Overnight, thousands of workers lost their jobs — but delivery speed tripled.</p><p>Then 2020 hit. COVID-19. Factories shut down. People locked inside. But robot-operated warehouses didn’t stop for a single day.</p><p>That was the moment the world finally understood — automation is no longer an option. It’s a survival strategy.</p><h3>So What Actually Is IoT + Robotics?</h3><p>Let me break it down simply.</p><p>IoT means a device that doesn’t just work — it <em>thinks.</em> If your AC understands you’re walking through the door and automatically adjusts the temperature before you even touch the remote — that’s IoT.</p><p>Robotics means turning that thinking into <em>physical action.</em> Not just sensors, but hands and legs too.</p><p>And when both work together?</p><blockquote>A factory where the machine detects its own fault, fixes it, and sends a WhatsApp alert to the supervisor — all by itself.</blockquote><p>This isn’t imagination. This is happening right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*egwk8KZw_Jq6QLEX" /><figcaption>What is IoT &amp; Robotics?</figcaption></figure><h3>The Timeline of This Revolution</h3><p>2008 → Connected devices outnumber world population for the first time</p><p>2012 → Amazon Kiva: Warehouse automation begins at scale</p><p>2015 → Industry 4.0 officially declared by the World Economic Forum</p><p>2017 → Boston Dynamics’ Atlas learns to walk, run, and do backflips</p><p>2020 → Pandemic pushes automation adoption forward by 5 years — overnight</p><p>2023 → AI merges with Robotics. ChatGPT-style reasoning enters physical machines</p><p>2025 → Tesla Optimus, Figure 01, Unitree H1 — humanoid robots start working on real factory floors</p><p>2026 → Right now. You’re reading this. The world is changing in real time.</p><h3>Where Has This Revolution Already Entered?</h3><p>1)Healthcare: The Da Vinci Surgical Robot has performed over 10 million surgeries to date. More precise than a human hand. No tremors. No fatigue.</p><p>2)Agriculture: John Deere’s autonomous tractors use GPS and AI to navigate fields on their own. Drones monitor crop health pixel by pixel.</p><p>3)Manufacturing: BMW’s Leipzig plant produces 1,000 cars every single day — with 5,000 robots working alongside just 3,000 human employees.</p><p>4)Logistics: Amazon now operates 750,000+ robots across its fulfillment centers. Place an order — it ships within 30 minutes.</p><p>5)Smart Cities: Singapore, Dubai, Tokyo — entire cities running traffic, power grids, and emergency response through one connected intelligent network.</p><h3>The Biggest Shift That’s Coming</h3><p>For decades, robots meant — <em>massive, heavy, dangerous, locked inside cages.</em></p><p>Now comes Collaborative Robots (Cobots) — designed to work beside humans. With you, not instead of you.</p><p>Coming next is Edge AI — where robots make decisions inside their own brain, without needing the cloud. In milliseconds.</p><p>Then Digital Twins — a complete virtual copy of an entire factory, where you simulate every scenario first, then implement in the real world.</p><p>And most importantly — ROS 2, the universal language of robots. One framework that lets any engineer program any robot, anywhere in the world.</p><h3>Let Me Talk About Bangladesh for a Moment</h3><p>We still think this revolution belongs to “them” — not us.</p><p>But think about it —</p><p>If smart quality-control robots enter our garment industry, rejection rates drop by 40%. If IoT sensor networks reach our agriculture, crop loss cuts in half. If Dhaka’s traffic system becomes AI-driven, we save billions of productive hours lost in gridlock every year.</p><p>Who will build these solutions?</p><p>Nobody is coming from outside to do it.</p><p>We have to build it. Our engineers. Our developers. Our innovators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2NtNhuM2w1ccpUqu" /><figcaption>IoT &amp; Robotics in Bangladesh</figcaption></figure><h3>Final Thought</h3><p>Nobody warned us that the revolution would arrive this quietly.</p><p>No dramatic announcement. No countdown. Just one morning you wake up and realize — the world you knew yesterday has already been replaced by something smarter, faster, and more connected.</p><p>That’s exactly where we are right now.</p><p>I’m a student of IoT &amp; Robotics Engineering — and honestly, that means I live inside this shift every single day. One week I’m training a gesture recognition model. The next I’m diving into ROS 2 and learning how robots actually <em>think</em> and <em>navigate.</em> Then it’s embedded systems, then edge AI, then simulation in Gazebo.</p><p>Every single day, something new breaks my understanding of what I thought I already knew.</p><p>And that’s the most exciting part.</p><p>Because this field doesn’t let you sit still. It pulls you forward — constantly. And the more you learn, the more you realize how much is still waiting to be built, to be solved, to be invented.</p><p>This revolution is not something to fear.</p><p>It belongs to the people who are curious enough to keep learning — even when it’s overwhelming. Even when it feels like you’ll never catch up.</p><blockquote>“The best way to predict the future is to invent it.”<em> — </em>Alan Kay</blockquote><p>So here’s my question for you —</p><p>Will you watch this revolution happen, or will you be one of the people building it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*tqQs51N0PnavmVnz" /><figcaption>Industry Revolution of IoT &amp; Robotics</figcaption></figure><p><em>I’m Rafiul Islam — an IoT &amp; Robotics Engineering student who is learning something new every single day. From gesture-controlled systems and machine learning models to ROS 2 robotics and embedded hardware — I’m on a journey of building, breaking, and figuring it all out. If you’re passionate about technology and want to connect with someone who’s deep in the grind — let’s talk….!</em></p><p>#IoT #Robotics #FutureTech #Engineering #Bangladesh #Innovation #SmartAutomation #Industry #LinkedInArticle #revolution #embedded systems</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a9b291e1e3d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/we-are-standing-in-the-middle-of-a-revolution-and-most-people-havent-realized-it-yet-6a9b291e1e3d">We Are Standing in the Middle of a Revolution — And Most People Haven’t Realized It Yet</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Expensive Mistakes I Made Building My First Robot]]></title>
            <link>https://rafiulislam25.medium.com/5-expensive-mistakes-i-made-building-my-first-robot-e2cb1819cff6?source=rss-17efd2adef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2cb1819cff6</guid>
            <category><![CDATA[mistakes]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Rafiul islam]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 23:53:20 GMT</pubDate>
            <atom:updated>2026-04-09T23:53:20.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUO1ig-a8glQC5wmiUNvXA.jpeg" /><figcaption><strong>Learn from Mistakes</strong></figcaption></figure><p>The burning smell hit me first. Then I saw the smoke curling up from my motor driver. Then I realized: this was the third component I’d fried this week.</p><p>Welcome to my $45 education in robotics. Building OopsStopper v1.0 — my first autonomous robot — taught me more about electronics than any course could. But not through success. Through spectacular, expensive failures.</p><p>I fried motor drivers. I killed an Arduino. I wasted days debugging problems that were embarrassingly obvious in hindsight. I spent money on components I didn’t need and skimped on ones I did.</p><p><strong>The final tally?</strong><br> Working robot: $35<br> Mistakes and replacements: $10<br> Total investment: $45</p><p>But here’s what makes it worth sharing: <strong>you don’t have to pay this tuition.</strong></p><p>Every mistake I made was preventable. Every dollar I wasted taught me a lesson. And now you get those lessons without the burnt electronics smell.</p><p>If you’re about to start your first robotics project, this article might save you a week of debugging, $10 — $15 in replacement parts, and at least one “why-did-I-think-this-would-work” moment.</p><p>Let’s dive into the five mistakes that cost me the most — and exactly how to avoid them.</p><h3>Before We Start: Why Mistakes Matter More Than Success</h3><p>Real talk: <strong>You will make mistakes.</strong> It’s not a matter of if, but when and how expensive.</p><p>Every maker has a drawer of dead components. Every engineer has that project that “almost worked.” Every beginner has reconnected wires five times before realizing they were using the wrong pin all along.</p><p>This isn’t failure — it’s how learning actually works.</p><p>But there are two types of mistakes:</p><ol><li><strong>Cheap mistakes</strong> you learn from quickly</li><li><strong>Expensive mistakes</strong> that cost time, money, and momentum</li></ol><p>The goal isn’t perfection. The goal is avoiding the expensive mistakes while embracing the educational ones.</p><p>So here are the five that hurt the most, the real damage they caused, and the systems I built to prevent them from happening again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G34RR4jQKLDsqeUP8AVqQw.jpeg" /></figure><h3>Mistake #1: “I Don’t Need a Circuit Diagram, I’ll Just Remember”</h3><h3>What I Did (Or Didn’t Do)</h3><p>I watched a few YouTube tutorials, looked at some wiring diagrams, and thought: “This is simple. Arduino pin 7 to motor driver IN1, pin 8 to IN2… I got this. No need to write it down.”</p><p>Then I started connecting wires based on memory and screenshots.</p><p><strong>Spoiler alert:</strong> My memory was very, very wrong.</p><h3>The Damage Report</h3><p><strong>Time wasted:</strong> 6+ hours across multiple debugging sessions<br> <strong>Components destroyed:</strong> 1 motor driver ($5)<br> <strong>Replacement cost:</strong> $5<br> <strong>Frustration level:</strong> Maximum<br> <strong>Coffee consumed:</strong> Too much</p><h3>What Actually Happened (The Painful Timeline)</h3><p><strong>Day 1 — The Confidence:</strong><br> Connected everything from memory. Powered it on. Nothing moved. “Must be a code issue,” I thought.</p><p>Spent 3 hours checking code that was actually fine.</p><p><strong>Day 2 — The Rewiring:</strong><br> Realized wiring was wrong. Tore everything apart. Rewired from memory again. Different configuration this time because I “remembered it better.”</p><p>Still didn’t work. Different symptoms.</p><p><strong>Day 3 — The Wild Guessing:</strong><br> Started randomly swapping wires. “Maybe this pin goes here?” Robot moved! Wrong direction. Swapped more wires. Moved again! Still wrong.</p><p><strong>Day 4 — The Smell:</strong><br> Finally got it moving correctly! Ran it for 5 minutes to celebrate. Then noticed burning smell. Motor driver overheating. Bad.</p><p><strong>Day 5 — The Death:</strong><br> Motor driver completely dead. Smoke. Smell. Defeat.</p><p>Had to order a new one. One week shipping. Project momentum: completely lost.</p><h3>The Real Problem</h3><p>Without proper documentation, I had:</p><ul><li><strong>No reference when debugging</strong> — Was this wire always here?</li><li><strong>No way to verify connections</strong> — Is this right or am I guessing?</li><li><strong>No baseline to return to</strong> — What was the working configuration?</li><li><strong>No ability to ask for help</strong> — Can’t describe what I did wrong if I don’t know what I did</li><li><strong>No documentation for future modifications</strong> — Version 2.0? Start from scratch again</li></ul><h3>The Solution That Actually Works</h3><p><strong>The “Document First, Connect Second” Rule</strong></p><p><strong>Step 1: Create a connection table BEFORE touching any wires</strong></p><pre>Component Connection Reference<br>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━<br>Arduino Uno → L298N Motor Driver</pre><pre>Pin 5 (PWM)  →  ENA (Enable A - Speed Control)<br>Pin 6        →  IN1 (Motor A Direction Control)<br>Pin 7        →  IN2 (Motor A Direction Control)<br>Pin 8        →  IN3 (Motor B Direction Control)<br>Pin 9        →  IN4 (Motor B Direction Control)<br>Pin 10 (PWM) →  ENB (Enable B - Speed Control)<br>GND          →  GND (CRITICAL: Common Ground)</pre><pre>Arduino Uno → IR Sensor</pre><pre>Pin 2        →  OUT (Digital Signal)<br>5V           →  VCC (Power)<br>GND          →  GND (Ground)</pre><pre>Power Distribution</pre><pre>Battery 7.4V →  Arduino Vin (Powers Arduino)<br>Battery 7.4V →  L298N 12V Input (Powers Motors)<br>Common GND   →  All grounds connected together</pre><p><strong>Step 2: Draw a simple diagram (doesn’t have to be fancy)</strong></p><p>Even a hand-drawn sketch works. Just needs to show:</p><ul><li>Which Arduino pin connects to what</li><li>Power flow</li><li>Ground connections (SUPER important)</li><li>Component labels</li></ul><p><strong>Tools you can use:</strong></p><ul><li><strong>Pen and paper</strong> (fastest, most authentic)</li><li><strong>Fritzing</strong> (free software, makes pretty diagrams)</li><li><strong>Tinkercad Circuits</strong> (browser-based, easy to share)</li><li><strong>Excel/Google Sheets table</strong> (super quick)</li></ul><p><strong>Step 3: Take photos of your actual wiring</strong></p><p>Before closing up the project:</p><ol><li>Top-down overview shot</li><li>Close-up of critical connections</li><li>Close-up of power connections</li><li>Label photos in your phone (“OopsStopper — Motor Connections”)</li></ol><p>Save in project folder. Future you will be grateful.</p><p><strong>Step 4: Keep a project notebook</strong></p><p>Physical or digital, doesn’t matter. Include:</p><p><strong>Page 1: Pin Assignments</strong></p><ul><li>Every connection listed</li><li>Color-coded if using different wire colors</li></ul><p><strong>Page 2: Component Specs</strong></p><ul><li>What you’re using and why</li><li>Voltage/current ratings</li><li>Where you bought it (for reordering)</li></ul><p><strong>Page 3: Known Issues &amp; Fixes</strong></p><ul><li>“Motor A runs backward → Swap IN1 and IN2”</li><li>“Robot stops randomly → Check battery charge”</li></ul><p><strong>Page 4: Modification Log</strong></p><ul><li>Date and what you changed</li><li>Why you changed it</li><li>Did it work?</li></ul><p><strong>Page 5: Future Ideas</strong></p><ul><li>“Add ultrasonic sensor for obstacle avoidance”</li><li>“Try different turn timing”</li></ul><h3>What I Do Now</h3><p><strong>My current project workflow:</strong></p><ol><li><strong>Before ordering parts:</strong> Create wiring diagram in Tinkercad</li><li><strong>After parts arrive:</strong> Test each component, document results</li><li><strong>During assembly:</strong> Follow diagram, photograph each step</li><li><strong>After working:</strong> Create clean documentation, push to GitHub</li></ol><p><strong>Time spent on documentation:</strong> 30–45 minutes per project<br> <strong>Time saved in debugging:</strong> Literally hours<br> <strong>Peace of mind:</strong> Priceless</p><p><strong>Example from OopsStopper v2.0:</strong></p><ul><li>Wiring diagram done BEFORE ordering parts</li><li>Caught power supply issue in planning phase</li><li>Assembly took 2 hours instead of 2 days</li><li>Zero fried components</li><li>Works perfectly first time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zhidSfo2ySVHgHFoe6MPA.jpeg" /></figure><h3>Mistake #2: Buying the Cheapest Components Without Checking Reviews</h3><h3>What I Did</h3><p>I needed a motor driver. Found two options on Amazon:</p><p><strong>Option A:</strong> $5, 4.5 stars, 200 reviews<br> <strong>Option B:</strong> $3, 3.8 stars, 50 reviews</p><p>My brain: “They’re both L298N motor drivers. Same chip, same function. Why pay more? I’ll save $2!”</p><p><strong>Narrator voice:</strong> <em>He would not save $2.</em></p><h3>The Damage Report</h3><p><strong>Money wasted on cheap driver:</strong> $3<br> <strong>Shipping for replacement:</strong> $5<br> <strong>Total monetary loss:</strong> $8<br> <strong>Time lost waiting for replacement:</strong> 1 week<br> <strong>Project momentum:</strong> Completely killed<br> <strong>Lesson learned:</strong> You can’t put a price on… oh wait, yes you can: $8</p><h3>What Actually Went Wrong</h3><p>The $3 motor driver had:</p><p><strong>Physical issues:</strong></p><ul><li>Bent pins (had to straighten with pliers)</li><li>Poor soldering (cold joints visible)</li><li>Thin PCB (felt cheap and flimsy)</li><li>No proper heat sink (just a small aluminum plate)</li></ul><p><strong>Performance issues:</strong></p><ul><li>Inconsistent voltage output (motors stuttered)</li><li>Overheating within 5 minutes</li><li>Erratic behavior under load</li><li>Random shutdowns</li></ul><p><strong>Documentation issues:</strong></p><ul><li>Instructions only in Chinese</li><li>No pinout diagram</li><li>Generic datasheet (not specific to this board)</li></ul><p><strong>The debugging nightmare:</strong></p><p>I spent THREE DAYS thinking:</p><ul><li>“My code must be wrong” (tested the code — it was fine)</li><li>“My wiring must be wrong” (checked 10 times — it was correct)</li><li>“My motors must be faulty” (tested individually — they worked)</li><li>“My power supply is bad” (measured with multimeter — it was good)</li></ul><p>Never suspected the $3 motor driver because “it’s just an L298N chip, how could that be the problem?”</p><p>Finally ordered the $5 version. Arrived. Swapped it in. Everything worked perfectly immediately.</p><p><strong>The $3 driver went in the trash.</strong> Along with a week of my time.</p><h3>The Real Problem</h3><p><strong>Not all “same” components are actually the same.</strong></p><p>Two L298N motor drivers might use:</p><ul><li>Different quality ICs (original vs knockoff chips)</li><li>Different PCB materials (quality copper vs thin cheap boards)</li><li>Different supporting components (proper capacitors vs minimal/missing ones)</li><li>Different manufacturing standards (tested vs “hope it works”)</li></ul><p><strong>The cheap one cuts corners you can’t see until it fails.</strong></p><h3>The Solution That Actually Works</h3><p><strong>The 5-Minute Component Research Method</strong></p><p><strong>Before buying ANY critical component:</strong></p><p><strong>Step 1: Check the review distribution, not just the average</strong></p><pre>GOOD SIGN:<br>★★★★★  70% ← Overwhelming positive<br>★★★★☆  20%<br>★★★☆☆   5%<br>★★☆☆☆   3%<br>★☆☆☆☆   2%</pre><pre>RED FLAG:<br>★★★★★  45% ← Mixed with lots of failures<br>★★★★☆  10%<br>★★★☆☆   5%<br>★★☆☆☆  15%<br>★☆☆☆☆  25% ← Too many 1-stars means quality control issues</pre><p><strong>Step 2: Read the 1-star AND 3-star reviews (most honest)</strong></p><p><strong>Ignore these 1-star reviews:</strong></p><ul><li>“Arrived late” (shipping issue, not product)</li><li>“Wrong item sent” (warehouse error)</li><li>“Didn’t read description” (user error)</li></ul><p><strong>Pay attention to these:</strong></p><ul><li><strong>“Burned out after 1 hour”</strong> ⚠️ Major red flag</li><li><strong>“Inconsistent performance”</strong> ⚠️ Quality issue</li><li><strong>“Overheats easily”</strong> ⚠️ Design problem</li><li><strong>“Doesn’t match datasheet”</strong> ⚠️ Knockoff chip</li></ul><p><strong>3-star reviews are golden:</strong></p><ul><li>“Works but gets hot” → Thermal management issue</li><li>“Functions okay for light loads” → Not suitable for your motors</li><li>“You get what you pay for” → Exactly</li></ul><p><strong>Step 3: Search Reddit for real user experiences</strong></p><p>Search: <strong>“[component name] vs alternatives reddit”</strong></p><p>Example: “L298N vs TB6612 reddit”</p><p>Real users share:</p><ul><li>Long-term reliability</li><li>Hidden issues not in marketing</li><li>Better alternatives</li><li>Compatibility problems</li></ul><p><strong>Step 4: Apply the “Middle Option” Rule</strong></p><pre>Premium Option:  $25  <br>│ Often overkill for beginners<br>│ Professional-grade features you won&#39;t use<br>│ But will last forever</pre><pre>Mid-Range Option: $10-15  ← The sweet spot for most projects<br>│ Quality components<br>│ Good documentation  <br>│ Reliable performance<br>│ Worth the price</pre><pre>Budget Option:   $3<br>│ Tempting savings<br>│ High failure rate<br>│ Poor support<br>│ Actually costs MORE when it fails</pre><p><strong>For first projects:</strong> Go mid-range. You save money compared to premium, but avoid the failures of budget.</p><p><strong>Step 5: Check seller reputation</strong></p><ul><li><strong>Amazon:</strong> Prime, fulfilled by Amazon, 90%+ positive seller rating</li><li><strong>AliExpress:</strong> 95%+ rating, 1000+ orders</li><li><strong>Local electronics stores:</strong> Reputable brands (Adafruit, SparkFun, Pololu)</li></ul><h3>My Current Shopping Strategy</h3><p><strong>Critical components</strong> (motor drivers, voltage regulators, sensors):</p><ul><li>Budget: $5–10 per component</li><li>Priority: Reliability and documentation</li><li>Source: Adafruit, SparkFun, or highly-rated Amazon Prime sellers</li><li><strong>Never again:</strong> Random $3 no-name boards</li></ul><p><strong>Consumables</strong> (wires, resistors, LEDs, basic passives):</p><ul><li>Budget: Cheap is totally fine</li><li>Priority: Quantity and variety</li><li>Source: Bulk packs from Amazon/AliExpress</li><li>Example: 600-piece resistor kit for $8 = great deal</li></ul><p><strong>The brain</strong> (Arduino, ESP32, Raspberry Pi):</p><ul><li>Budget: Mid to high range</li><li>Priority: Authentic or quality clones</li><li>Source: Official distributors or verified sellers</li><li><strong>Red flag:</strong> “Arduino-compatible” for $2 (probably terrible)</li></ul><p><strong>Investment breakdown:</strong></p><pre>My original approach (all cheap):<br>4 motors: $8 (2 were bad)<br>Motor driver: $3 (failed)<br>Arduino clone: $5 (worked but flaky)<br>Sensors: $10 (mixed quality)<br>Replacements: $30<br>Total: $56, half didn&#39;t work reliably</pre><pre>My current approach (strategic quality):<br>4 motors: $12 (quality, matched set)<br>Motor driver: $12 (SparkFun, works perfectly)<br>Arduino clone: $15 (well-reviewed, stable)<br>Sensors: $15 (Adafruit, reliable)<br>Total: $54, everything works first time</pre><pre>Saved money AND frustration.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5gaGQwFyXw9rPJXOOntyg.jpeg" /></figure><h3>Mistake #3: Assembling Everything Before Testing Components</h3><h3>What I Did</h3><p>Parts arrived! Excitement level: maximum!</p><p>I immediately spent an entire Saturday afternoon:</p><ul><li>Mounting motors to chassis</li><li>Securing Arduino with zip ties</li><li>Hot gluing the motor driver in place</li><li>Routing all wires neatly</li><li>Wrapping everything in electrical tape</li><li>Adding a custom-cut battery holder</li></ul><p>Beautiful. Professional. Permanent.</p><p>Then I powered it on for the first time.</p><p><strong>Nothing worked.</strong></p><h3>The Damage Report</h3><p><strong>Time wasted assembling:</strong> 1 hour<br> <strong>Time wasted disassembling:</strong> 3 hours (hot glue is REALLY permanent)<br> <strong>Components damaged during disassembly:</strong> 1 IR sensor (ripped the wire)<br> <strong>Replacement sensor cost:</strong> $3<br> <strong>Dignity remaining:</strong> Minimal<br> <strong>Lessons about hot glue:</strong> Many</p><h3>The Nightmare Unfolds</h3><p><strong>The problem:</strong> With everything assembled, I had no idea what was broken.</p><p>Could be:</p><ul><li>Motors (any of the 4 could be faulty)</li><li>Motor driver (could be bad)</li><li>Sensor (might be broken)</li><li>Wiring (might be wrong)</li><li>Code (might have bugs)</li><li>Power supply (might be insufficient)</li><li>Arduino (could be damaged)</li></ul><p><strong>To check each possibility, I had to:</strong></p><ol><li><strong>Unsolder connections</strong> (some I’d soldered “for reliability”)</li><li><strong>Remove hot glue</strong> (with a heat gun, carefully, slowly)</li><li><strong>Unwrap electrical tape</strong> (destroying the neat cable management)</li><li><strong>Remove zip ties</strong> (cutting them, buying more later)</li><li><strong>Test component</strong> (finally!)</li><li><strong>Reassemble</strong> (if component was fine)</li><li><strong>Repeat</strong> (for next suspect)</li></ol><p><strong>3 hours later:</strong> Found the problem. One motor was dead on arrival. A $2 component. Could have tested it in 30 seconds BEFORE gluing everything.</p><h3>The Real Problem</h3><p><strong>I treated assembly as the first step instead of the last step.</strong></p><p>The correct order is:</p><ol><li>Test components individually ✓</li><li>Test components together ✓</li><li>Verify everything works ✓</li><li>THEN make it permanent</li></ol><p>I did:</p><ol><li>Skip all testing</li><li>Make everything permanent immediately</li><li>Discover problems</li><li>Disassemble everything</li><li>Test finally</li><li>Reassemble</li></ol><p><strong>4x the work. 10x the frustration.</strong></p><h3>The Solution That Actually Works</h3><p><strong>The “Breadboard First, Permanent Last” Protocol</strong></p><p><strong>Phase 1: Individual Component Testing (Day 1)</strong></p><p>Test EVERY component alone on breadboard before connecting anything else:</p><p><strong>Motor test:</strong></p><p>arduino</p><pre>// Test each motor individually<br>// Connect to 3-6V power supply<br>// Does it spin?<br>// Does it draw reasonable current? (check with multimeter)<br>// Does it run smooth or make grinding noises?<br>// Mark working motors vs. dead ones</pre><p><strong>Motor driver test:</strong></p><p>arduino</p><pre>// Connect motor driver only<br>// Apply power<br>// Test each channel with test motor<br>// Check for heating after 5 minutes<br>// Verify all functions: forward, backward, speed control</pre><p><strong>Sensor test:</strong></p><p>arduino</p><pre>// Connect sensor only<br>// Run simple read test<br>void loop() {<br>  Serial.println(digitalRead(sensorPin));<br>  delay(100);<br>}<br>// Does output change when expected?<br>// Is it consistent?<br>// Any false triggers?</pre><p><strong>Power supply test:</strong></p><pre>// Use multimeter<br>// Measure voltage under NO load<br>// Measure voltage under FULL load (all motors running)<br>// If voltage drops more than 10%, power supply insufficient<br>// Check current draw (should be less than supply rating)</pre><p><strong>If ANY component fails here → Replace BEFORE continuing.</strong></p><p><strong>Investment:</strong> 30–60 minutes<br> <strong>Payoff:</strong> Finding problems when they’re easy to fix</p><p><strong>Phase 2: Integrated Testing (Day 2–3)</strong></p><p>Now connect everything on breadboard (or temporarily mounted):</p><p><strong>Basic movement test:</strong></p><p>arduino</p><pre>// Test all movements WITHOUT final assembly<br>moveForward();   // All motors spin correctly?<br>delay(1000);<br>moveBackward();  // Reverse works?<br>delay(1000);<br>turnLeft();      // Turn works?<br>delay(1000);<br>turnRight();     // Other direction works?<br>delay(1000);<br>stopMotors();    // All motors stop?</pre><p><strong>Sensor integration test:</strong></p><p>arduino</p><pre>// Edge detection test<br>// Hold sensor over edge of table<br>// Does robot stop?<br>// Does it back up correctly?<br>// Does turn work?<br>// Does it resume forward motion?</pre><p><strong>Extended runtime test:</strong></p><pre>// Run robot for 10-15 minutes continuously<br>// Check for:<br>//   - Overheating components (touch test)<br>//   - Battery voltage drop (multimeter)<br>//   - Consistent behavior<br>//   - Any intermittent issues</pre><p><strong>Stress test:</strong></p><pre>// Run robot for 30 minutes<br>// On different surfaces<br>// Different battery levels<br>// Different temperatures<br>// Does it still work reliably?</pre><p><strong>If ANY test fails → Debug NOW while everything is accessible.</strong></p><p><strong>Phase 3: Permanent Assembly (Day 4 — ONLY after everything works)</strong></p><p><strong>Now and ONLY now:</strong></p><p><strong>Rules for permanent assembly:</strong></p><ol><li>✅ Use screws, not glue (removable if you need to access later)</li><li>✅ Keep test points accessible (easy to probe with multimeter)</li><li>✅ Use connectors, not soldered joints (for easy replacement)</li><li>✅ Test after EACH assembly step (catch problems immediately)</li><li>✅ Leave critical connections accessible (motor driver, power input)</li><li>✅ Document any changes (wiring might shift during assembly)</li></ol><p><strong>Assembly sequence:</strong></p><ol><li>Mount components loosely</li><li>Test → Still works?</li><li>Tighten securely</li><li>Test → Still works?</li><li>Route wiring</li><li>Test → Still works?</li><li>Secure wiring</li><li>Test → Still works?</li><li>Final functionality test</li><li>Extended runtime test</li></ol><p><strong>If something stops working:</strong> You know exactly what step caused it.</p><h3>What I Do Now</h3><p><strong>My component testing checklist:</strong></p><pre>□ Individual Tests (breadboard)<br>  □ Each motor spins smoothly<br>  □ Motor driver controls all channels<br>  □ All sensors respond correctly<br>  □ Power supply stable under load<br>  □ Battery voltage measured and logged</pre><pre>□ Integration Tests (breadboard)<br>  □ Basic movements work (F/B/L/R)<br>  □ Sensor triggers correctly<br>  □ Edge avoidance sequence works<br>  □ 10-minute runtime successful<br>  □ No overheating detected</pre><pre>□ Extended Testing (breadboard)<br>  □ 30-minute stress test passed<br>  □ Different surfaces tested<br>  □ Battery low-voltage behavior checked<br>  □ Edge cases tested (corners, etc.)</pre><pre>□ Assembly (only after ALL tests pass)<br>  □ Components mounted securely<br>  □ Test after each assembly step<br>  □ All connections accessible<br>  □ Documentation updated with any changes<br>  □ Final 15-minute validation test</pre><pre>□ Deployment<br>  □ User acceptance test<br>  □ Demo to friend/family<br>  □ Video recorded for documentation<br>  □ Project marked &quot;complete&quot;</pre><p><strong>Time invested in systematic testing:</strong> 2–3 hours<br> <strong>Time saved not disassembling hot-glued assemblies:</strong> 10+ hours<br> <strong>Components saved from assembly damage:</strong> Priceless</p><h3>Mistake #4: Powering Motors Directly from Arduino</h3><h3>What I Did</h3><p>I looked at my circuit:</p><ul><li>Arduino has a 5V pin ✓</li><li>Motors need power ✓</li><li>Just connect motors to 5V pin ✓</li></ul><p>“Why do I need a separate power supply? This is simpler!”</p><p><strong>Narrator:</strong> <em>This was not simpler. This was how Arduinos die.</em></p><h3>The Damage Report</h3><p><strong>Components fried:</strong> 1 Arduino Uno<br> <strong>Cost of Arduino:</strong> $10<br> <strong>Shipping for replacement:</strong> $2 (express, because I was impatient)<br> <strong>Time waiting:</strong> 3 days<br> <strong>Understanding of electrical fundamentals:</strong> Significantly improved<br> <strong>Total financial lesson:</strong> $12</p><h3>What Killed My Arduino</h3><p><strong>The death spiral:</strong></p><ol><li><strong>Connected 4 motors to Arduino 5V pin</strong></li></ol><ul><li>Arduino’s voltage regulator can provide ~400mA safely</li><li>Four DC motors draw ~500mA each at startup (peak current)</li><li>Total draw: 2000mA (5x what Arduino can provide)</li></ul><p><strong>2. Powered it on</strong></p><ul><li>Motors tried to draw full current</li><li>Arduino voltage regulator overloaded</li><li>Voltage dropped (brownout)</li></ul><p><strong>3. Arduino started acting weird</strong></p><ul><li>Random resets</li><li>Erratic behavior</li><li>Code not executing properly</li><li>I thought: “Must be a software bug!”</li></ul><p><strong>4. Kept testing, trying to “fix the code”</strong></p><ul><li>Each power cycle stressed the regulator more</li><li>Getting hotter each time</li><li>I could feel the heat but thought: “Electronics get warm, right?”</li></ul><p><strong>5. The final moment</strong></p><ul><li>Small spark</li><li>Burning smell</li><li>Arduino completely dead</li><li>Power LED wouldn’t even light up</li><li>Multimeter test: Shorted voltage regulator</li></ul><p><strong>Cause of death:</strong> Trying to pull 2000mA through a 400mA regulator.</p><p><strong>My mistake:</strong> Confusing voltage (5V) with current capacity (400mA max).</p><h3>The Real Problem</h3><p><strong>I didn’t understand the difference between voltage and current.</strong></p><p><strong>Voltage</strong> = Electric pressure (measured in Volts)</p><ul><li>Like water pressure in a pipe</li><li>5V is 5V whether from a tiny Arduino pin or a huge power supply</li></ul><p><strong>Current</strong> = Electric flow (measured in Amps/milliamps)</p><ul><li>Like water flow rate in that pipe</li><li>Small pipe (Arduino) can only provide small flow</li><li>Big pipe (proper power supply) can provide big flow</li></ul><p><strong>Motors need both:</strong></p><ul><li>5V (voltage) — dictates speed</li><li>Up to 2000mA (current) — the actual power they draw</li></ul><p><strong>Arduino can provide:</strong></p><ul><li>5V (voltage) ✓</li><li>Only 400mA (current) ✗</li></ul><p><strong>Result:</strong> Voltage regulator tried to provide more current than it was designed for → overheated → died.</p><h3>The Solution That Actually Works</h3><p><strong>The Power Budget Method</strong></p><p><strong>Step 1: Calculate total current needed</strong></p><pre>OOPSSTOPPER POWER BUDGET</pre><pre>Component          Typical Draw    Peak Draw<br>──────────────────────────────────────────────<br>Arduino Uno        50 mA           50 mA<br>IR Sensor          20 mA           20 mA  <br>Motor 1 (running)  300 mA          500 mA<br>Motor 2 (running)  300 mA          500 mA<br>Motor 3 (running)  300 mA          500 mA<br>Motor 4 (running)  300 mA          500 mA<br>──────────────────────────────────────────────<br>TOTAL TYPICAL      1270 mA         2070 mA<br>Safety Margin (×1.5)               3105 mA</pre><pre>POWER SUPPLY NEEDED: 3.5A - 4A minimum</pre><p><strong>Step 2: Separate power paths (critical!)</strong></p><pre>CORRECT POWER DISTRIBUTION:</pre><pre>Battery (7.4V, 3A capable)<br>    │<br>    ├─→ Arduino Vin ──→ [Internal Regulator] ──→ 5V ──→ IR Sensor<br>    │                                                        (20mA, safe!)<br>    │<br>    └─→ Motor Driver 12V input ──→ Motors (2000mA)<br>                                   (bypasses Arduino completely!)</pre><pre>Common Ground: Arduino GND ←→ Motor Driver GND ←→ Battery GND<br>               (CRITICAL - all grounds must connect!)</pre><p><strong>Key principle:</strong></p><ul><li><strong>Low-power logic</strong> (Arduino, sensors) → Arduino’s 5V regulator</li><li><strong>High-power loads</strong> (motors) → Separate power supply</li></ul><p><strong>Step 3: Add protection components</strong></p><pre>Essential protections:</pre><pre>1. Fuse (3A): Protects against shorts<br>   - Between battery and circuit<br>   - Blows if current exceeds safe limit<br>   - Saves everything else</pre><pre>2. Capacitor (1000µF): Smooths power spikes<br>   - Across motor driver power input<br>   - Handles motor startup surges<br>   - Prevents voltage dips</pre><pre>3. Diodes (1N4007): Protects against back-EMF<br>   - Across each motor terminal<br>   - Motors create reverse voltage when stopping<br>   - Without diodes, can damage driver</pre><p><strong>Step 4: Test power supply under load</strong></p><pre>Multimeter test procedure:</pre><pre>1. Measure battery voltage (no load)<br>   Expected: 7.4V<br>   My reading: 7.42V ✓</pre><pre>2. Connect all components (don&#39;t turn on yet)</pre><pre>3. Turn on, motors stationary<br>   Expected: ~7.3V (slight drop acceptable)<br>   My reading: 7.35V ✓</pre><pre>4. Run all motors full speed<br>   Expected: &gt;6.5V (less than 15% drop)<br>   My reading: 7.1V ✓ (only 4% drop, excellent!)</pre><pre>If voltage drops &gt;15%: Power supply insufficient or high resistance in wiring</pre><h3>What I Do Now</h3><p><strong>My power supply checklist:</strong></p><pre>Before Connecting Power:<br>□ Total current calculated (with safety margin)<br>□ Power supply rating exceeds requirement<br>□ Separate power paths planned (logic vs. motors)<br>□ Common ground verified in diagram<br>□ Protection components added (fuse, caps, diodes)<br>□ Power supply test plan created</pre><pre>During Assembly:<br>□ Fuse installed first (before anything else!)<br>□ Common ground connections made<br>□ Power paths verified with multimeter<br>□ No direct motor→Arduino connections<br>□ Capacitors placed close to motor driver</pre><pre>Before First Power-On:<br>□ Visual inspection (no shorts, no loose wires)<br>□ Continuity test (multimeter beep test)<br>□ Voltage test (measure at all power points)<br>□ Current limit set on power supply (if bench supply)</pre><pre>After Power-On:<br>□ Voltage measured at Arduino (should be ~5V)<br>□ Voltage measured at motors (should match supply)<br>□ Current draw monitored (should match calculations)<br>□ Temperature check after 5 min (nothing too hot)<br>□ Extended test (15 minutes, monitor voltage)</pre><p><strong>My OopsStopper v1.0 final power setup:</strong></p><pre>Power Source: 2S Lithium-Ion (7.4V, 2200mAh, 3A max)<br>Protection: 3A automotive fuse<br>Distribution:<br>  ├─ Arduino Vin (powers Arduino 5V regulator)<br>  │    └─ IR Sensor (from Arduino 5V pin, only 20mA)<br>  └─ L298N 12V input (powers motors directly)<br>       └─ 1000µF capacitor across input<br>       └─ Diodes across motor terminals</pre><pre>Common Ground: ALL grounds connected together</pre><pre>Result: <br>- No more dead Arduinos ✓<br>- Stable operation ✓<br>- 45-minute runtime ✓<br>- No voltage brownouts ✓<br>- Perfect reliability ✓</pre><p><strong>Investment in proper power design:</strong> 1–2 hours learning + $5 in protection components<br> <strong>Saved:</strong> $15+ Arduino replacements, countless hours debugging brownout issues</p><h3>Mistake #5: Writing Code Without Comments or Structure</h3><h3>What I Did</h3><p>I sat down and wrote the robot control code in one focused session. 150 lines of pure, concentrated logic. No comments. No structure. Just raw functionality.</p><p><strong>It worked!</strong> Robot moved, avoided edges, everything perfect.</p><p>I felt like a genius.</p><p>Then I didn’t touch the project for a week.</p><p>When I came back to add a new feature? <strong>I had absolutely no idea what my own code did.</strong></p><h3>The Damage Report</h3><p><strong>Time wasted re-understanding code:</strong> 4–5 hours<br> <strong>Bugs introduced while modifying:</strong> 3 (in code that was working!)<br> <strong>Features abandoned:</strong> 2 (too risky to modify)<br> <strong>Future productivity:</strong> Nearly zero<br> <strong>Relationship with past-me:</strong> Strained</p><h3>The Conversation With Myself</h3><p><strong>Week 1 (writing code):</strong></p><pre>Me: *typing furiously*<br>Me: This is brilliant! So elegant! So clean!<br>Me: I&#39;ll remember exactly what this does.<br>Me: Comments would just clutter this masterpiece.</pre><p><strong>Week 2 (trying to modify):</strong></p><pre>Me: *reading code*<br>Me: What the hell does this function do?<br>Me: Why did I use variable &#39;x&#39; here?<br>Me: What is this magic number &#39;800&#39;?<br>Me: Who wrote this garbage?<br>Me: Oh. I did.</pre><p><strong>Week 3 (attempting to add feature):</strong></p><pre>Me: If I change this... does that break that?<br>Me: What happens if I modify this delay?<br>Me: Why does this even work?<br>Me: You know what, I&#39;ll just rewrite the whole thing.</pre><p><strong>Week 4 (giving up):</strong></p><pre>Me: This is fine. It works. I&#39;ll never touch it again.<br>Future Me: I hate Past Me.</pre><h3>The Real Problem</h3><p><strong>My original code looked like this:</strong></p><p>arduino</p><pre>void loop() {<br>  if(digitalRead(2)==0){<br>    digitalWrite(6,LOW);<br>    digitalWrite(7,LOW);<br>    digitalWrite(8,LOW);<br>    digitalWrite(9,LOW);<br>    delay(800);<br>    digitalWrite(6,LOW);<br>    digitalWrite(7,HIGH);<br>    digitalWrite(8,HIGH);<br>    digitalWrite(9,LOW);<br>    delay(600);<br>  } else {<br>    digitalWrite(6,HIGH);<br>    digitalWrite(7,LOW);<br>    digitalWrite(8,HIGH);<br>    digitalWrite(9,LOW);<br>  }<br>}</pre><p><strong>Questions I couldn’t answer a week later:</strong></p><ul><li>What is pin 2? (IR sensor, but code doesn’t say)</li><li>Why LOW on pin 2 triggers action? (sensor returns LOW for edge)</li><li>What do pins 6–9 control? (motors, but which is which?)</li><li>Why delay 800ms then 600ms? (backup time then turn time)</li><li>Which motor is which? (no idea without testing)</li></ul><p><strong>To make ANY change, I’d have to:</strong></p><ol><li>Re-read entire code</li><li>Trace every function</li><li>Test on actual hardware</li><li>Hope I don’t break something</li><li>Probably rewrite from scratch</li></ol><h3>The Solution That Actually Works</h3><p><strong>The “Code for Future You” Standard</strong></p><p><strong>Refactored version of the same code:</strong></p><p>arduino</p><pre>/*<br> * OopsStopper v1.0 - Edge Detection Robot<br> * <br> * DESCRIPTION:<br> * Autonomous robot that detects table edges using IR sensor<br> * and prevents falling through edge avoidance maneuvers<br> * <br> * HARDWARE:<br> * - Arduino Uno<br> * - L298N Motor Driver<br> * - IR Sensor (digital output, active LOW on edge detection)<br> * - 4x DC Motors (2 left, 2 right)<br> * <br> */</pre><pre>// ===== PIN CONFIGURATION =====<br>// IR Sensor<br>const int IR_SENSOR_PIN = 2;      // Digital input, active LOW when edge detected</pre><pre>// Motor Driver A (Right Side Motors)<br>const int MOTOR_A_SPEED = 5;      // PWM pin for speed control (ENA)<br>const int MOTOR_A_DIR1 = 6;       // Direction control pin 1 (IN1)<br>const int MOTOR_A_DIR2 = 7;       // Direction control pin 2 (IN2)</pre><pre>// Motor Driver B (Left Side Motors)  <br>const int MOTOR_B_SPEED = 10;     // PWM pin for speed control (ENB)<br>const int MOTOR_B_DIR1 = 8;       // Direction control pin 1 (IN3)<br>const int MOTOR_B_DIR2 = 9;       // Direction control pin 2 (IN4)</pre><pre>// ===== TIMING CONSTANTS =====<br>const int MOTOR_SPEED = 150;      // PWM value 0-255 (150 = ~60% speed)<br>const int BACKUP_DURATION = 800;  // Milliseconds to back up from edge<br>const int TURN_DURATION = 600;    // Milliseconds to turn (~90 degrees)</pre><pre>// ===== SENSOR READING =====<br>/**<br> * Check if table edge has been detected<br> * <br> * @return true if edge detected, false if surface present<br> * <br> * NOTE: IR sensor returns LOW when edge detected (no reflection)<br> *       and HIGH when surface present (reflection detected)<br> */<br>bool isEdgeDetected() {<br>  return (digitalRead(IR_SENSOR_PIN) == LOW);<br>}</pre><pre>// ===== MOTOR CONTROL FUNCTIONS =====<br>/**<br> * Stop all motors immediately<br> * Used before changing direction to prevent motor strain<br> */<br>void stopMotors() {<br>  digitalWrite(MOTOR_A_DIR1, LOW);<br>  digitalWrite(MOTOR_A_DIR2, LOW);<br>  digitalWrite(MOTOR_B_DIR1, LOW);<br>  digitalWrite(MOTOR_B_DIR2, LOW);<br>}</pre><pre>/**<br> * Move robot forward at set speed<br> * Both motor groups rotate in forward direction<br> */<br>void moveForward() {<br>  // Right motors forward<br>  digitalWrite(MOTOR_A_DIR1, HIGH);<br>  digitalWrite(MOTOR_A_DIR2, LOW);<br>  <br>  // Left motors forward  <br>  digitalWrite(MOTOR_B_DIR1, HIGH);<br>  digitalWrite(MOTOR_B_DIR2, LOW);<br>  <br>  // Set speed for both motor groups<br>  analogWrite(MOTOR_A_SPEED, MOTOR_SPEED);<br>  analogWrite(MOTOR_B_SPEED, MOTOR_SPEED);<br>}</pre><pre>/**<br> * Move robot backward at set speed<br> * Both motor groups rotate in reverse direction<br> */<br>void moveBackward() {<br>  // Right motors backward<br>  digitalWrite(MOTOR_A_DIR1, LOW);<br>  digitalWrite(MOTOR_A_DIR2, HIGH);<br>  <br>  // Left motors backward<br>  digitalWrite(MOTOR_B_DIR1, LOW);<br>  digitalWrite(MOTOR_B_DIR2, HIGH);<br>  <br>  // Set speed<br>  analogWrite(MOTOR_A_SPEED, MOTOR_SPEED);<br>  analogWrite(MOTOR_B_SPEED, MOTOR_SPEED);<br>}</pre><pre>/**<br> * Rotate robot to the right (clockwise)<br> * Right motors backward, left motors forward<br> */<br>void turnRight() {<br>  // Right motors backward<br>  digitalWrite(MOTOR_A_DIR1, LOW);<br>  digitalWrite(MOTOR_A_DIR2, HIGH);<br>  <br>  // Left motors forward<br>  digitalWrite(MOTOR_B_DIR1, HIGH);<br>  digitalWrite(MOTOR_B_DIR2, LOW);<br>  <br>  // Set speed<br>  analogWrite(MOTOR_A_SPEED, MOTOR_SPEED);<br>  analogWrite(MOTOR_B_SPEED, MOTOR_SPEED);<br>}</pre><pre>// ===== EDGE AVOIDANCE BEHAVIOR =====<br>/**<br> * Execute complete edge avoidance sequence<br> * <br> * SEQUENCE:<br> * 1. Stop immediately (prevent falling)<br> * 2. Back up for BACKUP_DURATION (clear the edge)<br> * 3. Stop briefly (prepare for turn)<br> * 4. Turn right for TURN_DURATION (face new direction)<br> * 5. Stop briefly (stabilize before resuming)<br> * <br> * NOTE: Timing values determined through testing on standard table<br> *       BACKUP_DURATION ensures robot clears edge completely<br> *       TURN_DURATION provides approximately 90-degree rotation<br> */<br>void avoidEdge() {<br>  stopMotors();<br>  delay(100);                    // Brief pause for stability<br>  <br>  moveBackward();<br>  delay(BACKUP_DURATION);        // Back away from detected edge<br>  <br>  stopMotors();  <br>  delay(100);                    // Brief pause before turn<br>  <br>  turnRight();<br>  delay(TURN_DURATION);          // Rotate to new direction<br>  <br>  stopMotors();<br>  delay(100);                    // Brief pause before resuming forward<br>}</pre><pre>// ===== MAIN CONTROL LOOP =====<br>/**<br> * Main robot control loop<br> * <br> * BEHAVIOR:<br> * - Continuously moves forward while surface is detected<br> * - When edge is detected, executes avoidance maneuver<br> * - Resumes forward movement after avoidance complete<br> * <br> * LOOP FREQUENCY: Runs as fast as possible (~hundreds per second)<br> * Sensor response time: &lt;50ms ensures timely edge detection<br> */<br>void loop() {<br>  if (isEdgeDetected()) {<br>    // Edge detected! Execute safety maneuver<br>    avoidEdge();<br>  } else {<br>    // Surface present - safe to continue forward<br>    moveForward();<br>  }<br>}</pre><pre>// ===== INITIALIZATION =====<br>void setup() {<br>  // Configure motor control pins as outputs<br>  pinMode(MOTOR_A_SPEED, OUTPUT);<br>  pinMode(MOTOR_A_DIR1, OUTPUT);<br>  pinMode(MOTOR_A_DIR2, OUTPUT);<br>  pinMode(MOTOR_B_SPEED, OUTPUT);<br>  pinMode(MOTOR_B_DIR1, OUTPUT);<br>  pinMode(MOTOR_B_DIR2, OUTPUT);<br>  <br>  // Configure sensor pin as input<br>  pinMode(IR_SENSOR_PIN, INPUT);<br>  <br>  // Ensure motors start stopped<br>  stopMotors();<br>  <br>  // Brief delay before starting main loop<br>  delay(1000);<br>}</pre><p><strong>Now when I return to this code:</strong></p><ul><li>✓ I know what every pin does (clear names and comments)</li><li>✓ I understand the timing (constants explained)</li><li>✓ I can modify safely (functions isolated)</li><li>✓ I can test incrementally (each function testable alone)</li><li>✓ I can explain to others (documentation built-in)</li><li>✓ I can build on it (structure is extensible)</li></ul><h3>The Commenting Strategy</h3><p><strong>Good comments explain WHY, not WHAT:</strong></p><p>arduino</p><pre>// ❌ BAD: States the obvious<br>delay(800);  // Wait 800 milliseconds</pre><pre>// ✅ GOOD: Explains the reasoning  <br>delay(800);  // Back up for 800ms - tested distance to clear table edge</pre><p><strong>Structure your comments:</strong></p><p>arduino</p><pre>// ===== SECTION HEADERS =====<br>// Make code scannable at a glance</pre><pre>// ----- Subsection Headers -----<br>// For groups of related code</pre><pre>// Single line comments for specific lines<br>// When the reason isn&#39;t immediately obvious</pre><p><strong>Document intent, not implementation:</strong></p><p>arduino</p><pre>// ❌ BAD: <br>// Set pin 6 high and pin 7 low<br>digitalWrite(MOTOR_A_DIR1, HIGH);<br>digitalWrite(MOTOR_A_DIR2, LOW);</pre><pre>// ✅ GOOD:<br>// Rotate right motors forward<br>digitalWrite(MOTOR_A_DIR1, HIGH);<br>digitalWrite(MOTOR_A_DIR2, LOW);</pre><h3>What I Do Now</h3><p><strong>My code documentation standard:</strong></p><p><strong>1. File header (always):</strong></p><p>arduino</p><pre>/*<br> * PROJECT NAME - Brief description<br> * <br> * PURPOSE: What problem does this solve?<br> * HARDWARE: What components are used?<br> * AUTHOR: Your name<br> * DATE: When created<br> * VERSION: Track changes<br> * <br> * NOTES: Any important information for future you<br> */</pre><p><strong>2. Meaningful names (no abbreviations unless standard):</strong></p><p>arduino</p><pre>// ❌ BAD<br>int x = 800;<br>int y = 600;<br>int spd = 150;</pre><pre>// ✅ GOOD  <br>int backupDuration = 800;     // milliseconds<br>int turnDuration = 600;        // milliseconds<br>int motorSpeed = 150;          // PWM value 0-255</pre><p><strong>3. Function documentation (for non-obvious functions):</strong></p><p>arduino</p><pre>/**<br> * Brief description of what function does<br> * <br> * @param paramName - what this parameter means<br> * @return what gets returned<br> * <br> * NOTES: Any gotchas or important details<br> */<br>void functionName(int paramName) {<br>  // implementation<br>}</pre><p><strong>4. Explain magic numbers:</strong></p><p>arduino</p><pre>// ❌ BAD<br>delay(800);</pre><pre>// ✅ GOOD<br>const int BACKUP_DURATION = 800;  // Tested distance to clear edge<br>delay(BACKUP_DURATION);</pre><p><strong>5. TODO comments for future improvements:</strong></p><p>arduino</p><pre>// TODO: Add speed ramping for smoother starts<br>// TODO: Implement battery voltage monitoring  <br>// FIXME: Turn duration varies by surface friction<br>// NOTE: This delay is critical - don&#39;t remove!</pre><p><strong>Time spent documenting code:</strong> 30–45 minutes per project<br> <strong>Time saved when returning to code:</strong> Hours every single time<br> <strong>Code reusability:</strong> 100% (can understand and modify anytime)<br> <strong>Mental load:</strong> Nearly zero (code explains itself)</p><h3>The Bonus Mistake: Perfectionism Paralysis (Almost Didn’t Start)</h3><p>This wasn’t in my original five, but it nearly prevented all the other mistakes from happening — because I almost didn’t start at all.</p><h3>What I Almost Did</h3><p>Before building OopsStopper, I spent two weeks:</p><ul><li>Reading every Arduino tutorial I could find</li><li>Watching every robotics video on YouTube</li><li>Planning the “perfect” first project</li><li>Overthinking every component choice</li><li>Afraid to actually buy parts (“What if I choose wrong?”)</li><li>Afraid to start building (“What if I mess up?”)</li></ul><h3>What Finally Got Me Started</h3><p>A comment I read on r/arduino:</p><p><strong>“Your first project should be bad. It should barely work. It should teach you things. Just make it exist.”</strong></p><p>That permission to be imperfect? <strong>Game changer.</strong></p><p>I stopped planning and started building.</p><h3>What I Actually Learned</h3><p><strong>Done beats perfect. Every single time.</strong></p><p>OopsStopper v1.0 has problems:</p><ul><li>Turns aren’t always exactly 90 degrees</li><li>Gets confused by dark shadows sometimes</li><li>Battery life could be better</li><li>Wiring could be neater</li><li>Code could be more efficient</li></ul><p><strong>But:</strong></p><ul><li>It exists ✓</li><li>It works ✓</li><li>I learned from building it ✓</li><li>I can now build v2.0 better ✓</li><li>I have experience instead of theory ✓</li></ul><p><strong>The insight:</strong> Perfect planning doesn’t create perfect projects. Building and iterating does.</p><p><strong>v1.0 taught me what to do in v2.0:</strong></p><ul><li>Use ESP32 for better processing</li><li>Add WiFi for remote control</li><li>Implement proper state machine</li><li>Better power management</li><li>More robust edge detection</li></ul><p><strong>Could I have planned all this upfront?</strong> No. I needed to build v1.0 to understand what v2.0 should be.</p><p><strong>Start. Fail. Learn. Iterate.</strong></p><p>That’s the entire game.</p><h3>The Receipt: What My Education Actually Cost</h3><p>Let’s be completely honest about the financial damage:</p><pre>MISTAKES &amp; REPLACEMENTS<br>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━<br>Fried motor driver (Mistake #1)         $5<br>Replacement motor driver                $8<br>Dead Arduino (Mistake #4)              $20<br>Replacement Arduino                    $20<br>Cheap motor driver that failed (#2)    $3<br>Quality replacement driver             $20<br>Wrong components ordered               $15<br>Damaged IR sensor during disassembly   $9<br>Express shipping (impatience tax)      $10<br>&quot;Just in case&quot; backup parts            $10<br>───────────────────────────────────────────<br>TOTAL MISTAKES:                       $120</pre><pre>WORKING ROBOT COST<br>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━<br>Arduino Uno                            $25<br>L298N Motor Driver (quality)           $12<br>4× DC Motors                            $8<br>IR Sensor                               $3<br>Battery pack                            $5<br>Chassis &amp; wheels                        $8<br>Wires, connectors, misc                 $4<br>───────────────────────────────────────────<br>WORKING ROBOT:                         $45</pre><pre>═══════════════════════════════════════════<br>TOTAL INVESTMENT:                     $165<br>═══════════════════════════════════════════</pre><p><strong>But here’s what makes it worthwhile:</strong></p><p>Those $120 in mistakes taught me:</p><ul><li>✓ How to read datasheets properly</li><li>✓ How to calculate power requirements</li><li>✓ How to test systematically</li><li>✓ How to document everything</li><li>✓ How to debug hardware issues</li><li>✓ How to respect electrical limits</li><li>✓ How to choose quality components</li><li>✓ How to structure code properly</li></ul><p><strong>That knowledge is permanent.</strong></p><p><strong>The next robot?</strong></p><ul><li>Cost: $25 (just $5 more than “planned” budget)</li><li>Failed components: Zero</li><li>Time from parts to working: 2 days</li><li>Worked perfectly first try</li></ul><p><strong>ROI on the education:</strong> Massive.</p><p><strong>Would I pay $131 again for this knowledge?</strong> Absolutely.</p><p>But would I like to save you that money? Even more absolutely.</p><h3>Your Action Plan: Avoid These Mistakes From Day One</h3><p><strong>Before Starting Any Robot Project:</strong></p><h3>Week -1: Planning Phase</h3><pre>Documentation:<br>□ Create wiring diagram (Fritzing/Tinkercad)<br>□ Make pin assignment table<br>□ Calculate power requirements<br>□ Check all calculations with 1.5× safety margin</pre><pre>Component Selection:<br>□ Research each critical component (5-minute method)<br>□ Read 1-star and 3-star reviews<br>□ Search Reddit for real experiences<br>□ Choose mid-range quality (not cheapest)<br>□ Order backup of critical components</pre><pre>Project Setup:<br>□ Create project folder<br>□ Set up notebook (physical or digital)<br>□ Prepare documentation template<br>□ Set up version control (GitHub)</pre><h3>Week 0: Preparation</h3><pre>Testing Setup:<br>□ Breadboard ready<br>□ Multimeter charged<br>□ Power supply tested<br>□ Test leads organized</pre><pre>Individual Component Testing:<br>□ Test each motor individually<br>□ Test motor driver with one motor<br>□ Test sensor in target environment  <br>□ Test power supply under full load<br>□ Document test results</pre><pre>Code Structure:<br>□ Plan function structure<br>□ Set up constants and pin definitions<br>□ Write function documentation first<br>□ Plan comment strategy</pre><h3>Week 1: Building</h3><pre>Assembly:<br>□ Follow wiring diagram exactly<br>□ Test after EACH connection<br>□ Take photos at each stage<br>□ Use removable fasteners (screws, not glue)<br>□ Keep test points accessible</pre><pre>Coding:<br>□ Write comments AS you code<br>□ Use meaningful variable names<br>□ Create functions for repeated code<br>□ Test each function individually<br>□ Document any deviations from plan</pre><pre>Testing:<br>□ Individual function tests<br>□ Integration tests<br>□ Extended runtime test (15+ minutes)<br>□ Edge case testing<br>□ Stress testing</pre><h3>Week 2: Finalization</h3><pre>Final Assembly:<br>□ Everything works on breadboard first<br>□ Permanent assembly only after full testing<br>□ Test after each assembly step<br>□ Document any final changes</pre><pre>Documentation:<br>□ Final wiring diagram with any changes<br>□ Code comments complete and accurate<br>□ README.md with full project description<br>□ Known issues documented<br>□ Future improvements noted</pre><pre>Validation:<br>□ User acceptance test (show someone else)<br>□ Video documentation<br>□ Photo documentation<br>□ Project marked complete<br>□ Lessons learned documented</pre><h3>Resources That Saved Me (After The Mistakes)</h3><p><strong>When I got stuck:</strong></p><ul><li><strong>Arduino Forum</strong> — Surprisingly helpful community, search before asking</li><li><strong>r/arduino subreddit</strong> — Great for debugging, post with details</li><li><strong>r/AskElectronics</strong> — For power supply and electrical questions</li><li><strong>Random Nerd Tutorials</strong> — ESP32 focused but principles apply to Arduino</li><li><strong>Paul McWhorter YouTube</strong> — Patient, thorough Arduino explanations</li></ul><p><strong>For component research:</strong></p><ul><li><strong>SparkFun product pages</strong> — Educational descriptions, honest about limitations</li><li><strong>Adafruit Learn</strong> — Detailed guides, tested projects</li><li><strong>Component datasheets</strong> — Boring but critical, teaches you to read specs</li><li><strong>EEVblog forums</strong> — Advanced discussions, learn from experts</li></ul><p><strong>For code quality:</strong></p><ul><li><strong>Arduino Style Guide</strong> — Official best practices</li><li><strong>Google C++ Style Guide</strong> — Professional coding standards adapted for Arduino</li><li><strong>GitHub trending Arduino projects</strong> — Learn from well-documented code</li></ul><p><strong>For power calculations:</strong></p><ul><li><strong>Electronics tutorials on All About Circuits</strong> — Free, comprehensive</li><li><strong>SparkFun power supply tutorial</strong> — Practical, beginner-friendly</li><li><strong>Afrotechmods YouTube</strong> — Excellent electrical fundamentals</li></ul><h3>The Series Continues</h3><p><strong>This is Part 3 of my IoT &amp; Robotics journey:</strong></p><p><strong>Part 1:</strong> <a href="https://medium.com/@rafiulislam25/how-i-built-a-robot-thats-afraid-of-heights-my-first-arduino-project-9b0ac7b1b925">https://medium.com/@rafiulislam25/how-i-built-a-robot-thats-afraid-of-heights-my-first-arduino-project-9b0ac7b1b925</a> — The complete OopsStopper build guide, components, code, and construction</p><p><strong>Part 2:</strong> <a href="https://medium.com/@rafiulislam25/esp32-vs-arduino-i-wish-someone-had-told-me-this-before-my-first-iot-project-ccc0fef935ec">https://medium.com/@rafiulislam25/esp32-vs-arduino-i-wish-someone-had-told-me-this-before-my-first-iot-project-ccc0fef935ec</a> — Real comparison after building on both platforms, cost analysis, and decision framework</p><p><strong>Part 3:</strong> You are here! 📍 — The expensive lessons that came from making every possible beginner mistake</p><p><strong>Coming Next:</strong> “Building OopsStopper v2.0 with ESP32 + WiFi Control” — Applying these lessons to create a better robot with remote control, telemetry, and all the improvements v1.0 taught me to add</p><p><strong>Subscribe to follow the journey!</strong></p><h3>One Final Truth</h3><p>If you take nothing else from this 5000+ word confession of failures, remember this:</p><p><strong>Mistakes aren’t setbacks. They’re the curriculum.</strong></p><p>The fried motor driver taught me to respect current ratings.<br> The dead Arduino taught me about power distribution.<br> The spaghetti code taught me about documentation.<br> The bad components taught me about research.<br> The premature assembly taught me about testing.</p><p><strong>Every burned component made the next project better.</strong></p><p>Every hour wasted debugging made me faster at troubleshooting.</p><p>Every dollar spent on replacements taught me to plan ahead.</p><p><strong>None of it was waste. It was all education.</strong></p><p>So go build your project. Make your own mistakes. But maybe — just maybe — avoid the really expensive ones I’ve laid out here.</p><p><strong>Your robot won’t be perfect. That’s not the goal.</strong></p><p>The goal is to make it exist. To learn. To iterate. To get better.</p><p>Because the only real mistake? <strong>Not starting at all.</strong></p><p>Now stop reading and go build something. 🤖</p><p><strong>Questions? Share your mistakes?</strong></p><p>Drop a comment below:</p><ul><li>What was YOUR most expensive learning experience?</li><li>Which mistake do you think you’ll make anyway?</li><li>What beginner question are you afraid to ask?</li></ul><p><strong>I’ll answer every single one.</strong> We’re all learning together.</p><p>And if you build something cool (mistakes included), tag me — I genuinely want to see it!</p><p>Happy building, and may your components stay unfried!</p><p><strong>Want the working code?</strong> Check out the <a href="https://github.com/rafiul254/OopsStopper-v1.0">rafiul254/OopsStopper-v1.0: DIY Edge Detection Robot — A table safety bot that navigates surfaces without falling off edges!</a> with full documentation and all the properly-commented code.</p><p><strong>Enjoyed this?</strong> Share it with someone starting their robotics journey. Save them the $120 education.💰</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2cb1819cff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>