{"id":150411,"date":"2024-07-23T17:23:10","date_gmt":"2024-07-23T17:23:10","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=150411"},"modified":"2024-07-23T18:44:37","modified_gmt":"2024-07-23T18:44:37","slug":"micropython-timer-interrupts-ep32-esp8266","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/micropython-timer-interrupts-ep32-esp8266\/","title":{"rendered":"MicroPython: Timer Interrupts with the ESP32\/ESP8266"},"content":{"rendered":"\n<p>In this guide, you&#8217;ll learn how to use timer interrupts (timers and event handling) with the ESP32 and ESP8266 programmed with MicroPython. Timer interrupts allow you to schedule and execute specific tasks at regular intervals or after a designated time delay.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Timer-Interrupts-MicroPython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython Timer Interrupts with the ESP32 ESP8266 NodeMCU\" class=\"wp-image-150497\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Timer-Interrupts-MicroPython.jpg?w=1920&amp;quality=100&amp;strip=all&amp;ssl=1 1920w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Timer-Interrupts-MicroPython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Timer-Interrupts-MicroPython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Timer-Interrupts-MicroPython.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Timer-Interrupts-MicroPython.jpg?resize=1536%2C864&amp;quality=100&amp;strip=all&amp;ssl=1 1536w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p><strong>Table of Contents:<\/strong><\/p>\n\n\n\n<p>In this tutorial, we&#8217;ll cover the following subjects:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#interrupts-intro\" title=\"\">Introducing Interrupts<\/a>\n<ul class=\"wp-block-list\">\n<li><a href=\"#types-interrupts\" title=\"\">Types of Interrupts<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><a href=\"#micropython-timer\" title=\"\">The MicroPython class <em>Timer<\/em><\/a>\n<ul class=\"wp-block-list\">\n<li><a href=\"#creating-timer\" title=\"\">Creating a Timer<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><a href=\"#timer-interrupts-esp32-esp8266\" title=\"\">Timer Interrupts with the ESP32\/ESP8266<\/a>\n<ul class=\"wp-block-list\">\n<li><a href=\"#blink-led-timer\" title=\"\">Example 1: Blinking an LED with a Timer<\/a><\/li>\n\n\n\n<li><a href=\"#blink-multiple-leds-different-frequencies\" title=\"\">Example 2: Blinking Multiple LEDs at Different Frequencies<\/a><\/li>\n\n\n\n<li><a href=\"#debouncing-pushbutton-timer\" title=\"\">Example 3: Debouncing a Pushbutton with a Timer<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before proceeding with this tutorial, make sure you check the following prerequisites<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MicroPython Firmware<\/h3>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-thumbnail\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"150\" height=\"150\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/02\/micropython-logo.png?resize=150%2C150&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"micorpython logo\" class=\"wp-image-148797\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/02\/micropython-logo.png?resize=150%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 150w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/02\/micropython-logo.png?w=250&amp;quality=100&amp;strip=all&amp;ssl=1 250w\" sizes=\"(max-width: 150px) 100vw, 150px\" \/><\/figure><\/div>\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Thonny IDE:\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-thonny-micropython-python-ide-esp32-esp8266\/\">Installing and getting started with Thonny IDE<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/flashing-micropython-firmware-esptool-py-esp32-esp8266\/\">Flashing MicroPython Firmware with esptool.py<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>uPyCraft IDE:\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">Getting Started with uPyCraft IDE<\/a><\/li>\n\n\n\n<li>Install uPyCraft IDE (<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-windows-pc-instructions\/\">Windows<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-mac-os-x-instructions\/\">Mac OS X<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-linux-ubuntu-instructions\/\">Linux<\/a>)<\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/flash-upload-micropython-firmware-esp32-esp8266\/\">Flash\/Upload MicroPython Firmware to ESP32 and ESP8266<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p>If you like to program using VS Code, there&#8217;s also an option: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-esp32-esp8266-vs-code-pymakr\/\">MicroPython: Program ESP32\/ESP8266 using VS Code and Pymakr<\/a><\/p>\n\n\n\n<p class=\"rntbox rntclblue\">Learn more about MicroPython:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\">MicroPython Programming with ESP32 and ESP8266<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Parts Required<\/h3>\n\n\n\n<p>To complete the examples in this tutorial you need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\" rel=\"noreferrer noopener\">ESP32<\/a> or <a href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\" rel=\"noopener\" title=\"\">ESP8266<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener\" title=\"\">2x LEDs<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">2x 220 Ohm resistor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Pushbutton<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Jumper wires<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"interrupts-intro\">Introducing Interrupts<\/h2>\n\n\n\n<p>Interrupts are useful for making things happen automatically in microcontroller programs and can help solve timing problems. Interrupts and event handling provide mechanisms to respond to events, enabling the ESP32\/ESP8266  to react quickly to changes without continuous polling (continuously checking the current value of a pin or variable or continuously checking the time).<\/p>\n\n\n\n<p>Using timer interrupts is especially useful to make something happen periodically or after a predefined period without constantly checking the elapsed time.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"types-interrupts\">Types of Interrupts<\/h3>\n\n\n\n<p>There are different types of interrupts: external interrupts and timed interrupts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>External Interrupts<\/strong>: triggered by external signals such as a button press or a sensor reading\u2014this is hardware-based and associated with a specific GPIO pin. When the state of a pin changes, it will trigger a task\u2014learn more about external interrupts with the ESP32\/ESP8266 in this article: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-interrupts-esp32-esp8266\/\">MicroPython: External Interrupts with ESP32 and ESP8266<\/a>.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Timed Interrupts (timers)<\/strong>: initiated based on time intervals, enabling periodic actions\u2014 this uses the boards&#8217; hardware timer to trigger callbacks at regular intervals. We&#8217;ll take a look at this kind of interrupts in this article.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"micropython-timer\">The MicroPython class <em>Timer<\/em><\/h2>\n\n\n\n<p>The MicroPython <span class=\"rnthl rntliteral\">machine<\/span> module comes with a class called <span class=\"rnthl rntliteral\">Timer<\/span> that provides methods to execute a callback function periodically within a given period or once after some predefined delay. This is useful for scheduling events or running periodic tasks without constantly checking the elapsed time.<\/p>\n\n\n\n<p>Let\u2019s take a quick look at the <span class=\"rnthl rntliteral\">Timer<\/span> constructors.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"creating-timer\">Creating a Timer<\/h3>\n\n\n\n<p>To create a timer, you simply need to call the <span class=\"rnthl rntliteral\">Timer()<\/span> constructor and pass as argument the timer id, as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>my_timer = Timer(id)<\/code><\/pre>\n\n\n\n<p>Then, you initialize a timer using the <span class=\"rnthl rntliteral\">init()<\/span> method on the <span class=\"rnthl rntliteral\">Timer()<\/span> object and you pass as argument the timer mode, period, and the callback function. Here\u2019s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>my_timer.init(mode=Timer.PERIODIC, period=1000, callback=timer_callback)<\/code><\/pre>\n\n\n\n<p>This initializes a periodic timer that will run the <span class=\"rnthl rntliteral\">timer_callback<\/span> function every 1000 milliseconds (1 second). You can change the period parameter to any desired period.<\/p>\n\n\n\n<p>Instead of calling the callback function periodically, you may also want to run it once after a predefined time. For that, you can use the <span class=\"rnthl rntliteral\">Timer.ONE_SHOT<\/span> mode as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>my_timer.init(mode=Timer.ONE_SHOT, period=1000, callback=timer_callback)<\/code><\/pre>\n\n\n\n<p>This line of code configures a timer (<span class=\"rnthl rntliteral\">my_timer<\/span>) to run in a one-shot mode, triggering the specified callback function (<span class=\"rnthl rntliteral\">timer_callback<\/span>) after 1000 milliseconds.<\/p>\n\n\n\n<p>Learn more about the <a href=\"https:\/\/docs.micropython.org\/en\/latest\/library\/machine.Timer.html\" target=\"_blank\" rel=\"noopener\" title=\"\">Timer class in the MicroPython documentation<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"timer-interrupts-esp32-esp8266\">Timer Interrupts with the ESP32\/ESP8266<\/h2>\n\n\n\n<p>We&#8217;ll now take a look at different application scenarios of timer interrupts with the ESP32\/ESP8266.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#blink-led-timer\" title=\"\">Blinking an LED with a Timer<\/a><\/li>\n\n\n\n<li><a href=\"#blink-multiple-leds-different-frequencies\" title=\"\">Blinking Multiple LEDs at Different Frequencies<\/a><\/li>\n\n\n\n<li><a href=\"#debouncing-pushbutton-timer\" title=\"\">Debouncing a Pushbutton with a Timer<\/a><\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"blink-led-timer\">1. Blinking an LED with a Timer &#8211; MicroPython<\/h3>\n\n\n\n<p>In this example, you\u2019ll learn how to blink an LED using a Timer. This will help you understand how periodic timers work.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Circuit Diagram<\/h4>\n\n\n\n<p>We\u2019ll blink an LED connected to GPIO 13. So, wire an LED to the ESP32 or ESP8266 on that GPIO. You can use the following diagrams as a reference.<\/p>\n\n\n\n<p><strong>ESP32<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"788\" height=\"774\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-with-LED-circuit.png?resize=788%2C774&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Blink an LED with a Timer (MicroPython) Circuit\" class=\"wp-image-150434\" style=\"width:470px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-with-LED-circuit.png?w=788&amp;quality=100&amp;strip=all&amp;ssl=1 788w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-with-LED-circuit.png?resize=300%2C295&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-with-LED-circuit.png?resize=768%2C754&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 788px) 100vw, 788px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclblue\">Recommended reading: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-pinout-reference-gpios\/\" title=\"\">ESP32 Pinout Reference: Which GPIO pins should you use?<\/a><\/p>\n\n\n\n<p><strong>ESP8266 NodeMCU<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"575\" height=\"875\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-LED_circuit.png?resize=575%2C875&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 Blink an LED with a Timer (MicroPython) Circuit\" class=\"wp-image-150440\" style=\"width:470px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-LED_circuit.png?w=575&amp;quality=100&amp;strip=all&amp;ssl=1 575w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-LED_circuit.png?resize=197%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 197w\" sizes=\"(max-width: 575px) 100vw, 575px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclblue\">Recommended reading:<a href=\"https:\/\/randomnerdtutorials.com\/esp8266-pinout-reference-gpios\/\" title=\"\"> ESP8266 Pinout Reference: Which GPIO pins should you use?<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code<\/h4>\n\n\n\n<p>The following example uses the <span class=\"rnthl rntliteral\">Timer<\/span> class to blink an LED every half a second. This code is compatible with ESP32 and ESP8266 boards.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/micropython-timer-interrupts-ep32-esp8266\/\r\n\r\nfrom machine import Pin, Timer\r\nfrom time import sleep\r\n\r\n# LED pin\r\nled_pin = 13\r\nled = Pin(led_pin, Pin.OUT)\r\n\r\n# Callback function for the timer\r\ndef toggle_led(timer):\r\n    led.value(not led.value())  # Toggle the LED state (ON\/OFF)\r\n\r\n# Create a periodic timer\r\nblink_timer = Timer(1)\r\nblink_timer.init(mode=Timer.PERIODIC, period=500, callback=toggle_led)  # Timer repeats every half second\r\n\r\ntry:\r\n    # Main loop (optional)\r\n    while True:\r\n        print('Main Loop is running')\r\n        sleep(2)\r\nexcept KeyboardInterrupt:\r\n    # Keyboard interrupt occurred, deinitialize the timer\r\n    blink_timer.deinit()\r\n    print('Timer deinitialized')\r\n    # Turn off the LED\r\n    led.value(0)\r\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/esp_blink_led_timer.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>In this code, we create a timer called <span class=\"rnthl rntliteral\">blink_timer<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>blink_timer = Timer(1)<\/code><\/pre>\n\n\n\n<p>Then, we initialize the timer with the following parameters:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>blink_timer.init(mode=Timer.PERIODIC, period=500, callback=toggle_led)<\/code><\/pre>\n\n\n\n<p>This means this timer will call the <span class=\"rnthl rntliteral\">toggle_led<\/span> function every 500, forever (or until you stop the program).<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">toggle_led<\/span> function, as the name suggests, will toggle the LED state:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Callback function for the timer\ndef toggle_led(timer):\n    led.value(not led.value())  # Toggle the LED state (ON\/OFF)<\/code><\/pre>\n\n\n\n<p>The timer callback functions must have one argument that is passed automatically by the <span class=\"rnthl rntliteral\">Timer<\/span> object when the event is triggered.<\/p>\n\n\n\n<p>With timers, you can also have other tasks running on the main loop without interfering with each other. For example, in our case, in the main loop, we\u2019ll print a message every two seconds.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>while True:\n    print('Main Loop is running')\n    sleep(2)<\/code><\/pre>\n\n\n\n<p>When the user stops the program (<span class=\"rnthl rntliteral\">KeyboardInterrupt<\/span>), we deinitialize the timer using the <span class=\"rnthl rntliteral\">deinit()<\/span> method and turn off the LED.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except KeyboardInterrupt:\n    # Keyboard interrupt occurred, deinitialize the timer\n    blink_timer.deinit()\n    print('Timer deinitialized')\n    # Turn off the LED\n    led_pin.value(0)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Testing the Code<\/h4>\n\n\n\n<p>With an LED connected to GPIO 13, run the previous code on your board.<\/p>\n\n\n\n<p>You\u2019ll get the message \u201cMain Loop is running\u201d every two seconds on the Shell, while the LED is blinking every half a second at the same time.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"729\" height=\"302\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/blinking-led-timer-esp32-esp8266.png?resize=729%2C302&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 ESP8266 MicroPython testing blinking led with timer\" class=\"wp-image-150435\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/blinking-led-timer-esp32-esp8266.png?w=729&amp;quality=100&amp;strip=all&amp;ssl=1 729w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/blinking-led-timer-esp32-esp8266.png?resize=300%2C124&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 729px) 100vw, 729px\" \/><\/figure><\/div>\n\n\n<div class=\"wp-block-jetpack-tiled-gallery aligncenter is-style-rectangular\"><div class=\"\"><div class=\"tiled-gallery__gallery\"><div class=\"tiled-gallery__row\"><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-1.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-1.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"\" data-height=\"421\" data-id=\"150437\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=150437#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-1.jpg\" data-width=\"750\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-1.jpg?ssl=1\" data-amp-layout=\"responsive\" aria-label=\"Open image 1 of 2 in full-screen\"\/><\/figure><\/div><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-2.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-2.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"\" data-height=\"421\" data-id=\"150438\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=150438#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-2.jpg\" data-width=\"750\" src=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-blinking-led-2.jpg?ssl=1\" data-amp-layout=\"responsive\" aria-label=\"Open image 2 of 2 in full-screen\"\/><\/figure><\/div><\/div><\/div><\/div><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"blink-multiple-leds-different-frequencies\">2. Blinking Multiple LEDs at Different Frequencies<\/h3>\n\n\n\n<p>After testing the previous example, it\u2019s easy to understand that if you create multiple timers, you can run multiple tasks at different frequencies. In this example, we\u2019ll blink two different LEDs. One will blink every half a second, and the other one every two seconds.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Circuit Diagram<\/h4>\n\n\n\n<p>Wire two LEDs to the ESP32\/ESP8266 (to distinguish between the different LEDs, we\u2019ll use different colors):<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Red LED: GPIO 13\u2014will blink every half a second;<\/li>\n\n\n\n<li>Yellow LED: GPIO 12\u2014will blink every two seconds.<\/li>\n<\/ul>\n\n\n\n<p>You can use the following diagrams as a reference to wire the circuit.<\/p>\n\n\n\n<p><strong>ESP32<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"670\" height=\"823\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-with-two-LEDs-circuit.png?resize=670%2C823&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 blink two LEDs at different frequencies with micropython\" class=\"wp-image-150442\" style=\"width:470px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-with-two-LEDs-circuit.png?w=670&amp;quality=100&amp;strip=all&amp;ssl=1 670w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-with-two-LEDs-circuit.png?resize=244%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 244w\" sizes=\"(max-width: 670px) 100vw, 670px\" \/><\/figure><\/div>\n\n\n<p><strong>ESP8266 NodeMCU<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"647\" height=\"857\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-2-LEDs_bb_circuit.png?resize=647%2C857&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 blink two LEDs at different frequencies with micropython\" class=\"wp-image-150444\" style=\"width:470px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-2-LEDs_bb_circuit.png?w=647&amp;quality=100&amp;strip=all&amp;ssl=1 647w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-2-LEDs_bb_circuit.png?resize=226%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 226w\" sizes=\"(max-width: 647px) 100vw, 647px\" \/><\/figure><\/div>\n\n\n<h4 class=\"wp-block-heading\">Code<\/h4>\n\n\n\n<p>The following code uses Timers to blink two different LEDs at different frequencies. The code is compatible with ESP32 and ESP8266 boards.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/micropython-timer-interrupts-ep32-esp8266\/\r\n \r\nfrom machine import Pin, Timer\r\nfrom time import sleep\r\n\r\n# LEDs\r\nred_led_pin = 12\r\nred_led = Pin(red_led_pin, Pin.OUT)\r\nyellow_led_pin = 13\r\nyellow_led = Pin(yellow_led_pin, Pin.OUT)\r\n\r\n# Callback function for the red timer\r\ndef toggle_red_led(timer):\r\n    red_led.value(not red_led.value())  # Toggle the LED state (ON\/OFF)\r\n    print('red LED is: ', red_led.value())\r\n\r\n# Callback function for the yellow timer\r\ndef toggle_yellow_led(timer):\r\n    yellow_led.value(not yellow_led.value())  # Toggle the LED state (ON\/OFF)\r\n    print('yellow LED is: ', yellow_led.value())\r\n\r\n# Create periodic timers\r\nred_timer = Timer(1)\r\nyellow_timer = Timer(2)\r\n\r\n# Init the timers\r\nred_timer.init(mode=Timer.PERIODIC, period=500, callback=toggle_red_led)  # Timer repeats every 0.5 second\r\nyellow_timer.init(mode=Timer.PERIODIC, period=2000, callback=toggle_yellow_led)  # Timer repeats every 2 seconds\r\n\r\ntry:\r\n    # Main loop (optional)\r\n    while True:\r\n        print('Main Loop is running')\r\n        sleep(2)\r\n        \r\nexcept KeyboardInterrupt:\r\n    # Keyboard interrupt occurred, deinitialize the timers\r\n    red_timer.deinit()\r\n    yellow_timer.deinit()\r\n    print('Timers deinitialized')\r\n    # Turn off the LEDs\r\n    yellow_led.value(0)\r\n    red_led.value(0)\r\n\r\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/esp_blink_two_leds_timer.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>In this code, we create two different timers, one for each LED:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Create periodic timers\nred_timer = Timer(1)\nyellow_timer = Timer(2)<\/code><\/pre>\n\n\n\n<p>Then, we call the corresponding callback functions at different intervals:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Init the timers\nred_timer.init(mode=Timer.PERIODIC, period=500, callback=toggle_red_led)  # Timer repeats every 0.5 second\nyellow_timer.init(mode=Timer.PERIODIC, period=2000, callback=toggle_yellow_led)  # Timer repeats every 2 seconds<\/code><\/pre>\n\n\n\n<p>The callback functions simply toggle the current LED value:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Callback function for the red timer\ndef toggle_red_led(timer):\n    red_led.value(not red_led.value())  # Toggle the LED state (ON\/OFF)\n    print('red LED is: ', red_led.value())\n\n# Callback function for the yellow timer\ndef toggle_yellow_led(timer):\n    yellow_led.value(not yellow_led.value())  # Toggle the LED state (ON\/OFF)\n    print('yellow LED is: ', yellow_led.value())<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Testing the Code<\/h4>\n\n\n\n<p>Run the previous code on the ESP32 or ESP8266. You\u2019ll notice that the two LEDs will blink at different frequencies.<\/p>\n\n\n\n<div class=\"wp-block-jetpack-tiled-gallery aligncenter is-style-rectangular\"><div class=\"\"><div class=\"tiled-gallery__gallery\"><div class=\"tiled-gallery__row\"><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/1-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/1-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"ESP32 ESP8266 Blinking LEDs at different rates\" data-height=\"422\" data-id=\"150464\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=150464#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/1-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg\" data-width=\"750\" src=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/1-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?ssl=1\" data-amp-layout=\"responsive\" aria-label=\"Open image 1 of 4 in full-screen\"\/><\/figure><\/div><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/2-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/2-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"ESP32 ESP8266 Blinking LEDs at different rates\" data-height=\"422\" data-id=\"150465\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=150465#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/2-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg\" data-width=\"750\" src=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/2-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?ssl=1\" data-amp-layout=\"responsive\" aria-label=\"Open image 2 of 4 in full-screen\"\/><\/figure><\/div><\/div><div class=\"tiled-gallery__row\"><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/3-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/3-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"ESP32 ESP8266 Blinking LEDs at different rates\" data-height=\"422\" data-id=\"150466\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=150466#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/3-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg\" data-width=\"750\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/3-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?ssl=1\" data-amp-layout=\"responsive\" aria-label=\"Open image 3 of 4 in full-screen\"\/><\/figure><\/div><div class=\"tiled-gallery__col\" style=\"flex-basis:50.00000%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/4-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/4-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?strip=info&#038;w=750&#038;ssl=1 750w\" alt=\"ESP32 ESP8266 Blinking LEDs at different rates\" data-height=\"422\" data-id=\"150467\" data-link=\"https:\/\/randomnerdtutorials.com\/?attachment_id=150467#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/4-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg\" data-width=\"750\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/4-ESP32-ESP8266-blinking-leds-with-timers.JPG.jpg?ssl=1\" data-amp-layout=\"responsive\" aria-label=\"Open image 4 of 4 in full-screen\"\/><\/figure><\/div><\/div><\/div><\/div><\/div>\n\n\n\n<p>At the same time, you\u2019ll get a message from the while loop every two seconds. This shows that the other tasks don\u2019t interfere with our loop.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"672\" height=\"375\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Blinking-LEDs-timers-micropython.png?resize=672%2C375&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 ESP8266 MicroPython blinking LEDs with different frequencies using timers\" class=\"wp-image-150463\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Blinking-LEDs-timers-micropython.png?w=672&amp;quality=100&amp;strip=all&amp;ssl=1 672w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Blinking-LEDs-timers-micropython.png?resize=300%2C167&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 672px) 100vw, 672px\" \/><\/figure><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"debouncing-pushbutton-timer\">3. Debouncing a Pushbutton with a Timer<\/h3>\n\n\n\n<p>Button bouncing is when the pushbutton will count more than one press when in fact, you just pressed one time. This is very common in mechanical buttons like pushbuttons.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"860\" height=\"529\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/debouncing-pushbutton.jpg?resize=860%2C529&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Debouncing a pushbutton with a timer\" class=\"wp-image-150468\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/debouncing-pushbutton.jpg?w=860&amp;quality=100&amp;strip=all&amp;ssl=1 860w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/debouncing-pushbutton.jpg?resize=300%2C185&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/debouncing-pushbutton.jpg?resize=768%2C472&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 860px) 100vw, 860px\" \/><\/figure><\/div>\n\n\n<p>This happens because the electrical contacts inside the button connect and disconnect very quickly before reaching a steady state, which will cause the system to register multiple press events, causing an inaccurate count. To prevent this issue, we can add some debouncing techniques using delays or timers.<\/p>\n\n\n\n<p>In this example, we&#8217;ll take a look at how you can use timers and events to debounce a pushbutton.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Circuit Diagram<\/h4>\n\n\n\n<p>For this example, wire an LED (GPIO 13) and a pushbutton (GPIO12) to the ESP32 and ESP8266.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>LED (GPIO 13)<\/li>\n\n\n\n<li>Pushbutton (GPIO 12)<\/li>\n<\/ul>\n\n\n\n<p>You can use the following schematic diagrams as a reference.<\/p>\n\n\n\n<p><strong>ESP32<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"692\" height=\"855\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-LED-pushbutton_bb-1.png?resize=692%2C855&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 MicroPython debounce pushbutton with a timer\" class=\"wp-image-150504\" style=\"width:470px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-LED-pushbutton_bb-1.png?w=692&amp;quality=100&amp;strip=all&amp;ssl=1 692w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-LED-pushbutton_bb-1.png?resize=243%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 243w\" sizes=\"(max-width: 692px) 100vw, 692px\" \/><\/figure><\/div>\n\n\n<p><strong>ESP8266 NodeMCU<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"625\" height=\"854\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-LED-pushbutton_bb.png?resize=625%2C854&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-150505\" style=\"width:470px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-LED-pushbutton_bb.png?w=625&amp;quality=100&amp;strip=all&amp;ssl=1 625w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP8266-LED-pushbutton_bb.png?resize=220%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 220w\" sizes=\"(max-width: 625px) 100vw, 625px\" \/><\/figure><\/div>\n\n\n<h4 class=\"wp-block-heading\">Code<\/h4>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/micropython-timer-interrupts-ep32-esp8266\/\r\n \r\nfrom machine import Pin, Timer\r\nimport time\r\n\r\nled = Pin(13, Pin.OUT)\r\nbutton = Pin(12, Pin.IN, Pin.PULL_UP)\r\ncounter = 0  # Initialize the button press count\r\ndebounce_timer = None\r\n\r\ndef button_pressed(pin):\r\n    global counter, debounce_timer  # Declare variables as global\r\n\r\n    if debounce_timer is None:\r\n        counter += 1\r\n        print(&quot;Button Pressed! Count: &quot;, counter)\r\n        \r\n        # Toggle the LED on each button press\r\n        led.value(not led.value())\r\n\r\n        # Start a timer for debounce period (e.g., 200 milliseconds)\r\n        debounce_timer = Timer(1)\r\n        debounce_timer.init(mode=Timer.ONE_SHOT, period=200, callback=debounce_callback)\r\n\r\ndef debounce_callback(timer):\r\n    global debounce_timer\r\n    debounce_timer = None\r\n\r\n# Attach the interrupt to the button's rising edge\r\nbutton.irq(trigger=Pin.IRQ_RISING, handler=button_pressed)\r\n\r\ntry:\r\n    # Main loop (optional)\r\n    while True:\r\n        print(&quot;Loop is running&quot;)\r\n        time.sleep(5)\r\nexcept KeyboardInterrupt:\r\n    # Keyboard interrupt occurred, deinitialize the timer\r\n    debounce_timer.deinit()\r\n    # Turn off the LED\r\n    led.value(0)<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/esp_debounce_pushbutton_timer.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How the Code Works<\/h4>\n\n\n\n<p>Let&#8217;s take a quick look at how we use timers to debounce a pushbutton.<\/p>\n\n\n\n<p class=\"rntbox rntclgreen\"><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-digital-inputs-digital-outputs-micropython\/\" title=\"\">Related content: ESP32\/ESP8266 Digital Inputs and Digital Outputs with MicroPython<\/a><\/p>\n\n\n\n<p>This example uses a one-shot timer (<span class=\"rnthl rntliteral\">debounce_timer<\/span>) initiated on each button press with a specified debounce period, in this example 200 milliseconds. You may increase the debouncing period if you&#8217;re still getting false positives.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>debounce_timer.init(mode=Timer.ONE_SHOT, period=200, callback=debounce_callback)<\/code><\/pre>\n\n\n\n<p>To detect a pushbutton press, we use external interrupts. The the <span class=\"rnthl rntliteral\">button_pressed<\/span> function will be triggered on rising mode (when the button is pressed).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>button.irq(trigger=Pin.IRQ_RISING, handler=button_pressed)<\/code><\/pre>\n\n\n\n<p class=\"rntbox rntclblue\">Related content: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-interrupts-esp32-esp8266\/\">MicroPython: Interrupts with ESP32 and ESP8266<\/a>.<\/p>\n\n\n\n<p>When the button is pressed, the <span class=\"rnthl rntliteral\">button_pressed<\/span> function is called, incrementing the <span class=\"rnthl rntliteral\">counter<\/span>, toggling the LED, and starting the one-shot timer for debounce.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>counter += 1\nprint(\"Button Pressed! Count: \", counter)\n        \n# Toggle the LED on each button press\nled.value(not led.value())\n\n# Start a timer for debounce period (e.g., 200 milliseconds)\ndebounce_timer = Timer(1)\ndebounce_timer.init(mode=Timer.ONE_SHOT, period=200, callback=debounce_callback)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">debounce_callback<\/span> function of the timer is called when the one-shot timer expires, resetting the <span class=\"rnthl rntliteral\">debounce_timer<\/span> to <span class=\"rnthl rntliteral\">None<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def debounce_callback(timer):\n    global debounce_timer\n    debounce_timer = None<\/code><\/pre>\n\n\n\n<p>If the timer hasn\u2019t yet expired, if another button press is detected, it will not be accounted for because the <span class=\"rnthl rntliteral\">debounce_timer<\/span> hasn\u2019t been reset to <span class=\"rnthl rntliteral\">None<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>if debounce_timer is None:<\/code><\/pre>\n\n\n\n<p>Notice that we make use of global variables so that we can access them throughout all parts of the code including inside the functions:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>global counter, debounce_timer  # Declare variables as global<\/code><\/pre>\n\n\n\n<p>This is just one of the many ways to debounce a pushbutton.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>The use of <em>None<\/em><\/strong><\/h5>\n\n\n\n<p>In Python\/MicroPython, <span class=\"rnthl rntliteral\">None<\/span> is often used as a placeholder or default value to indicate the absence of a meaningful value. In this previous example, <span class=\"rnthl rntliteral\">None<\/span> helps us manage the state of the <span class=\"rnthl rntliteral\">debounce_timer<\/span> variable.<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">debounce_timer<\/span> is initially set to <span class=\"rnthl rntliteral\">None<\/span> to indicate that no debounce timer is currently active.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>debounce_timer = None<\/code><\/pre>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">button_pressed<\/span> function, the following condition checks if there is no active debounce timer.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>if debounce_timer is None:<\/code><\/pre>\n\n\n\n<p>If there is no active timer (<span class=\"rnthl rntliteral\">None<\/span>), the button press actions are performed, and a new one-shot timer, <span class=\"rnthl rntliteral\">debounce_timer<\/span>, is initiated.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>debounce_timer = Timer(1)\ndebounce_timer.init(mode=Timer.ONE_SHOT, period=200, callback=debounce_callback)<\/code><\/pre>\n\n\n\n<p>When the one-shot timer expires, the <span class=\"rnthl rntliteral\">debounce_callback<\/span> function is called, and it sets <span class=\"rnthl rntliteral\">debounce_timer<\/span> back to <span class=\"rnthl rntliteral\">None<\/span>, indicating that the debounce period has ended.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def debounce_callback(timer):\n    global debounce_timer\n    debounce_timer = None<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Testing the Code<\/h4>\n\n\n\n<p>Run the code on your ESP32\/ESP8266. Press the push button multiple times. You\u2019ll notice that you won\u2019t get false positives and it will count the number of times the pushbutton was pressed.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"729\" height=\"306\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-debouncing-pushbutton-micropython.png?resize=729%2C306&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Testing Debouncing pushbutton with timer ESP32 and ESP8266 MicroPython\" class=\"wp-image-150475\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-debouncing-pushbutton-micropython.png?w=729&amp;quality=100&amp;strip=all&amp;ssl=1 729w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-debouncing-pushbutton-micropython.png?resize=300%2C126&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 729px) 100vw, 729px\" \/><\/figure><\/div>\n\n\n<p>If you get false positives, you need to increase the 200 milliseconds debounce period on the <span class=\"rnthl rntliteral\">debounce_timer<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>debounce_timer.init(mode=Timer.ONE_SHOT, <strong>period=200<\/strong>, callback=debounce_callback)<\/code><\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-debouncing-pushbutton.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Debouncing pushbutton with a timer ESP32 and ESP8266 MicroPython\" class=\"wp-image-150476\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-debouncing-pushbutton.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-debouncing-pushbutton.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to use timer interrupts with the ESP32 and ESP8266 programmed with MicroPython. Using timer interrupts is useful to make things happen periodically without having to constantly check the elapsed time.<\/p>\n\n\n\n<p>We have a tutorial about external interrupts that you may find useful: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-interrupts-esp32-esp8266\/\">MicroPython: Interrupts with ESP32 and ESP8266<\/a>.<\/p>\n\n\n\n<p>Learn more about MicroPython with our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\" title=\"\">MicroPython Programming with ESP32 and ESP8266 eBook<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32-esp8266-micropython\/\" title=\"\">Free MicroPython Projects and Tutorials<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, you&#8217;ll learn how to use timer interrupts (timers and event handling) with the ESP32 and ESP8266 programmed with MicroPython. Timer interrupts allow you to schedule and execute &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"MicroPython: Timer Interrupts with the ESP32\/ESP8266\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/micropython-timer-interrupts-ep32-esp8266\/#more-150411\" aria-label=\"Read more about MicroPython: Timer Interrupts with the ESP32\/ESP8266\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":150497,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[310,309,264],"tags":[],"class_list":["post-150411","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-micropython","category-0-esp32-micropython","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/ESP32-ESP8266-Timer-Interrupts-MicroPython.jpg?fit=1920%2C1080&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/150411","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=150411"}],"version-history":[{"count":17,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/150411\/revisions"}],"predecessor-version":[{"id":161043,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/150411\/revisions\/161043"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/150497"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=150411"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=150411"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=150411"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}