<?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 Yasantha Niroshan on Medium]]></title>
        <description><![CDATA[Stories by Yasantha Niroshan on Medium]]></description>
        <link>https://medium.com/@niroshanyi?source=rss-ce5e468ed76c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nHm5OkytH03M8kNs3wBB1g.png</url>
            <title>Stories by Yasantha Niroshan on Medium</title>
            <link>https://medium.com/@niroshanyi?source=rss-ce5e468ed76c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:20:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niroshanyi/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[Pushing a $7 Linux Board to the Limit]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@niroshanyi/pushing-a-7-linux-board-to-the-limit-a840ef04d1d1?source=rss-ce5e468ed76c------2"><img src="https://cdn-images-1.medium.com/max/1400/1*iZ265ENA89uzeMFRzST3fQ.png" width="1400"></a></p><p class="medium-feed-snippet">NPU Inference on the LuckFox Pico RV1103</p><p class="medium-feed-link"><a href="https://medium.com/@niroshanyi/pushing-a-7-linux-board-to-the-limit-a840ef04d1d1?source=rss-ce5e468ed76c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@niroshanyi/pushing-a-7-linux-board-to-the-limit-a840ef04d1d1?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a840ef04d1d1</guid>
            <category><![CDATA[rockchip-rv1103]]></category>
            <category><![CDATA[npu]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tinyml]]></category>
            <category><![CDATA[luckfox-pico]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 02:32:16 GMT</pubDate>
            <atom:updated>2025-12-16T02:32:16.323Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why Do Microcontrollers Get Distracted?]]></title>
            <link>https://blog.roboticgenlabs.com/why-do-microcontrollers-get-distracted-a24502951c1e?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a24502951c1e</guid>
            <category><![CDATA[interrupt]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[roboticgen]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Sun, 04 May 2025 06:44:44 GMT</pubDate>
            <atom:updated>2025-05-04T07:09:21.712Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Case of Interrupts!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fhm0ynXZo-uXSFd_uVTfA.jpeg" /></figure><h3>Meet Our Story Characters</h3><p>Do you know about “Nelum Pokuna” tower ? There are two workers (Raj and Sheela) working there.</p><ul><li><strong>Sheela</strong> — Sheela is cool, calm, and always focused on typing reports at her desk.</li><li><strong>Raj</strong> — Raj is always on the move, bursting in with urgent messages, waving papers, and shouting, “Emergency!”</li></ul><h3>One Day !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0r-3FJtRr9hCUFKm_o57w.png" /><figcaption>Storyline</figcaption></figure><p>One day, Sheela was peacefully typing when Raj rushed in. “I have urgent work to do!” Raj yelled. Sheela sighed but knew Raj’s messages were important. She paused her typing and gave chance to Raj to do his “urgent” job. After completion of Raj’s work, Sheela continues to do her work.</p><p>Like Raj and Sheela, microcontrollers handle important tasks and respond to urgent events through <strong>interrupts.</strong></p><h3>What is an Interrupt?</h3><p>Imagine your microcontroller is like Sheela, busy doing important tasks like controlling robot arms or checking sensor readings. Suddenly, Raj (<em>an interrupt</em>) bursts in with an urgent task, like a button press or a temperature spike.</p><p>The microcontroller temporarily pauses its main task, handles the urgent task (<em>called the </em><strong><em>Interrupt Service Routine</em></strong><em> or ISR</em>), and then returns to what it was doing — just like Sheela went back to his report.</p><h3>Everyday Interrupt Adventures</h3><p>Here are some fun real-life examples of the involvement of interrupts</p><h4>1. Cooking and the Doorbell</h4><p>Imagine you’re cooking a delicious meal. Suddenly, the doorbell rings. You pause cooking, answer the door, and then return to your meal. The doorbell is the interrupt, and answering it is the ISR.</p><h4>2. Playing Video Games and Mom Calling</h4><p>You’re winning a game when your mom calls from the kitchen. You pause the game, answer her, and then jump back into action. That’s another interrupt!</p><h3>Why Do Microcontrollers Love Interrupts?</h3><p>Without interrupts, microcontrollers would be like someone constantly checking the front door for visitors — wasting time and energy. Interrupts let them focus on their main tasks and only respond when something important happens.</p><p>This makes devices faster and smarter.</p><h3>How Do Interrupts Work? The Simple Story</h3><p>Here’s how the interrupts work.</p><h4><strong>Step 1: Something Important Happens!</strong></h4><p>Imagine Raj (<em>the interrupt</em>) gets a call about an urgent package delivery. That’s an event trigger — just like when a microcontroller notices a button press or sensor change.</p><h4>Step 2: Raj Alerts Sheela</h4><p>Raj shouts, “Sheela ! I have urgent call to make!” This is the interrupt request (IRQ).</p><h4><strong>Step 3: Sheela Puts her Work on Hold</strong></h4><p>Sheela carefully bookmarks her place in the report so she can pick up right where she left off. That’s like the microcontroller saving important information (<em>context saving</em>).</p><h4><strong>Step 4: Raj Checks the Address Book</strong></h4><p>Raj looks up the delivery person’s name in his address book to figure out what to do next. This is the interrupt vector table (IVT) lookup.</p><h4><strong>Step 5: Raj Handles the Delivery</strong></h4><p>Raj calls for the package and takes care of the delivery. That’s like the microcontroller running the ISR.</p><h4><strong>Step 6: Raj Finishes the Task</strong></h4><p>Raj finishes the task and thanks Sheela. The ISR is now complete. Sheela continues working on her report again</p><h3>What’s Next?</h3><p>In the next part, we’ll discover how we can trigger interrupts. Stay tuned for more fun tech stories!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a24502951c1e" width="1" height="1" alt=""><hr><p><a href="https://blog.roboticgenlabs.com/why-do-microcontrollers-get-distracted-a24502951c1e">Why Do Microcontrollers Get Distracted?</a> was originally published in <a href="https://blog.roboticgenlabs.com/">RoboticGen Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blinking into the Heart of Arduino]]></title>
            <link>https://blog.stackademic.com/blinking-into-the-heart-of-arduino-8b552976592c?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b552976592c</guid>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[baremetal]]></category>
            <category><![CDATA[arduino-uno]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 04:16:44 GMT</pubDate>
            <atom:updated>2024-07-24T04:16:44.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*w4XofNV1Z7VhkPst302qdA.png" /></figure><h3>A Bare-Metal Adventure with ATmega328P</h3><p>This comprehensive guide dives into the exciting world of bare-metal programming on the Arduino Uno’s ATmega328P microcontroller. We’ll demonstrate the process by building a simple yet informative project — a blinking LED controlled entirely through direct register manipulation and timer interrupts, all without relying on the familiar Arduino libraries.</p><h3>Why Go Bare Metal?</h3><p>While Arduino libraries offer a convenient abstraction layer, tackling into bare-metal programming unlocks a deeper understanding and finer control over your microcontroller</p><p><strong>Unveiling the Hardware</strong></p><ul><li>You’ll gain intimate knowledge of the ATmega328P’s architecture, registers, and how they interact to bring your code to life.</li></ul><p><strong>Efficiency at its Core</strong></p><ul><li>By tailoring code for specific needs, you can often achieve significant gains in code size and execution speed, crucial for resource-constrained projects.</li></ul><p><strong>Embrace Portability</strong></p><ul><li>Reduced reliance on platform-specific libraries potentially makes your code more portable across different AVR microcontrollers.</li></ul><h3>Gearing Up</h3><h4>Prerequisites</h4><p>Before we proceed, ensure you have the following tools in your working enviornment</p><p><strong>AVR-GCC Toolchain</strong></p><ul><li>The cornerstone of AVR development, this toolchain provides the compiler, assembler, and linker needed to transform your C code into executable instructions for the ATmega328P.</li><li>You can download it from the official GNU website: <a href="https://gcc.gnu.org/wiki/avr-gcc">https://gcc.gnu.org/wiki/avr-gcc</a>.</li></ul><p><strong>avrdude:</strong></p><ul><li>This command-line utility serves as the bridge between your computer and the Arduino Uno, enabling you to upload the compiled code (firmware) onto the microcontroller.</li><li>It often comes bundled with the AVR-GCC toolchain or can be obtained separately: <a href="https://www.nongnu.org/avrdude/">https://www.nongnu.org/avrdude/</a></li></ul><p><strong>Code Editor of Choice:</strong></p><ul><li>A good code editor is your trusty companion in this journey. Choose one that suits your preferences, be it VS Code, Sublime Text, Atom, or any other capable editor.</li></ul><p><strong>Arduino Uno (or Simulator):</strong></p><ul><li>We’ll use the Arduino Uno as our development board due to its popularity and ease of use.</li><li>However, if you prefer a virtual environment, you can use a simulator like Wokwi (<a href="https://wokwi.com/">https://wokwi.com/</a>).</li></ul><h3>Setting the Stage</h3><h4>Hardware Setup</h4><p>This project requires minimal hardware. You only need:</p><ul><li>An Arduino Uno board</li></ul><p>No external resistors are needed as we’ll be using the built-in LED on the Arduino Uno, which is connected to pin 13 (which corresponds to PORTB5 on the ATmega328P).</p><h4>Software Setup</h4><p>You can find the full repository in <a href="https://github.com/yasanthaniroshan/Bare-Metal-Microcontroller-Programming">here</a></p><h3>Deconstructing the Code</h3><h4>blynk.c</h4><p>The provided blynk.c file houses the C code that breathes life into our blinking LED. Let’s break it down step-by-step</p><pre>#define PORTB *((volatile unsigned char *)0x25)<br>#define DDRB *((volatile unsigned char *)0x24)<br>#define TCCR1A *((volatile unsigned char *)0x80)<br>#define TCCR1B *((volatile unsigned char *)0x81)<br>#define OCR1AH *((volatile unsigned char *)0x89)<br>#define OCR1AL *((volatile unsigned char *)0x88)<br>#define TIMSK1 *((volatile unsigned char *)0x6F)<br>#define TIFR1 *((volatile unsigned char *)0x36)<br>#define TCNT1 *((volatile unsigned int *)0x84)<br><br>#define CS12 2<br>#define CS11 1<br>#define CS10 0<br><br>#define PORTB5 5<br>#define DDRB5 5<br><br>#define TOV1 0<br><br>#define OCIE1A 1<br>#define OCF1A 1<br><br>#define COM1A1 7<br>#define COM1A0 6</pre><h4>Talking to Hardware: Register Definitions</h4><ul><li>These lines are not your typical variable declarations.</li><li>They are powerful macros that provide a human-readable way to interact with the ATmega328P’s memory-mapped registers.</li><li>#define PORTB creates a macro named PORTB. Every time the compiler encounters PORTB, it replaces it with *((volatile unsigned char *)0x25), allowing you to directly access and manipulate the PORTB register.</li></ul><h4>Pointers and Volatile</h4><ul><li>(volatile unsigned char *)0x25 creates a pointer to the memory address 0x25, the location of the PORTB register in the ATmega328P’s memory space.</li><li>We use unsigned char * because each register typically holds 8 bits (1 byte).</li><li>The volatile keyword is crucial as it instructs the compiler not to optimize any access to this address, ensuring that every read and write to this register happens as intended.</li></ul><h4>Memory Addresses and Datasheets</h4><ul><li>The hexadecimal values (like 0x25) represent the memory addresses of specific registers, meticulously detailed in the ATmega328P datasheet (<a href="http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf">http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf</a>).</li><li>PORTB (address 0x25) controls the output state of the pins on Port B, including digital pins 8 to 13 on the Arduino Uno.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*KDoEu4P2_E9ykskK5jLXzA.png" /></figure><ul><li>DDRB (address 0x24) configures the direction (input/output) of those pins. We will be setting pin 13 (PORTB5) as output to control the LED.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*M7zHVgz9skNIuLbKiF13Hw.png" /></figure><h4>Responding to Events: Interrupt Service Routine (ISR)</h4><pre>void __vector_11(void) __attribute__((signal, used, externally_visible));<br>void __vector_11(void)<br>{<br>    PORTB ^= (1 &lt;&lt; PORTB5); // Toggle PORTB5<br>    TIFR1 ^= (1 &lt;&lt; OCF1A);  // Clear Timer1 Compare Match A Flag<br>}</pre><ul><li>This code defines a special function, __vector_11, which is an Interrupt Service Routine (ISR).</li></ul><p><strong>Interrupt Vector Table</strong></p><ul><li>The ATmega328P has an interrupt vector table that maps specific interrupt events to their corresponding ISRs.</li><li>__vector_11 is associated with the “Timer/Counter1 Compare Match A” interrupt.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*1gCB1riH09vZ-zj0P4UVVg.png" /><figcaption>Timer Compare Match Interrupt Vectr</figcaption></figure><p><strong>Attributes</strong></p><ul><li>The __attribute__((signal, used, externally_visible)) directive ensures the compiler generates correct code for an ISR and makes it accessible from outside the current compilation unit (essential for interrupt handling).</li></ul><p><strong>Toggling the LED</strong></p><ul><li>The line PORTB ^= (1 &lt;&lt; PORTB5); performs the LED toggling magic. It flips the state of the PORTB5 bit (which controls the LED) between 0 (off) and 1 (on).</li></ul><p><strong>Clearing the Interrupt Flag</strong></p><ul><li>The line TIFR1 ^= (1 &lt;&lt; OCF1A); is essential for acknowledging that the interrupt has been handled.</li><li>It clears the corresponding interrupt flag in the TIFR1 (Timer/Counter1 Interrupt Flag Register) so that the microcontroller is ready to detect the next timer match event.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CV6gEoguOIclPaZ3-MWMiA.png" /></figure><h4>The Heart of the Program: Main Function</h4><pre>int main()<br>{<br>    // Setting Timer1 Control Registers<br>    TCNT1 = 0;  // Initialize Timer1 Counter to 0<br>    TCCR1A = 0; // Initialize Timer1 Control Register A to 0<br>    TCCR1B = 0; // Initialize Timer1 Control Register B to 0<br><br>    // Store the value 15624 in OCR1A register<br>    OCR1AH = 15624 &gt;&gt; 8;   // Set Timer1 Compare Register High Byte to 15625 &gt;&gt; 8<br>    OCR1AL = 15624 &amp; 0xFF; // Set Timer1 Compare Register Low Byte to 15625 &amp; 0xFF<br><br>    // Clear Timer1 Compare Match A Flag<br>    TIFR1 ^= (1 &lt;&lt; OCF1A); // Clear Timer1 Compare Match A Flag<br><br>    TCCR1B |= (1 &lt;&lt; CS12); // Set Timer1 Clock Prescaler to 256<br><br>    DDRB |= (1 &lt;&lt; DDRB5); // Set PORTB5 as output (Pin 13 on Arduino Uno)<br><br>    // Setting Interrupts<br>    __asm__ __volatile__(&quot;cli&quot; ::: &quot;memory&quot;); // Disable Global Interrupt<br><br>    TIMSK1 = (1 &lt;&lt; OCIE1A); // Enable Timer1 Overflow Interrupt<br><br>    __asm__ __volatile__(&quot;sei&quot; ::: &quot;memory&quot;); // Enable Global Interrupt<br><br><br>    // Set PORTB5 to High<br>    PORTB |= (1 &lt;&lt; PORTB5); // Set PORTB5 to High<br><br><br>    // Infinite Loop<br>    while (1);<br>}</pre><p><strong>Pin Configuration</strong></p><ul><li>DDRB |= (1 &lt;&lt; DDRB5); sets PORTB5 as an output pin, enabling us to control the connected LED.</li></ul><p><strong>Timer Configuration:</strong></p><ul><li>We’ll delve into the details shortly, but this is where we configure Timer1 to generate interrupts at specific intervals to control the blinking rate of the LED.</li></ul><p><strong>Interrupt Setup</strong></p><ul><li>We enable the Timer1 Compare Match A interrupt, ensuring that our ISR (__vector_11) is called whenever the timer reaches our specified value.</li></ul><p><strong>Initial LED State</strong></p><ul><li>PORTB |= (1 &lt;&lt; PORTB5); sets PORTB5 high, turning the LED on initially.</li></ul><p><strong>Infinite Loop</strong></p><ul><li>The while (1); statement ensures the microcontroller keeps running and responding to the timer interrupt.</li></ul><h4>Fine-Tuning the Blink: Timer1 Configuration</h4><p><strong>Timer Initialization:</strong></p><ul><li>The first three lines reset the timer counter (TCNT1) and control registers (TCCR1A, TCCR1B) to their default values, ensuring a clean slate for our configuration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HEwcgQmGkFHmATSVEr0AA.png" /><figcaption>TCCR1A Control Register A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10esTOX4f37pGFjnT3VZQg.png" /><figcaption>TCCR1B Timer Control Trgister B</figcaption></figure><p><strong>Setting the Compare Value</strong></p><ul><li>OCR1AL = 15624 &amp; 0xFF; and OCR1AH = 15624 &gt;&gt; 8; set the 16-bit value 15624 into the OCR1A (Output Compare Register A).</li><li>Timer1 will generate an interrupt each time its counter (TCNT1) matches this value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*UEteMiyOjohRH6vy8DjajQ.png" /></figure><p><strong>Controlling the Tick: Prescaler</strong></p><ul><li>TCCR1B |= (1 &lt;&lt; CS12); configures Timer1 to use a prescaler of 256. This slows down the timer’s counting rate.</li><li>The ATmega328P typically runs at 16 MHz, meaning the timer would increment every 62.5 nanoseconds.</li><li>With a prescaler of 256, this is slowed down to approximately 16 microseconds per tick.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJxOwXVaH4ZomfrkGo_t1A.png" /></figure><p><strong>Blinking Frequency Calculation</strong></p><ul><li>The combination of the compare value (15624) and prescaler (256) determines the blink rate.</li><li>With a 16 MHz clock and a prescaler of 256, the timer takes approximately 1 second to count to 15624, resulting in a blink rate of once per second.</li></ul><p><strong>Enabling the Heartbeat: Interrupt Setup</strong></p><p><strong>Critical Section (Disabling Interrupts)</strong></p><p>The code __asm__ __volatile__(“cli” ::: “memory”); temporarily disables all interrupts. This is crucial to prevent any interrupt from occurring while we are in the process of configuring the specific interrupt we need. Interrupts are re-enabled after the setup using __asm__ __volatile__(“sei” ::: “memory”);</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8ZPDa-c-P_1SjDBV8eHng.png" /><figcaption>Assembly Instruction for enabling interrupts and disabling interupts</figcaption></figure><p><strong>Enabling the Timer Interrupt</strong></p><ul><li>The line TIMSK1 = (1 &lt;&lt; OCIE1A); enables the Timer1 Compare Match A interrupt, ensuring that the microcontroller will jump to our ISR (__vector_11) every time the timer matches our configured value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CV6gEoguOIclPaZ3-MWMiA.png" /></figure><h3>The Automation Maestro: Makefile</h3><p>The Makefile simplifies the process of compiling, linking, and uploading your code to the Arduino. Let’s look at some key parts</p><p><strong>Configuration Variables</strong></p><ul><li>The Makefile defines variables like CC (the compiler), MMCU (the microcontroller type), and FILE (the project file name).</li><li>This makes it easy to modify these settings if needed.</li></ul><p><strong>Targets</strong></p><ul><li>The flash target is particularly important.</li><li>It invokes avrdude to upload the compiled code ($(OUTPUT)/$(HEX)) to the Arduino Uno.</li><li>Make sure the -P /dev/ttyACM0 option matches the serial port your Arduino is connected to.</li><li>The all target is a convenience target that executes the necessary build steps in the correct sequence.</li><li>The clean target removes the build directory and its contents, providing a clean slate for subsequent builds.</li></ul><h3>Bringing It All Together: Building and Flashing</h3><ol><li><strong>Terminal Time:</strong> Open a terminal and navigate to your project directory.</li><li><strong>Build Command:</strong> Execute the command make all to compile, assemble, and link your code. The Makefile will take care of invoking the compiler and linker with the correct flags and settings.</li><li><strong>Flashing to the Arduino:</strong> Once the build is successful, run make flash to upload the compiled code to your Arduino Uno.</li></ol><h3>Observing the Magic</h3><p>If everything is set up correctly, the LED connected to pin 13 on your Arduino Uno should now be blinking at approximately one-second intervals. Congratulations! You’ve successfully blinked an LED using bare-metal programming on the ATmega328P.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*pKaey4nZZsfJrU1OF03RHw.png" /></figure><h3>Embracing the Journey: Further Explorations</h3><p>This is just the beginning of your bare-metal adventure! Here are some ideas for further exploration:</p><p><strong>Modify the Blink Rate</strong></p><ul><li>Experiment with different values for the compare register (OCR1A) and prescaler (in TCCR1B) to control the blinking speed of the LED.</li></ul><p><strong>Explore Other Timers and Interrupts</strong></p><ul><li>The ATmega328P has multiple timers and a rich set of interrupts.</li><li>Try using different timers and interrupt sources to create more complex patterns and behaviours.</li></ul><p><strong>Dive Deeper into Datasheets:</strong></p><ul><li>The <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf">ATmega328P datasheet</a> is your bible for bare-metal programming. Use it to understand the microcontroller’s capabilities and explore new registers and features.</li></ul><p>By embracing bare-metal programming, you’ll gain invaluable insights into the inner workings of microcontrollers, opening up a world of possibilities for creating efficient and customized embedded systems. Enjoy the journey!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b552976592c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/blinking-into-the-heart-of-arduino-8b552976592c">Blinking into the Heart of Arduino</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Connect ESP32 with Mobile using Bluetooth in MicroPython]]></title>
            <link>https://python.plainenglish.io/comprehensive-guide-to-connect-esp32-with-mobile-using-bluetooth-in-micropython-19232641bf5c?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/19232641bf5c</guid>
            <category><![CDATA[bluetooth]]></category>
            <category><![CDATA[micropython]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[dht-22]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Fri, 24 May 2024 06:17:33 GMT</pubDate>
            <atom:updated>2024-05-24T06:17:33.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*LxvImB5CBd528GE4iT40kA.png" /><figcaption>Article Featured Image</figcaption></figure><p>This guide provides a detailed walkthrough on establishing a Bluetooth Low Energy (BLE) connection between your ESP32 microcontroller and a mobile device using MicroPython.</p><p>Our aim is to read temperature and humidity data from a DHT22 sensor connected to the ESP32 and send this data wirelessly to a mobile device via BLE.</p><h3>Hardware Requirements</h3><ul><li>ESP32 development board</li><li>DHT22 temperature and humidity sensor</li><li>Jumper wires</li><li>Mobile device with Bluetooth capabilities</li></ul><h4>Hardware Connection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Y6IdBSV32vQVRvFW6uEodA.png" /><figcaption>Connection Between DHT22 and ESP32</figcaption></figure><h3>Software Requirements</h3><ul><li>MicroPython firmware flashed onto the ESP32</li><li>DHT library for ESP32 should be installed in ESP32</li><li>Thonny IDE or any other compatible IDE</li><li>A mobile app capable of connecting to BLE devices (<a href="https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal">Serial Bluetooth Terminal</a> )</li></ul><h3>Code Breakdown</h3><h4>DHT22 Sensor Setup</h4><pre>dht_sensor = dht.DHT22(machine.Pin(26))</pre><p>This code defines the DHT22 sensor connected to GPIO pin 26. Ensure to change the pin number if your setup differs.</p><h4>Bluetooth Constants and UUIDs</h4><pre>_ADV_TYPE_FLAGS = const(0x01)<br>_ADV_TYPE_NAME = const(0x09)<br>_ADV_TYPE_UUID16_COMPLETE = const(0x3)<br>_ADV_TYPE_UUID32_COMPLETE = const(0x5)<br>_ADV_TYPE_UUID128_COMPLETE = const(0x7)<br>_ADV_TYPE_UUID16_MORE = const(0x2)<br>_ADV_TYPE_UUID32_MORE = const(0x4)<br>_ADV_TYPE_UUID128_MORE = const(0x6)<br>_ADV_TYPE_APPEARANCE = const(0x19)<br><br>_ADV_MAX_PAYLOAD = const(128)<br><br>_IRQ_CENTRAL_CONNECT = const(1)<br>_IRQ_CENTRAL_DISCONNECT = const(2)<br>_IRQ_GATTS_WRITE = const(3)<br><br>_FLAG_WRITE = const(0x0008)<br>_FLAG_NOTIFY = const(0x0010)<br><br>_UART_UUID = bluetooth.UUID(&quot;6E400001-B5A3-F393-E0A9-E50E24DCCA9E&quot;)<br>_UART_TX = (<br>    bluetooth.UUID(&quot;6E400003-B5A3-F393-E0A9-E50E24DCCA9E&quot;),<br>    _FLAG_NOTIFY,<br>)<br>_UART_RX = (<br>    bluetooth.UUID(&quot;6E400002-B5A3-F393-E0A9-E50E24DCCA9E&quot;),<br>    _FLAG_WRITE,<br>)<br>_UART_SERVICE = (<br>    _UART_UUID,<br>    (_UART_TX, _UART_RX),<br>)<br><br># org.bluetooth.characteristic.gap.appearance.xml<br>_ADV_APPEARANCE_GENERIC_COMPUTER = const(128)</pre><p>The code defines various constants related to BLE advertising types, service UUIDs for a simulated UART profile, and appearance characteristics.</p><h4>Advertising Payload Function</h4><p>This function constructs the advertising payload, which carries information about the ESP32’s BLE services and characteristics to be broadcasted.</p><pre>def advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):<br>    payload = bytearray()<br><br>    def _append(adv_type, value):<br>        nonlocal payload<br>        payload += struct.pack(&quot;BB&quot;, len(value) + 1, adv_type) + value<br><br>    _append(<br>        _ADV_TYPE_FLAGS,<br>        struct.pack(&quot;B&quot;, (0x01 if limited_disc else 0x02) + (0x18 if br_edr else 0x04)),<br>    )<br><br>    if name:<br>        _append(_ADV_TYPE_NAME, name)<br><br>    if services:<br>        for uuid in services:<br>            b = bytes(uuid)<br>            if len(b) == 2:<br>                _append(_ADV_TYPE_UUID16_COMPLETE, b)<br>            elif len(b) == 4:<br>                _append(_ADV_TYPE_UUID32_COMPLETE, b)<br>            elif len(b) == 16:<br>                _append(_ADV_TYPE_UUID128_COMPLETE, b)<br><br>    # See org.bluetooth.characteristic.gap.appearance.xml<br>    if appearance:<br>        _append(_ADV_TYPE_APPEARANCE, struct.pack(&quot;&lt;h&quot;, appearance))<br><br>    if len(payload) &gt; _ADV_MAX_PAYLOAD:<br>        raise ValueError(&quot;advertising payload too large&quot;)<br><br>    return payload</pre><h4>BLEUART Class</h4><p>This is the heart of our BLE communication, handling connection management, data transmission, and reception.</p><pre><br>class BLEUART:<br>    def __init__(self, ble, name=&quot;Esp-Temp-Meter&quot;, rxbuf=100):<br>        self._ble = ble<br>        self._ble.active(True)<br>        self._ble.irq(self._irq)<br>        ((self._tx_handle, self._rx_handle),) = self._ble.gatts_register_services((_UART_SERVICE,))<br>        self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True)<br>        self._connections = set()<br>        self._rx_buffer = bytearray()<br>        self._handler = None<br>        self._payload = advertising_payload(name=name, appearance=_ADV_APPEARANCE_GENERIC_COMPUTER)<br>        self._advertise()<br><br>    def irq(self, handler):<br>        self._handler = handler<br><br>    def _irq(self, event, data):<br>        if event == _IRQ_CENTRAL_CONNECT:<br>            conn_handle, _, _ = data<br>            self._connections.add(conn_handle)<br>        elif event == _IRQ_CENTRAL_DISCONNECT:<br>            conn_handle, _, _ = data<br>            if conn_handle in self._connections:<br>                self._connections.remove(conn_handle)<br>            self._advertise()<br>        elif event == _IRQ_GATTS_WRITE:<br>            conn_handle, value_handle = data<br>            if conn_handle in self._connections and value_handle == self._rx_handle:<br>                self._rx_buffer += self._ble.gatts_read(self._rx_handle)<br>                if self._handler:<br>                    self._handler()<br><br>    def any(self):<br>        return len(self._rx_buffer)<br><br>    def read(self, sz=None):<br>        if not sz:<br>            sz = len(self._rx_buffer)<br>        result = self._rx_buffer[0:sz]<br>        self._rx_buffer = self._rx_buffer[sz:]<br>        return result<br><br>    def write(self, data):<br>        for conn_handle in self._connections:<br>            self._ble.gatts_notify(conn_handle, self._tx_handle, data)<br><br>    def close(self):<br>        for conn_handle in self._connections:<br>            self._ble.gap_disconnect(conn_handle)<br>        self._connections.clear()<br><br>    def _advertise(self, interval_us=500000):<br>        self._ble.gap_advertise(interval_us, adv_data=self._payload)<br></pre><ul><li>__init__ : Initializes the BLE object, sets up the UART service, and configures advertising parameters.</li><li>irq : Allows you to register a callback function (`handler`) that gets triggered on BLE events.</li><li>_irq : Internal function handling various BLE events like connection, disconnection, and data reception.</li><li>any, read, write : Functions for checking data availability, reading, and writing data to the BLE UART service.</li><li>close : Disconnects any existing connections.</li><li>_advertise : Starts advertising the BLE services.</li></ul><h4>main Function</h4><pre>def main():<br>    import time<br><br>    ble = bluetooth.BLE()<br>    uart = BLEUART(ble)<br><br>    def on_rx():<br>        print(&quot;rx: &quot;, uart.read().decode().strip())<br><br>    uart.irq(handler=on_rx)<br> <br>    try:<br>        while True:<br>                dht_sensor.measure()<br>                temperature = dht_sensor.temperature()<br>                humidity = dht_sensor.humidity()<br>                data_string = f&quot;Temperature: {temperature}°C, Humidity: {humidity}%\n&quot;<br>                uart.write(data_string)<br>                time.sleep(2)  # Send data every 2 seconds<br>    except KeyboardInterrupt:<br>        pass<br><br>    uart.close()</pre><p>This function demonstrates the usage of the `BLEUART` class. It initializes the BLE object, creates a `BLEUART` instance, registers a callback function to handle received data, and continuously reads and transmits sensor readings.</p><h3>Running the Code</h3><ul><li>Connect the DHT22 sensor to the ESP32 board (refer to the code and diagram for pin configuration).</li><li>Upload the code to your ESP32 using Thonny IDE or a similar tool.</li><li>Open a BLE app on your mobile device.</li><li>Scan for available devices. The ESP32 should appear with the name <strong>“Esp-Temp-Meter”</strong> or the name you set in the code.</li><li>Connect to the ESP32.</li><li>The mobile app should display the temperature and humidity readings being sent from the ESP32.</li></ul><h3>Troubleshooting</h3><ul><li>Ensure your ESP32 is flashed with the latest MicroPython firmware.</li><li>Double-check the DHT22 sensor connections and pin assignments in the code.</li><li>Verify that the UUIDs used in the code match the ones used by your mobile app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*9VO3VU7Di7G-OK9tLIAi8w.png" /><figcaption>Screenshot of a working Phototype</figcaption></figure><p>This comprehensive guide should get you started with ESP32 Bluetooth communication using MicroPython. You can now explore further possibilities and modify the code to transmit different types of data or control external devices via BLE.</p><p>References :</p><ol><li><a href="https://github.com/micropython/micropython/tree/master/examples/bluetooth"><em>Official Micropython Implementation</em></a></li><li><a href="https://docs.micropython.org/en/latest/library/bluetooth.html"><em>Official Micropython Documentation</em></a></li></ol><h3>Full Code Snippet</h3><p>You can download the full code snippet from <a href="https://gist.github.com/yasanthaniroshan/2fcb01689cd3bda018ef65c8b28e5709">here</a>.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19232641bf5c" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/comprehensive-guide-to-connect-esp32-with-mobile-using-bluetooth-in-micropython-19232641bf5c">Comprehensive Guide to Connect ESP32 with Mobile using Bluetooth in MicroPython</a> was originally published in <a href="https://python.plainenglish.io/">Python 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[A Comprehensive Guide on Building a Library Management System (LMS) using Django]]></title>
            <link>https://python.plainenglish.io/building-a-library-management-system-lms-using-django-85a3dd4d9a49?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/85a3dd4d9a49</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[library-management-system]]></category>
            <category><![CDATA[lms-systems]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Mon, 20 May 2024 12:17:29 GMT</pubDate>
            <atom:updated>2024-05-20T12:17:29.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yk3DfV06EjVtf0Fgm80jSQ.png" /></figure><h3>Introduction</h3><p>In today’s digital era, managing libraries efficiently has become increasingly important. Traditional methods of library management are being replaced by digital solutions that streamline processes and enhance user experience. In this article, we’ll delve into the process of building a Library Management System (LMS) using Django, a high-level Python web framework.</p><h3>Overview of the Library Management System (LMS) Project</h3><p>A Library Management System is a crucial tool for librarians to organize, catalog, and manage library resources effectively. Our LMS project will offer features such as book management, search functionality, and a user-friendly interface to facilitate smooth library operations.</p><h3>Introduction to Django and its Suitability for Building an LMS</h3><p>Django is a powerful web framework known for its simplicity, versatility, and scalability. Its built-in features such as ORM (Object-Relational Mapping) and admin interface make it an ideal choice for developing complex web applications like an LMS.</p><h3>Features of the LMS Our LMS will include the following features</h3><h4>Book Management</h4><ul><li>Adding new books</li><li>Viewing a list of books</li><li>Deleting books</li><li>Detailed view of specific books</li></ul><h4>Search Functionality</h4><ul><li>Searching books by title or author</li></ul><h4>User-friendly Interface</h4><ul><li>Simple and intuitive design for ease of use</li></ul><h3>Prerequisites</h3><p>Before proceeding, ensure you have the following prerequisites installed</p><ul><li>Python 3.10 or higher</li></ul><blockquote>You can download relevent python version in <a href="https://www.python.org/downloads/">here</a></blockquote><ul><li>Django 5.0.0 or higher</li></ul><pre>pip install django</pre><h3>Setting Up the Development Environment</h3><p><strong>Setting Up the Development Environment from scratch<br></strong>1. Creating a New Django Project</p><pre>django-admin startproject LibraryManagementSystem</pre><p>2. Navigate to the project directory</p><pre>cd LibraryManagementSystem</pre><p>3. Create a Django app to manage library functionalities</p><pre>python manage.py startapp LibManager</pre><p><strong>Or just clone the repository from </strong><a href="https://github.com/yasanthaniroshan/Library-Management-System"><strong><em>here</em></strong></a></p><p><strong>Project File Structure</strong></p><p>Now you have to make project file structure as follow. Here’s a breakdown of the key directories and files in your project:</p><ul><li><strong>LibraryManagementSystem — </strong>Contains project-level configuration files like settings.py and urls.py.</li><li><strong>LibManager —</strong> Encompasses the library management app, including models, views, and URLs specific to the LMS.</li><li><strong>Templates — </strong>Houses HTML templates used to render the application’s user interface.</li><li><strong>booklist.txt — </strong>The text file containing the initial book data.</li><li><strong>manage.py —</strong> A utility script for managing the Django project.</li><li><strong>static/</strong> (Optional) — Stores static files like CSS for styling the application.</li></ul><h3><strong>Creating the Library Management App (LibManager)</strong></h3><ol><li><strong>models.py</strong></li></ol><p>This file defines the data model for your books. Here’s an explanation of the Book model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xi1bXl5yW6UI09Nt7K4HQ.png" /></figure><p>The model defines the following fields for each book:</p><ul><li>title: The book&#39;s title (CharField with a maximum length of 100 characters).</li><li>author: The book&#39;s author(s) (CharField with a maximum length of 100 characters).</li><li>genre: The book&#39;s genre (CharField with a maximum length of 100 characters).</li><li>copies: The number of available copies of the book (IntegerField with a default value of 1).</li></ul><p>The __str__ method specifies how a book object is represented as a string when requested.</p><p><strong>2. views.py</strong></p><p>This file contains Python functions responsible for handling user interactions and rendering the appropriate web pages. Here’s a breakdown of the included views:</p><p><strong>viewBookList(request)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0qSnPioS-BpxOiN8pxLfg.png" /></figure><p>This function retrieves and displays a list of all books:</p><ul><li><strong>Retrieving Books:</strong></li><li>books = Book.objects.all() fetches all book objects from the database.</li><li><strong>Preparing Data for Template:</strong></li><li>context = {&#39;books&#39;: books} creates a dictionary named context to store book data for the template.</li><li><strong>Rendering the Template:</strong></li><li>render(request, &#39;bookList.html&#39;, context) renders the bookList.html template, passing the context dictionary.</li></ul><p><strong>addBook(request)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5LJhSI7GOA61OKfEXe_gg.png" /></figure><p>This function handles adding new books to the library.</p><ul><li><strong>Checking for Form Submission (</strong><strong>POST request):</strong></li><li>if request.method == &#39;POST&#39;: This line checks if the user submitted a form (indicated by the POST method).</li><li><strong>Extracting Form Data (if POST):</strong></li><li>Assuming you’re not using a form class like BookForm here, the code retrieves individual field values from the submitted form data using request.POST.get().</li><li>title = request.POST.get(&#39;title&#39;): Extracts the value for the &quot;title&quot; form field.</li><li>Similar lines extract values for “author”, “genre”, and “copies”.</li><li><strong>Creating a New Book Object (if POST):</strong></li><li>book = Book(title=title, author=author, genre=genre, copies=copies): This line creates a new Book object using the extracted form data. It maps the retrieved values to the corresponding fields (title, author, genre, and copies) of the Book model (defined in models.py).</li><li><strong>Saving the New Book (if POST):</strong></li><li>book.save(): This line saves the newly created book object to the database. The save method is built into the Django model to persist the book data.</li><li><strong>Redirecting to Book Details (if POST):</strong></li><li>return redirect(&#39;bookView&#39;, book_id=book.id): After successful book creation, this line redirects the user to the book details view using redirect. It constructs a URL for the bookView function, passing the newly created book&#39;s ID (book.id) as the book_id argument. This allows the user to see the details of the added book.</li><li><strong>Rendering the Add Book Form (if not POST):</strong></li><li>return render(request, &#39;addBook.html&#39;): This line, outside the if block, handles situations where the request method is not POST (likely the initial page load). It uses render to render the &#39;addBook.html&#39; template, which presumably displays the form for adding new books.</li></ul><p><strong>bookView(request, book_id)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEhGCUyJqTf3Gb4TxIewHQ.png" /></figure><p>This function retrieves and displays details of a specific book:</p><ul><li><strong>Extracting Book ID:</strong></li><li>Takes request and book_id as arguments.</li><li><strong>Fetching the Book Object:</strong></li><li>book = Book.objects.get(pk=book_id) retrieves the book based on its ID.</li><li><strong>Preparing Data for Template:</strong></li><li>context = {&#39;book&#39;: book} creates a dictionary with the retrieved book object.</li><li><strong>Rendering the Template:</strong></li><li>render(request, &#39;bookView.html&#39;, context) renders the bookView.html template with book details.</li></ul><p><strong>deleteBook(request)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kOVb1r9XcK5nBPisg9Y3g.png" /></figure><ul><li>This function handles deleting books from the library based on a search query.</li><li><strong>Checking for Form Submission (</strong><strong>POST request):</strong></li><li>if request.method == &#39;POST&#39;: This line checks if the user submitted a form containing the search query (likely a form on the deleteBook.html template).</li><li><strong>Extracting Search Query (if POST):</strong></li><li>query = request.POST[&#39;query&#39;]: This line extracts the search query value from the submitted form data using request.POST[&#39;query&#39;].</li><li><strong>Searching for Books (if POST):</strong></li><li>books = Book.objects.filter(Q(title__icontains=query) | Q(author__icontains=query)): This line performs a database query using Django&#39;s ORM (Object-Relational Mapper). It searches for books where the title or author (case-insensitive) contains the provided query.</li><li><strong>Handling Search Results:</strong></li><li>if len(books) == 1: This condition checks if exactly one book was found based on the search query.</li><li>if len(books) == 1: This condition checks if exactly one book was found based on the search query.</li><li>books.delete(): If only one book is found, this line deletes that book object from the database using the delete method.</li><li>return redirect(&#39;viewBookList&#39;): After successful deletion, it redirects the user to the book list view (&#39;viewBookList&#39;).</li><li><strong>Multiple Books Found:</strong></li><li>elif len(books) &gt; 1: This condition checks if more than one book matches the search query.</li><li>for book in books: This loop iterates through each book object found in the search results.</li><li>book.delete(): Inside the loop, each book object is deleted from the database using delete.</li><li>return redirect(&#39;viewBookList&#39;): After deleting all matching books, it redirects the user to the book list view.</li><li><strong>No Books Found:</strong></li><li>This block executes if no books are found matching the search query.</li><li>It creates a dictionary named context to store error messages.and sets the &#39;title&#39; key to &quot;Book not found&quot; and the &#39;message&#39; key to a message indicating the user needs to enter a valid book title or author.</li><li>It renders the &#39;ErrorHandler.html&#39; template with the error message context</li><li><strong>Rendering the Delete Book Form (if not POST):</strong></li><li>This block executes when the request method is not POST (likely the initial page load for deleting a book).</li><li>return render(request, &#39;deleteBook.html&#39;): It renders the &#39;deleteBook.html&#39; template, which presumably displays a form for users to enter the book title or author for deletion.</li></ul><p><strong>searchBook(request)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJR8vLaZnJHVLmwJ7qj0JA.png" /></figure><ul><li>This function handles searching for books in the library based on a search query.</li><li><strong>Checking for Form Submission (</strong><strong>POST request):</strong></li><li>if request.method == &#39;POST&#39;: This line checks if the user submitted a form containing the search query (likely a form on the search.html template).</li><li><strong>Extracting Search Query (if POST):</strong></li><li>query = request.POST[&#39;query&#39;]: This line extracts the search query value from the submitted form data using request.POST[&#39;query&#39;].</li><li><strong>Searching for Books (if POST):</strong></li><li>books = Book.objects.filter(Q(title__icontains=query) | Q(author__icontains=query)): This line performs a database query using Django&#39;s ORM, similar to the deleteBook function. It searches for books where the title or author (case-insensitive) contains the provided query.</li><li><strong>Handling Search Results:</strong></li><li><strong>One Book Found:</strong></li><li>if len(books) == 1: This condition checks if exactly one book was found based on the search query.</li><li>return redirect(&#39;bookView&#39;, book_id=books[0].id): If only one book matches, it redirects the user to the details view (&#39;bookView&#39;) for that specific book, passing the book&#39;s ID (books[0].id).</li><li><strong>Multiple Books Found:</strong></li><li>elif len(books) &gt; 1: This condition checks if more than one book matches the search query.</li><li>context = {&#39;books&#39;: books}: It creates a dictionary named context to store the list of found books.</li><li>return render(request, &#39;bookList.html&#39;, context): It renders the &#39;bookList.html&#39; template, likely designed to display a list of search results (multiple books). The context dictionary provides the list of books (&#39;books&#39;) to the template.</li><li><strong>No Books Found:</strong></li><li>This block executes if no books are found matching the search query.</li><li>It creates a context dictionary with error messages.</li><li>It renders the &#39;ErrorHandler.html&#39; template with the error message context.</li><li><strong>Rendering the Search Form (if not POST):</strong></li><li>This block executes when the request method is not POST (likely the initial page load for searching books).</li><li>return render(request, &#39;search.html&#39;): It renders the &#39;search.html&#39; template, which presumably displays a form for users to enter their search query.</li></ul><p><strong>3. urls.py</strong></p><p>The urls.py file acts as a router, directing the user to the appropriate functionality based on the requested URL. Here&#39;s a breakdown</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ynaLNgfnvGMBnoPOTeyNw.png" /></figure><ul><li><strong>Importing Necessary Modules:</strong></li><li>from django.urls import path: This line imports the path function used to define URL patterns.</li><li>from . import views: This line imports all views defined in your views.py file (assuming it&#39;s in the same app directory).</li><li><strong>Defining URL Patterns:</strong></li><li>urlpatterns = [ ... ]: This list stores the URL patterns for your application.</li><li>Each pattern is defined using the path function:</li><li><strong>First argument:</strong></li><li>The URL path (can be empty &#39;&#39; for the root URL or include patterns like &#39;addBook/&#39;).</li><li><strong>Second argument:</strong></li><li>The view function to be called when this URL is requested (e.g., views.viewBookList).</li><li><strong>Third argument (optional):</strong></li><li>A name for the URL pattern, which can be used for reverse URL resolution (e.g., name=&#39;viewBookList&#39;).</li></ul><p><strong>4. admin.py</strong></p><p>This file allows you to register your models with the Django admin interface. With this enabled, you can manage books (add, edit, delete) directly through a web-based interface at <a href="http://127.0.0.1:8000/admin/">http://127.0.0.1:8000/admin/.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3oz7l0WL1jPDqF6I0kCF4g.png" /></figure><h3><strong>Modifiying the Settings of Library Management App (LibraryManagementSystem/)</strong></h3><p><strong>1. settings.py:</strong></p><p>In the settings.py you need to change some settings related to the static files templates folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWQXN9Q1gslWOzPZfzOB_A.png" /></figure><blockquote><strong>Are you tired ? <br></strong>Just clone the original repository and complete the remaining part of your project from <a href="https://github.com/yasanthaniroshan/Library-Management-System.git"><strong>here</strong></a></blockquote><p><strong>Running the Application</strong></p><ol><li>Start the Django development server:</li></ol><pre>python manage.py runserver</pre><p>This launches the server, typically accessible at http://127.0.0.1:8000/ in your web browser.</p><p><strong>Preparing the Book Data</strong></p><p>Add book entries to the booklist.txt file in the specified format (title, author, genre, number of copies).</p><p><strong>Populate the database with book data (Optional):</strong></p><ol><li>The AddBooks.py script demonstrates an alternative approach to populate the database with book data from the booklist.txt file. You can run this script to automatically add books during development.</li></ol><h4><strong>Using the Library Management System</strong></h4><p>Once the server is running, you can access the LMS through your web browser at http://127.0.0.1:8000/. The application provides functionalities through the following features:</p><ul><li><strong>Home Page:</strong> Serves as the entry point, offering navigation links to various functionalities.</li><li><strong>View Book List:</strong> Displays a tabular list of all available books in the library.</li><li><strong>Add Book:</strong> Provides a form to add new book entries to the library’s catalog.</li><li><strong>Delete Book:</strong> Allows users to search for books by title or author and delete matching entries.</li><li><strong>View Book:</strong> Presents detailed information about a specific book, retrieved based on its unique ID.</li></ul><p><strong>You can find the whole project in </strong><a href="https://github.com/yasanthaniroshan/Library-Management-System.git"><strong>here</strong></a></p><h3>Conclusion</h3><p>In conclusion, we’ve explored the process of building a Library Management System with Django. By leveraging Django’s robust features, developers can create efficient and user-friendly LMS solutions tailored to their specific needs. Embracing digital solutions like Django enables libraries to adapt to changing technological landscapes and deliver enhanced services to their users.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85a3dd4d9a49" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/building-a-library-management-system-lms-using-django-85a3dd4d9a49">A Comprehensive Guide on Building a Library Management System (LMS) using Django</a> was originally published in <a href="https://python.plainenglish.io/">Python 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[3 Steps to Build a Telegram Bot with Django Backend]]></title>
            <link>https://medium.com/towards-data-engineering/3-steps-to-build-a-telegram-bot-with-django-python-a87e5cc1226c?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a87e5cc1226c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Thu, 09 May 2024 19:34:51 GMT</pubDate>
            <atom:updated>2024-05-10T04:49:26.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*KbZpSl2gzrX6FRMenrVjKQ.png" /></figure><p>Telegram bots have become increasingly popular for automating tasks, providing information, and engaging with users on the Telegram platform. When developing a Telegram bot, it’s crucial to consider aspects like data management, scalability, and ease of development. Integrating Django, a high-level Python web framework, as the backend for your Telegram bot can offer significant advantages.</p><h3>Why Django for Telegram Bot Backend?</h3><h4>1. Robust Database Management</h4><p>Django comes with a built-in Object-Relational Mapping (ORM) system, providing a straightforward way to interact with databases. This makes managing user data, logs, and bot state seamless.</p><h4>2. Model Architecture</h4><p>Django’s model architecture enables developers to define data models using Python classes. These models automatically create database tables, simplifying the storage and retrieval of bot-related data.</p><h4>3. Scalability and Flexibility</h4><p>Django is known for its scalability and flexibility, allowing developers to build complex applications with ease. As your Telegram bot grows, Django’s modular structure enables you to extend functionality and handle increased traffic efficiently.</p><h3>1. Setting Up Django</h3><h4>1. Install Django and Required Libraries</h4><p>If you haven’t already installed Django, python-dotenv, and python-telegram-bot, you can do so using pip, Python’s package manager</p><pre>pip install django python-dotenv python-telegram-bot</pre><h4>2. Obtaining Bot Token</h4><p>Before proceeding, you need to obtain a bot token from the Telegram BotFather. Follow these steps</p><ul><li>Go to Telegram’s <a href="https://t.me/botfather">BotFather</a> on Telegram.</li><li>Send the BotFather a message with the /newbot command to create a new bot.</li><li>Follow the BotFather’s instructions to provide a name for your bot and choose a username.</li><li>Once your bot is created, the BotFather will provide you with a bot token. This token is necessary for authenticating your bot with the Telegram API.</li></ul><p>For detailed instructions, refer to <a href="https://core.telegram.org/bots/features#creating-a-new-bot">Telegram’s official guide.</a></p><h4>3. Adding Bot Token to .env File</h4><p>Once you have obtained the bot token, add it to the .env file in your Django project directory. If the .env file doesn’t exist, create one in the root directory of your project.</p><p>Open the .env file and add the following line</p><pre>TOKEN=your_telegram_bot_token</pre><p>Replace your_bot_token_here with the bot token obtained from the BotFather.</p><p>Storing sensitive information like API tokens in the .env file ensures that they are not exposed in version control or other public places.</p><h4>2. Create a Django Project</h4><p>Navigate to the directory where you want to create your Django project and run the following command</p><pre>django-admin startproject django_telegram_bot</pre><p>This command will create a new directory named django_telegram_bot containing the basic structure for your Django project.</p><h4>3. Create a Django App</h4><p>Inside your Django project directory (django_telegram_bot), create a new Django app named user_data</p><pre>cd django_telegram_botpython manage.py startapp user_data</pre><p>This command will create a new directory named user_data containing the files and directories required for a Django app.</p><h4>4. Add the App to Django Settings</h4><p>Open the settings.py file located in the django_telegram_bot directory. Add ‘user_data’ to the INSTALLED_APPS list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZWgulMqBUU-RBPy5LXbPQ.png" /><figcaption>Settings.py Additions</figcaption></figure><p>Adding ‘<strong>user_data</strong>’ to <strong>INSTALLED_APPS</strong> ensures that Django recognizes the user_data app and includes it in the project.</p><h3>2. Creating Models</h3><p>Define Django models to represent bot-related data. For example, you can create a UserData model to store user information such as ID, first name, last name, and username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbRSJVRVXFVJWzKB_wtd-A.png" /><figcaption>Models.py Model Definition</figcaption></figure><p>Within the UserData model, we define four fields:</p><p><strong>id</strong> : An IntegerField that serves as the primary key for each user. By default, Django adds an auto-incrementing primary key to every model if one isn’t specified explicitly. However, in this case, we’ve defined it explicitly to match the Telegram user ID, ensuring uniqueness.</p><p><strong>first_name </strong>: A CharField that stores the first name of the user. We specify a maximum length of 100 characters to ensure that the field doesn’t exceed a reasonable size.</p><p><strong>last_name</strong>: Similar to first_name, this field stores the last name of the user.</p><p><strong>username </strong>: A CharField that stores the username of the user. Telegram users may have usernames associated with their accounts, which can be useful for identification and communication within the platform.</p><p>This __str__ method defines how instances of the UserData model should be represented as strings. In this case, it returns a formatted string containing the user’s first name and last name, which is helpful for human-readable representation, especially in Django’s admin interface.</p><p>By defining the UserData model with these fields, we establish a structure for storing user data associated with our Telegram bot. This model will automatically create a corresponding database table when migrations are applied, facilitating data storage and retrieval within our Django application.</p><h4>Run Migrations</h4><p>Run database migrations to create the necessary database tables for the Django project and the user_data app</p><pre>python manage.py makemigrationspython manage.py migrate</pre><p>This command will create the initial database schema based on the models defined in your Django apps.</p><h3>3. Implementing Bot Logic</h3><p>let’s break down the code for implementing the bot logic using the python-telegram-bot library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ez4TYYtKZz8a4-RWBBYunA.png" /><figcaption>Bot.py imports</figcaption></figure><p>In the bot.py file, we import necessary modules and components required for building our Telegram bot</p><p><strong>os </strong>: This module provides a portable way of interacting with the operating system, allowing us to access environment variables and perform other system-related tasks.</p><p><strong>django </strong>: We import Django to ensure that our Django project is properly set up and can interact with the database.</p><p><strong>DATABASES </strong>: This import retrieves the database configuration from Django’s settings, which may be necessary for database operations within the bot logic.</p><p><strong>UserData </strong>: We import the UserData model from the user_data app, which we defined earlier. This allows us to interact with user data stored in the database.</p><p><strong>Update </strong>: This class represents an incoming update from Telegram, containing information about a message, callback query, or other interactions.</p><p><strong>Updater, CommandHandler, CallbackContext </strong>: These are classes from the python-telegram-bot library, which we use to set up and handle the bot’s interactions.</p><p><strong>load_dotenv :</strong> This function loads environment variables from a .env file, which is commonly used to store sensitive information like API tokens securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlHOT7nXXG5W30kdpUFrjg.png" /><figcaption>Bot.py start Function</figcaption></figure><p>This start function defines the logic for handling the /start command from users. When a user sends the /start command to the bot, this function is triggered. Here’s what it does</p><ul><li>It extracts the <strong>user_id</strong> from the incoming update using the <strong>effective_user.id</strong> attribute.</li><li>It tries to retrieve the user’s data from the database using the <strong>UserData.objects.get() </strong>method. If the user exists <strong>(DoesNotExist</strong> exception is not raised), it sends a welcome message addressing the user by their first name.</li><li>If the user does not exist (the <strong>DoesNotExist</strong> exception is raised), it creates a new <strong>UserData</strong> instance using information from the incoming update (first name, last name, username), saves it to the database, and sends a welcome message to the user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Yl_O8ria537RMOvtL61pg.png" /><figcaption>Bot.py main function</figcaption></figure><p>The main function is the entry point of our bot script. Here’s what it does</p><ul><li>It loads environment variables from the .<strong>env</strong> file using <strong>load_dotenv</strong>.</li><li>It retrieves the Telegram bot token from the environment variables.</li><li>It initializes an <strong>Updater</strong> instance with the bot token.</li><li>It retrieves the dispatcher from the <strong>Updater</strong>.</li><li>It adds a command handler for the<strong> /start</strong> command, specifying the start function as the handler.</li><li>It starts polling for updates from Telegram using <strong>updater.start_polling()</strong>.</li><li>It enters the main loop (<strong>updater.idle()</strong>) to continuously check for updates and handle them.</li></ul><h3>4. Running the Bot</h3><p>Run the Django development server and start the Telegram bot. Ensure that the bot is connected to the Telegram API and can respond to commands as expected.</p><pre>python bot.py</pre><p>This command will execute the bot.py file, starting the Telegram bot and enabling it to listen for incoming messages and commands from users. Make sure that you have activated your virtual environment (if you’re using one) and all necessary dependencies are installed.</p><p>Once the bot is running, it will continuously check for updates from Telegram and respond to user interactions according to the defined logic in the script.</p><h3>5. Conclusion</h3><p>Integrating Django as the backend for your Telegram bot offers numerous benefits, including robust database management, model architecture, scalability, and flexibility. By following best practices and leveraging Django’s features, you can develop powerful and reliable Telegram bots tailored to your specific requirements. Whether you’re building a bot for automation, customer support, or information retrieval, Django provides a solid foundation for creating efficient and maintainable solutions.</p><p>If you’re interested in exploring a complete project setup and detailed instructions, you can find the full project source code and instructions on my GitHub repository:</p><p><a href="https://github.com/yasanthaniroshan/TelegramBot_with_Django"><strong>GitHub Repository</strong></a></p><p>There, you’ll find the complete implementation of a Telegram bot with Django backend, along with step-by-step instructions to set up the project, integrate the bot with Django, and deploy it for your use case.</p><p>With the resources provided in the repository, you can further customize and extend the Telegram bot according to your needs, leveraging the power of Django’s web framework and the simplicity of Telegram bot development.</p><p>Feel free to explore the repository and contribute to the project to enhance its functionality and usability. Happy bot building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a87e5cc1226c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/3-steps-to-build-a-telegram-bot-with-django-python-a87e5cc1226c">3 Steps to Build a Telegram Bot with Django Backend</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing IoT Devices : Firmware Over-The-Air]]></title>
            <link>https://medium.com/@niroshanyi/revolutionizing-iot-devices-firmware-over-the-air-4b882ae2e776?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b882ae2e776</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[fota]]></category>
            <category><![CDATA[trends]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 14:32:14 GMT</pubDate>
            <atom:updated>2023-12-14T14:32:14.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionizing IoT Devices : Firmware Over-The-Air</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qkk-zkhulBFs16mOBz5VQ.jpeg" /></figure><h3>What is FOTA</h3><p><strong>Firmware Over-The-Air (FOTA)</strong> is a groundbreaking technology that allows the wireless updating of firmware or software on IoT (Internet of Things) devices. Unlike traditional methods that require physical connections or manual interventions, FOTA enables seamless updates through the Internet or cellular networks. This innovative approach has become a cornerstone in developing and maintaining IoT devices, offering unparalleled convenience and efficiency.</p><h3><strong>History of FOTA</strong></h3><p>The evolution of FOTA can be traced back to the early 2000s when mobile phones started incorporating the capability to receive software updates over the air. As technology advanced, the need for remote firmware updates became apparent in various industries, leading to the widespread adoption of FOTA in IoT devices. Over the years, FOTA has undergone significant improvements, addressing challenges and adapting to the ever-changing landscape of connected devices</p><h3><strong>Current Situation of FOTA Technology</strong></h3><p>FOTA has become an essential component of IoT device management in the current technological landscape. Manufacturers and developers leverage FOTA to ensure their devices remain up-to-date with the latest features, security patches, and bug fixes. This technology is extensively used in diverse sectors, including smart home devices, industrial IoT, healthcare, and automotive. The increasing complexity and connectivity of IoT ecosystems highlight the importance of FOTA in streamlining the update process and enhancing device performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwlHQkRFy4GODkGzyVAgtg.gif" /></figure><h3><strong>Advantages of FOTA</strong></h3><p>FOTA offers a myriad of advantages that contribute to its widespread adoption in IoT firmware development:</p><ul><li><strong>Remote Updates:</strong> FOTA eliminates the need for physical access to devices, enabling remote updates from anywhere in the world.</li><li><strong>Improved Security:</strong> Timely deployment of security patches ensures that devices are protected against emerging threats, enhancing overall cyber security.</li><li><strong>Enhanced Features:</strong> Manufacturers can introduce new features and improvements to devices without requiring users to replace or manually update their hardware.</li><li><strong>Reduced Downtime:</strong> FOTA minimizes downtime by streamlining the update process, allowing devices to stay operational while receiving updates in the background.</li><li><strong>Cost-Efficiency:</strong> The ability to update devices remotely reduces the costs associated with manual interventions and physical maintenance.</li></ul><h3><strong>Difficulties of FOTA:</strong></h3><p>While FOTA presents numerous advantages, it is essential to be aware of potential challenges:</p><ul><li><strong>Connectivity Issues:</strong> Poor network connectivity can hinder the FOTA process, leading to incomplete or failed updates.</li><li><strong>Data Security Concerns:</strong> Transmitting firmware updates over the air raises concerns about data security, making encryption and secure protocols crucial.</li><li><strong>Compatibility Challenges:</strong> Ensuring backward compatibility and seamless integration with various devices can be complex, especially in heterogeneous IoT environments.</li><li><strong>User Acceptance:</strong> Some users may need clarification about automatic updates, raising concerns about the reliability and stability of FOTA processes.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b882ae2e776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OctoIntel | Embedded Autonomous Devices]]></title>
            <link>https://medium.com/@niroshanyi/octointel-embedded-autonomous-devices-1aec9601f32b?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aec9601f32b</guid>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[intelligence]]></category>
            <category><![CDATA[autonomous]]></category>
            <category><![CDATA[octopus]]></category>
            <category><![CDATA[cognition]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 16:22:29 GMT</pubDate>
            <atom:updated>2023-12-05T16:22:29.007Z</atom:updated>
            <content:encoded><![CDATA[<p>Octopuses are amazing creatures that have fascinated scientists with their ability to adapt, learn, and process information. Researchers are interested in using these unique qualities to develop autonomous devices. This article will explore how octopuses adjust and learn, compare them with existing technologies, discuss potential advantages, and explore the challenges and opportunities of using these capabilities in real-world scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfO6dxTclnhWSbOyZff9Kw.jpeg" /></figure><h3>Adaptability and Learning</h3><p>Unlike many organisms, octopuses lack a rigid skeletal structure, enabling them to squeeze through tight spaces and manipulate objects with incredible talent. Their nervous system, distributed throughout their arms, allows for decentralized decision-making, facilitating rapid responses to changing conditions.</p><p>This decentralized nervous system contributes to their exceptional learning abilities. Octopuses exhibit complex problem-solving skills, learning from experience and adapting their behavior accordingly. These creatures are highly adaptable in different environments due to genetics and their interactions with the environment.</p><h3>Comparing with Existing Technologies:</h3><p>It’s incredible how far autonomous devices have come. Still, there’s something extraordinary about the adaptability and learning abilities of octopuses. While traditional AI and machine learning rely on centralized processing, octopuses excel in parallel processing. Each arm is capable of independent decision-making, which offers a decentralized and flexible model. It’s no wonder octopus-inspired technologies are becoming increasingly popular in robotics, surveillance, and environmental monitoring. They offer improved adaptability, faster learning, and better decision-making in dynamic environments. It’s exciting to see how these advancements can benefit us all.</p><h3>Use Cases</h3><p>Imagine a world where disaster-stricken areas can be navigated efficiently, ecosystems can be monitored with precision and manufacturing processes can be optimized to perfection. This world is not far from reality thanks to octopuses’ adaptability and learning capabilities. By implementing octopus-inspired intelligence in autonomous devices, we can enhance their ability to navigate complex and unpredictable environments, provide accurate and real-time data for environmental scientists, and optimize production lines, improving efficiency and reducing errors. The possibilities are endless, and the future is bright with octopus-inspired capabilities.</p><figure><img alt="Octopuses are the master architects,with incredible intelligence and adaptability" src="https://cdn-images-1.medium.com/max/1024/1*th-47OBhWWAT6Y01XjrWVg.jpeg" /><figcaption>Octopuses are the master architects,with incredible intelligence and adaptability</figcaption></figure><h3>Implementation in Real-World Situations:</h3><p>Drawing inspiration from the remarkable abilities of octopuses, researchers are developing cutting-edge algorithms and neural network architectures to imbue autonomous devices with similar capabilities. By emulating the decentralized nervous system of these incredible creatures, algorithms can be designed to distribute processing power across multiple nodes, enabling rapid adaptation and parallel decision-making. Reinforcement learning models are also being incorporated to allow devices to learn from their environment and adjust their behaviour over time. By integrating sensors and actuators in a modular fashion, similar to the arms of an octopus, these devices can easily interact with their surroundings and perform complex tasks. The possibilities are endless, and the future of autonomous devices looks brighter than ever.</p><h3>Challenges in Implementation:</h3><p>While the potential benefits are promising, there are challenges associated with implementing octopus-inspired capabilities in embedded devices. Designing algorithms that effectively mimic the decentralized nature of the octopus nervous system while maintaining efficiency is a complex task. Ensuring seamless communication between different processing nodes is essential for achieving parallel processing without sacrificing performance.<br>Additionally, ethical considerations and potential unintended consequences must be addressed. As autonomous devices become more sophisticated, questions about privacy, security, and the ethical use of such technology arise, requiring careful consideration and regulation.</p><h3>Conclusion:</h3><p>Exploring octopus adaptability, learning, and parallel processing presents many opportunities for advancing embedded autonomous devices. By embracing the decentralized and flexible nature of octopus intelligence, researchers can pave the way for innovative solutions in robotics, artificial intelligence, and beyond. Although challenges may arise, the potential benefits make this avenue of exploration a compelling frontier in the quest for creating highly adaptable and intelligent autonomous systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aec9601f32b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Fast and Robust APIs with FastAPI and SQL Databases]]></title>
            <link>https://medium.com/towards-data-engineering/fastapi-with-sql-1c7852ccbf21?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c7852ccbf21</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 07:00:23 GMT</pubDate>
            <atom:updated>2023-09-30T15:57:58.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnPRoj1pqv1uuSv8pHtnCg.png" /></figure><p>In the realm of web development, the creation of fast and dependable APIs is an essential aspect. One noteworthy and modern Python web framework that has gained popularity among developers is FastAPI. This framework is known for its swiftness, user-friendliness, and robustness. When it comes to storing and retrieving data, SQL databases are a common choice due to their reliability and maturity. This article will delve into using FastAPI in tandem with SQL databases to create powerful and efficient APIs.</p><h3>FastAPI: A Brief Introduction</h3><p>FastAPI is a web framework that facilitates speedy API development with Python. It stands out for its high performance, automatic validation, and automatic documentation generation. With FastAPI, you can build RESTful APIs with minimal boilerplate code, which makes it an ideal choice for projects of all sizes.</p><h4>Installation</h4><p>You can install FastAPI, Uvicorn and Sqlalchemy using pip:</p><pre>pip install &quot;fastapi[all]&quot; uvicorn[standard] sqlalchemy</pre><p>make a main.py add following to that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*333YBe_NYZWZAKbMAcMpuw.png" /></figure><p>You can run this application with:</p><pre>uvicorn main:app --reload</pre><p>Visit local host address displayed in terminal and you’ll see the “Hello, World!” message.</p><h3>SQL Databases with FastAPI</h3><p>Integrating SQL databases with FastAPI is straightforward, and you have multiple choices for your database system. For this example, we’ll use SQLite, a lightweight and serverless database.</p><h4>SQLAlchemy</h4><p>It’s a library that offers a range of tools for interacting with databases. You can use a low-level SQL interface to write custom queries, or a high-level ORM to define and manipulate database structures with Python classes and objects. SQLAlchemy is a popular choice for simplifying database operations, supporting multiple database backends, and promoting more efficient ways of working with relational databases in Python applications.</p><h4>ORM (Object Relational Mapper)</h4><p>In SQLAlchemy, you can use an Object Relational Mapper (ORM) to simplify your interactions with databases. This high-level abstraction allows you to work with Python objects and classes that directly correspond to database tables and relationships. By defining your database models using Python classes, you can specify the schema, relationships, and constraints. The ORM in SQLAlchemy makes it easy to query, insert, update, and delete records in the database without having to write underlying SQL queries. This tool bridges the gap between the object-oriented world of Python and the relational world of databases, making it simpler and more intuitive to work with databases in your Python applications.</p><h4>Configuration of a SQLAlchemy Database</h4><p>Let’s configure a SQLite database and set up the connection :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEcfXyHX-hJosWz6gtBzjA.png" /></figure><p>Above Python script configures a SQLAlchemy-based database interaction environment. It defines a DATABASE_URL pointing to an SQLite database file, creates a database engine with additional configuration for SQLite thread safety, establishes a session factory with options to control transaction behavior, and sets up a base class for declarative database models. This configuration is essential for connecting to and interacting with a SQLite database using SQLAlchemy, a popular Object-Relational Mapping (ORM) library in Python.</p><h4>Definition of a SQLAlchemy Database Model</h4><p>Then we have to model the database tables :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdVVacP4yfvLR20LNjuiSw.png" /></figure><p>In above code snippet, a SQLAlchemy database model class called User is defined, inheriting from the Base class, which was imported from a module named database we defined before. This class represents a database table named “users.” It contains four columns: id, name, email, and nickname. The id column is defined as an integer and serves as the primary key for the table, ensuring each row has a unique identifier. The other columns, name, email, and nickname, are defined as string fields. This class and its column definitions provide a structured blueprint for creating and interacting with a “users” table in the database using SQLAlchemy, specifying the data types and constraints for each column.</p><h4>Defining a Data Schema</h4><p>Now we have to define schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sIl3Yz-ehTaTeWl6lOKdHw.png" /></figure><p>In the above code , a Pydantic BaseModel named UserSchema is defined, serving as a structured data schema for representing user information. It consists of four attributes: id (an integer for the user’s unique identifier), name (a string for the user’s name), email (a string for the user’s email address), and nickname (a string for the user’s nickname). Pydantic’s BaseModel offers data validation and serialization capabilities, making it well-suited for tasks like validating and parsing incoming data in web applications, as well as serializing data for API responses, ensuring that data adheres to the specified schema.</p><h4>Modify main.py</h4><p>As the last step we have to modify main.py for handle the requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkJGUtNa1aetUjQFTy4V6A.png" /></figure><p>This code establishes a FastAPI application for managing user data with an SQLite database backend. It begins by importing necessary modules and creating database tables based on SQLAlchemy models. The FastAPI application instance is initialized, and a function called get_db is defined to manage database sessions. The application has three route handlers: one for a root URL that responds with a “Hello, World!” message, another for adding user data through an HTTP POST request, and a third for retrieving user data based on the provided username via an HTTP GET request. SQLAlchemy is used for database interactions, while Pydantic sachems ensure data validation and serialization. The get_db function manages the database sessions to maintain proper resource handling throughout the application.</p><h3>Testing Application</h3><p>Quickly navigate the URL provided in terminal and enter ‘docs’ to end of the URL(<a href="http://127.0.0.1:8000/docs">example</a>). Then you will see a window like follow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*is03IUREthkoQVOABplB4w.png" /></figure><p>Then you can change the parameters and add users.Although you can get user by username.You can use database browser to check whether actual data is stored in above database !</p><h4>GitHub Source Files</h4><p>You can find all source codes from <a href="https://github.com/yasanthaniroshan/FastAPI_SQL_Databases">here</a>!</p><h3>Conclusion</h3><p>FastAPI, combined with SQL databases like SQLite, provides an efficient and developer-friendly way to create powerful APIs. In this article, we’ve covered the basics of setting up FastAPI and integrating it with an SQL database. With FastAPI’s automatic validation and documentation generation, you can focus on building your API’s functionality while ensuring it remains robust and performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c7852ccbf21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/fastapi-with-sql-1c7852ccbf21">Building Fast and Robust APIs with FastAPI and SQL Databases</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kill or Save?]]></title>
            <link>https://medium.com/@niroshanyi/kill-or-save-80ea39096388?source=rss-ce5e468ed76c------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ea39096388</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[positivity]]></category>
            <category><![CDATA[library-management-system]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Yasantha Niroshan]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 13:01:50 GMT</pubDate>
            <atom:updated>2023-07-18T13:01:50.308Z</atom:updated>
            <content:encoded><![CDATA[<h4>Will Generative AI Save Us? Exploring the Positive Side of Generative AI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvW2n0xQlpU8ngbiSZf4DA.jpeg" /></figure><p>Last week, I used the Django framework to simulate a Library Management System. First, I started to do it myself from scratch. But suddenly, I got an idea, and I prompted Chat GPT. It gave terrific responses. So, I started to prompt ChatGPT to generate most of the content. I only had to clarify what needed to be developed.</p><p>As a critical point, I was able to complete this work in<strong> less than one and a half hours!</strong></p><p>The Generation of codes was not surprising using ChatGPT. But when requesting mobile-responsive GUI elements with unique properties, it produced fantastic results. It did better when I requested Django functions, HTML, CSS, and JS.</p><p>While generating code, it produced errors, and I had to request the same thing repetitively. However, I realized that it gave incredible results when I asked for point-by-point with descriptive requests.<br>When I prompted error messages with relevant code blocks, Then it corrected faulty parts in the code block. <br>Although, it can produce new code blocks quickly by referring to older generated code blocks</p><p>Here are some web pages generated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6tnTbseRgEljO33thzA8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNRwNSP69-WD-SDTuIMWBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elYWL6oH0dcznosoN5rkWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UaOStlE0JbsKHxKIfZjbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpPv8AXPq3uGloZp0AULSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZ3KoUjdg2eOGNUwHL2wbw.png" /><figcaption>Screenshots of Different Pages</figcaption></figure><p>Here is the GitHub repository of <a href="https://github.com/yasanthaniroshan/Library-Management-System">Library-Management-System</a></p><p>Here are some of prompts I used <a href="https://chat.openai.com/share/42c03dbd-c008-4c98-817e-42e3a92e9216">ChatGPT Prompts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ea39096388" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>