{"id":136663,"date":"2024-04-03T16:00:13","date_gmt":"2024-04-03T16:00:13","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=136663"},"modified":"2024-05-06T11:00:22","modified_gmt":"2024-05-06T11:00:22","slug":"raspberry-pi-pico-motion-pir-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-motion-pir-micropython\/","title":{"rendered":"Raspberry Pi Pico: Detect Motion using a PIR Sensor (MicroPython)"},"content":{"rendered":"\n<p>Learn how to interface a PIR motion sensor with the Raspberry Pi Pico to detect motion in your surroundings. We\u2019ll show you how to wire the sensor to the Pico board and we&#8217;ll program the board using MicroPython firmware to execute a certain task when motion is detected.<\/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\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-MicroPython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Detect Motion using a PIR Sensor MicroPython\" class=\"wp-image-136742\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-MicroPython.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-MicroPython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-MicroPython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-MicroPython.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p><strong>Table of Contents:<\/strong><\/p>\n\n\n\n<p>Throughout this tutorial, we&#8217;ll cover the following topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#motion-sensor-intro\" title=\"Introducing the PIR Motion Sensor\">Introducing the PIR Motion Sensor<\/a><\/li>\n\n\n\n<li><a href=\"#Raspberry-Pi-Motion-Sensor-circuit\" title=\"\">Wiring a PIR Motion Sensor to the Pi Pico<\/a><\/li>\n\n\n\n<li><a href=\"#Pi-Pico-detect-motion-micropython\" title=\"\">PIR Motion Sensor &#8211; Detect Motion (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"#intro-interrupts\" title=\"\">Introducing Interrupts<\/a>\n<ul class=\"wp-block-list\">\n<li><a href=\"#pi-pico-interrupt-micropython\" title=\"\">Raspberry Pi Pico Setting Up an Interrupt in MicroPython<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><a href=\"#pi-pico-pir-micropython-code\" title=\"\">Raspberry Pi Pico with PIR Motion Sensor Using Interrupts &#8211; MicroPython Code<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">Prerequisites \u2013 MicroPython Firmware<\/h2>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.<\/p>\n\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\">Programming Raspberry Pi Pico using MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"motion-sensor-intro\">Introducing the PIR Motion Sensor<\/h2>\n\n\n\n<p>A PIR motion sensor detects changes in infrared light in its field of view. This makes it ideal for detecting humans or animals because it will pick up living things (or heat-emitting objects) that move within their range but not inanimate objects. <\/p>\n\n\n\n<p>You can program the Pi to react to changes in infrared light by triggering an event such as turning on a light, sounding an alarm, sending a notification, or any other task. In this tutorial, we&#8217;ll print a message on the console, and we&#8217;ll light up an LED.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/AM312-PIR-Motion-Sensor.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"AM312 PIR Motion Sensor Pinout labeled\" class=\"wp-image-130668\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/AM312-PIR-Motion-Sensor.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/04\/AM312-PIR-Motion-Sensor.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><figcaption class=\"wp-element-caption\">Mini AM312 PIR Motion Sensor<\/figcaption><\/figure><\/div>\n\n\n<p>There are different PIR motion sensor modules, but all act in a similar way. You&#8217;ll have a power pin, GND, and data. <\/p>\n\n\n\n<p>The PIR motion sensor outputs a <strong>HIGH <\/strong>signal on the Data pin when it detects movement, or a <strong>LOW <\/strong>signal if it doesn&#8217;t. It only has three pins: <strong>VCC<\/strong>, <strong>GND, <\/strong>and <strong>Data<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"358\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-How-it-works.png?resize=1024%2C358&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"How a PIR Motion sensor works\" class=\"wp-image-136745\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-How-it-works.png?resize=1024%2C358&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-How-it-works.png?resize=300%2C105&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-How-it-works.png?resize=768%2C268&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-How-it-works.png?resize=1536%2C537&amp;quality=100&amp;strip=all&amp;ssl=1 1536w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-How-it-works.png?resize=2048%2C716&amp;quality=100&amp;strip=all&amp;ssl=1 2048w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-How-it-works.png?w=2400&amp;quality=100&amp;strip=all&amp;ssl=1 2400w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n<p>Some models like the HC-SR501 might have two potentiometers (those two orange potentiometers in the picture below) to adjust the sensitivity and the time delay.<\/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=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/HC-SR501-Motion-Sensor.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HC-SR501 PIR Motion Sensor\" class=\"wp-image-136744\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/HC-SR501-Motion-Sensor.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/HC-SR501-Motion-Sensor.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><figcaption class=\"wp-element-caption\">HC-SR501 PIR Motion Sensor<\/figcaption><\/figure><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sensitivity potentiometer:<\/strong> this adjusts the sensor&#8217;s detection range. Clockwise increases sensitivity, counterclockwise decreases it.<\/li>\n\n\n\n<li><strong>Time delay potentiometer:<\/strong> this controls how long the sensor remains triggered after detecting motion. Clockwise increases the delay, and counterclockwise decreases it.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"Raspberry-Pi-Motion-Sensor-circuit\">Wiring a PIR Motion Sensor to the Pi Pico<\/h2>\n\n\n\n<p>The PIR motion sensor has three pins: VCC, GND, and Data. You should connect VCC to the 3V3 pin (or 5V depending on the model), GND to a GND pin, and the Data pin to a suitable Raspberry Pi Pico GPIO\u2014we&#8217;ll connect it to GPIO 22 (<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\" title=\"\">take a look at the Raspberry Pi Pico pinout<\/a>). We&#8217;ll also add an LED to GPIO 21 to add visual feedback to your project.<\/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=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-Raspberry-Pi-Pico-LED-Circuit.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"PIR Motion Sensor with Raspberry Pi Pico Circuit\" class=\"wp-image-136747\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-Raspberry-Pi-Pico-LED-Circuit.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/PIR-Motion-Sensor-Raspberry-Pi-Pico-LED-Circuit.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<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>PIR Motion Sensor<\/strong><\/td><td><strong>Raspberry Pi<\/strong><\/td><\/tr><tr><td><strong>Vin\/3v3<\/strong><\/td><td>3.3V or 5V depending on the model<\/td><\/tr><tr><td><strong>Data<\/strong><\/td><td>GPIO 22 (or another GPIO of your choice)<\/td><\/tr><tr><td><strong>GND<\/strong><\/td><td>GND<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>We&#8217;ll use the <a href=\"https:\/\/makeradvisor.com\/tools\/mini-hc-sr505-pir-motion-sensor\/\" target=\"_blank\" rel=\"noopener\" title=\"\">AM312 Mini PIR Motion<\/a> sensor because it works with 3V3 volts, which is perfect for the Raspberry Pi. But you can use any other PIR motion sensor module. The working principle is the same.<\/p>\n\n\n\n<p>Here&#8217;s a list of components you need for this project:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-pico-w\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico board<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mini-hc-sr505-pir-motion-sensor\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Mini PIR Motion Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener\" title=\"\">LED<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">220 Ohm resistor<\/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<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"586\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/raspberry-pi-pico-pir-motion-sensor-circuit.png?resize=1024%2C586&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Motion Sensor Circuit\" class=\"wp-image-136755\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/raspberry-pi-pico-pir-motion-sensor-circuit.png?resize=1024%2C586&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/raspberry-pi-pico-pir-motion-sensor-circuit.png?resize=300%2C172&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/raspberry-pi-pico-pir-motion-sensor-circuit.png?resize=768%2C440&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/raspberry-pi-pico-pir-motion-sensor-circuit.png?w=1149&amp;quality=100&amp;strip=all&amp;ssl=1 1149w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"Pi-Pico-detect-motion-micropython\">PIR Motion Sensor &#8211; Detect Motion (MicroPython)<\/h2>\n\n\n\n<p>There are many different ways to write a program to detect motion using a PIR motion sensor. The simplest way is to simply read the state of the PIR sensor as you would read any other <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-outputs-inputs-micropython\/\" title=\"\">digital input<\/a>.<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-motion-pir-micropython\/\n\nfrom machine import Pin\nfrom time import sleep\n\npir_pin = Pin(22, Pin.IN)\nled_pin = Pin (21, Pin.OUT)\n\nwhile True:\n    if pir_pin.value():\n        print(&quot;Motion detected!&quot;)\n        led_pin.value(1)\n    sleep(1)\n    led_pin.value(0)\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/PIR_Detect_Motion.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>However, this might not be the best solution, because the PIR motion sensor data pin stays in a HIGH state for a few seconds before getting back to LOW. The best way is to detect the precise moment when the state goes from LOW to HIGH (rising mode) and have a better responsiveness. For that, we can use <strong>interrupts<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"intro-interrupts\">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. With interrupts, you don\u2019t need to constantly check the current pin value. When a change is detected, an event is triggered (a function is called\u2014this function is often called an ISR (interrupt service routine).<\/p>\n\n\n\n<p>When an interrupt happens, the processor stops the execution of the main program to execute a task, and then gets back to the main program as shown in the figure below.<\/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=\"992\" height=\"291\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/03\/interrupt.png?resize=992%2C291&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Interrupts Raspberry Pi Pico\" class=\"wp-image-81979\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/03\/interrupt.png?w=992&amp;quality=100&amp;strip=all&amp;ssl=1 992w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/03\/interrupt.png?resize=300%2C88&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/03\/interrupt.png?resize=768%2C225&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 992px) 100vw, 992px\" \/><\/figure><\/div>\n\n\n<p>This is especially useful to trigger an action whenever motion is detected or whenever a pushbutton is pressed without the need for constantly checking its state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"pi-pico-interrupt-micropython\">Raspberry Pi Pico Setting Up an Interrupt in MicroPython<\/h3>\n\n\n\n<p>To set up an interrupt in MicroPython, you need to follow the next steps:<\/p>\n\n\n\n<p><strong>1. Define an interrupt handling function<\/strong> (ISR). The interrupt handling function should be as simple as possible, so the processor gets back to the execution of the main program quickly. The best approach is to signal the main code that the interrupt has happened by using a global variable, for example.<\/p>\n\n\n\n<p>The interrupt handling function should accept a parameter of type <span class=\"rnthl rntliteral\">Pin<\/span>. This parameter is returned to the callback function and it refers to the GPIO that caused the interrupt. You should avoid doing tasks that take a long time inside the ISR. You should also avoid using the regular <span class=\"rnthl rntliteral\">print<\/span> function inside.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def handle_interrupt(pin):<\/code><\/pre>\n\n\n\n<p><strong>2.<\/strong> Set up the GPIO that will act as an interrupt pin as an input. For example, in our case we&#8217;re using GPIO 22:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>pir = Pin(22, Pin.IN)<\/code><\/pre>\n\n\n\n<p><strong>3. <\/strong>Attach an interrupt to that pin by calling the <span class=\"rnthl rntliteral\">irq()<\/span> method:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>pir.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">irq()<\/span> method accepts the following arguments: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>trigger:<\/strong> this defines the trigger mode. There are different conditions in MicroPython:\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">Pin.IRQ_FALLING<\/span>: to trigger the interrupt whenever the pin goes from HIGH to LOW;<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">Pin.IRQ_RISING<\/span>: to trigger the interrupt whenever the pin goes from LOW to HIGH.<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">Pin.IRQ_LOW_LEVEL<\/span>: interrupt occurs when a pin is LOW (not supported on the Pico board at the time of writing this article).<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">Pin.IRQ_HIGH_LEVEL<\/span>: interrupt occurs when a pin is HIGH (not supported on the Pico board at the time of writing this article).<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">Pin.IRQ_FALLING | Pin.IRQ_RISING<\/span>: interrupt on both the rising edge and the falling edge.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>handler:<\/strong> this is a function that will be called when an interrupt is detected, in this case, the <span class=\"rnthl rntliteral\">handle_interrupt()<\/span> function.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"pi-pico-pir-micropython-code\">Raspberry Pi Pico with PIR Motion Sensor Using Interrupts &#8211; MicroPython Code<\/h2>\n\n\n\n<p>The following MicroPython code for the Raspberry Pi Pico monitors a PIR motion sensor connected. When the PIR sensor detects motion, it turns on an LED for visual feedback and prints &#8220;Motion detected!&#8221; to the console. When motion stops, it turns off the LED and prints &#8220;Motion stopped&#8221; to the console. The code continuously runs in a loop until interrupted by a keyboard command or when an exception occurs.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-motion-pir-micropython\/\n\nfrom machine import Pin\nfrom time import sleep\n\n# Define the PIR sensor input pin\npir_pin = Pin(22, Pin.IN)\n\n# Define the LED pin (optional, for visual feedback)\nled_pin = Pin(21, Pin.OUT)\n\n# Flags to indicate motion detection state\nmotion_detected = False\n\nmotion_stopped_printed = False\n\n# Callback function to handle motion detection\ndef pir_interrupt(pin):\n    global motion_detected\n    if pin.value() == 1:  # Rising edge (motion detected)\n        motion_detected = True\n        led_pin.value(1)  # Turn on the LED\n    else:  # Falling edge (motion stopped)\n        motion_detected = False\n        led_pin.value(0)  # Turn off the LED\n\n# Configure the interrupt on the PIR pin for both rising and falling edges\npir_pin.irq(trigger=(Pin.IRQ_RISING | Pin.IRQ_FALLING), handler=pir_interrupt)\n\ntry:\n    while True:\n        if motion_detected and not motion_stopped_printed:\n            print(&quot;Motion detected!&quot;)\n            motion_stopped_printed = True  # Set the flag to indicate motion detected\n\n        elif not motion_detected and motion_stopped_printed:\n            print(&quot;Motion stopped&quot;)\n            motion_stopped_printed = False  # Reset the flag\n\n        sleep(0.1)  # Main loop delay\n\nexcept KeyboardInterrupt:\n    print(&quot;Keyboard interrupt&quot;)\n    pir_pin.irq(trigger=0)  # Disable the interrupt\n    led_pin.value(0)  # Turn off the LED\n    \nexcept Exception as e:\n    print(&quot;An unexpected exception occurred:&quot;, e)\t\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/PIR_Detect_Motion_Interrupt.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How Does the Code Work?<\/h3>\n\n\n\n<p>Continue reading to learn how the code works or skip to the <a href=\"#demonstration\" title=\"\">Demonstration <\/a>section.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Importing Libraries<\/h4>\n\n\n\n<p>The following lines import the necessary libraries for working with GPIO pins and implementing time delays.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from machine import Pin\nfrom time import sleep<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Pin Definitions<\/h4>\n\n\n\n<p>In this section, the code defines the pins for the PIR sensor input and an optional LED for visual feedback. We&#8217;re connecting the sensor to GPIO 22 and the LED to GPIO 21. Alternatively, you can use any other suitable pins (just make sure you modify the code with the pins you&#8217;re using).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Define the PIR sensor input pin\npir_pin = Pin(22, Pin.IN)\n\n# Define the LED pin (optional, for visual feedback)\nled_pin = Pin(21, Pin.OUT)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Motion Detection Flags<\/h4>\n\n\n\n<p>We create two variables to indicate the state of motion detection. The <span class=\"rnthl rntliteral\">motion_detected<\/span> is set to <span class=\"rnthl rntliteral\">True<\/span> when motion is detected, and the <span class=\"rnthl rntliteral\">motion_stopped_printed<\/span> is used to track whether the &#8220;Motion stopped&#8221; message has been printed on the console (this is to prevent writing the same message multiple times when motion is not being detected).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Flags to indicate motion detection state\nmotion_detected = False\n\nmotion_stopped_printed = False<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Callback Function for Motion Detection<\/h4>\n\n\n\n<p>A callback function named <span class=\"rnthl rntliteral\">pir_interrupt<\/span> is defined to handle the interrupts generated by the PIR sensor. This function will be called every time motion is detected. <\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Callback function to handle motion detection\ndef pir_interrupt(pin):\n    global motion_detected\n    if pin.value() == 1:  # Rising edge (motion detected)\n        motion_detected = True\n        led_pin.value(1)  # Turn on the LED\n    else:  # Falling edge (motion stopped)\n        motion_detected = False\n        led_pin.value(0)  # Turn off the LED<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">pir_interrupt<\/span> function has an input parameter (<span class=\"rnthl rntliteral\">pin<\/span>) in which an object of class <span class=\"rnthl rntliteral\">Pin<\/span> will be passed when the interrupt happens (it indicates which pin caused the interrupt).<\/p>\n\n\n\n<p>This function toggles the <span class=\"rnthl rntliteral\">motion_detected<\/span> variable and controls the LED based on the rising and falling edges of the PIR sensor signal. If the <span class=\"rnthl rntliteral\">pin.value()<\/span> is <span class=\"rnthl rntliteral\">1<\/span>, which means the PIR sensor data pin is HIGH, we set the <span class=\"rnthl rntliteral\">motion_detected<\/span> variable to <span class=\"rnthl rntliteral\">True<\/span> and turn on the LED.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>if pin.value() == 1:  # Rising edge (motion detected)\n    motion_detected = True\n    led_pin.value(1)  # Turn on the LED<\/code><\/pre>\n\n\n\n<p>If <span class=\"rnthl rntliteral\">pin.value()<\/span> is not <span class=\"rnthl rntliteral\">1<\/span>, it means that the PIR motion sensor data pin went from HIGH to LOW. So, we can set the <span class=\"rnthl rntliteral\">motion_detected<\/span> variable to <span class=\"rnthl rntliteral\">False<\/span> and turn off the LED because motion is no longer detected.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>else:  # Falling edge (motion stopped)\n    motion_detected = False\n    led_pin.value(0)  # Turn off the LED<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Configuring Interrupts<\/h4>\n\n\n\n<p>The following line configures the interrupt on the PIR pin to trigger on both rising and falling edges. The <span class=\"rnthl rntliteral\">pir_interrupt<\/span> function will be called when these edges are detected. This means we&#8217;ll detect when motion is detected and when motion stops being detected.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>pir_pin.irq(trigger=(Pin.IRQ_RISING | Pin.IRQ_FALLING), handler=pir_interrupt)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">While Loop<\/h4>\n\n\n\n<p>The main loop continuously checks the state of the <span class=\"rnthl rntliteral\">motion_detected<\/span> variable and provides feedback accordingly. It prints messages when motion is detected or stopped. To prevent printing the same message multiple times, we also check the state of the <span class=\"rnthl rntliteral\">motion_stopped_printed<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    while True:\n        if motion_detected and not motion_stopped_printed:\n            print(\"Motion detected!\")\n            motion_stopped_printed = True  # Set the flag to indicate motion detected\n\n        elif not motion_detected and motion_stopped_printed:\n            print(\"Motion stopped\")\n            motion_stopped_printed = False  # Reset the flag\n\n        sleep(0.1)  # Main loop delay<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Exception Handling<\/h3>\n\n\n\n<p>The code includes exception handling to handle keyboard interrupts (e.g., when stopping the script) and other unexpected exceptions. It disables the interrupt and turns off the LED when the script is stopped.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except KeyboardInterrupt:\n    print(\"Keyboard interrupt\")\n    pir_pin.irq(trigger=0)  # Disable the interrupt\n    led_pin.value(0)  # Turn off the LED\n    \nexcept Exception as e:\n    print(\"An unexpected exception occurred:\", e)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"demonstration\">Demonstration<\/h2>\n\n\n\n<p>Save the code to your Raspberry Pi Pico board using&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\">Thonny IDE<\/a>&nbsp;or any other MicroPython IDE of your choice.<\/p>\n\n\n\n<p>Copy the code provided to a new file on Thonny IDE.<\/p>\n\n\n\n<p>With the code copied to the file, click on the&nbsp;<strong>Save&nbsp;<\/strong>icon. Then, select&nbsp;<strong>Raspberry Pi Pico<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"214\" height=\"203\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Save-file-to-Raspberry-Pi-Pico.png?resize=214%2C203&amp;quality=100&amp;strip=all&amp;ssl=1\" alt=\"Saving file to Raspberry Pi Pico MicroPython IDE\" class=\"wp-image-130899\"\/><\/figure><\/div>\n\n\n<p>Save the file with the following name:&nbsp;<strong>main.py<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"545\" height=\"327\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/micropython-main-py-file.png?resize=545%2C327&amp;quality=100&amp;strip=all&amp;ssl=1\" alt=\"Micropython saving main.py file Thonny IDE\" class=\"wp-image-132452\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/micropython-main-py-file.png?w=545&amp;quality=100&amp;strip=all&amp;ssl=1 545w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/micropython-main-py-file.png?resize=300%2C180&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 545px) 100vw, 545px\" \/><\/figure><\/div>\n\n\n<p><strong>Note:<\/strong> when you name a file&nbsp;<em>main.py<\/em>, the Raspberry Pi Pico will run that file automatically on boot. If you call it a different name, it will still be saved on the board filesystem, but it will not run automatically on boot.<\/p>\n\n\n\n<p>Click the little green button \u201cRun Current Script\u201d or press F5.<\/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=\"450\" height=\"78\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/thonny-ide-run-code.png?resize=450%2C78&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"run script on thonny ide\" class=\"wp-image-132505\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/thonny-ide-run-code.png?w=450&amp;quality=100&amp;strip=all&amp;ssl=1 450w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/06\/thonny-ide-run-code.png?resize=300%2C52&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 450px) 100vw, 450px\" \/><\/figure><\/div>\n\n\n<p>Now, test your setup. Wave your hand in front of the motion sensor. It will print &#8220;Motion Detected!&#8221; in the console.<\/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=\"685\" height=\"265\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/detect-motion-raspberry-pi-pico-thonny-ide.png?resize=685%2C265&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico MicroPython Thonny IDE PIR Motion sensor detect motion\" class=\"wp-image-136734\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/detect-motion-raspberry-pi-pico-thonny-ide.png?w=685&amp;quality=100&amp;strip=all&amp;ssl=1 685w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/detect-motion-raspberry-pi-pico-thonny-ide.png?resize=300%2C116&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 685px) 100vw, 685px\" \/><\/figure><\/div>\n\n\n<p>And the LED will light up. The LED will be lit as long as the PIR sensor data pin is high (this might depend on the PIR sensor model you&#8217;re using).<\/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=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-Detect-Motion-Demonstration.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico PIR Motion Sensor Detect Motion Demonstration Example\" class=\"wp-image-136749\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-Detect-Motion-Demonstration.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-Detect-Motion-Demonstration.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<p>After a few seconds, if motion is no longer detected. You&#8217;ll get a &#8220;motion stopped&#8221; message and the LED will turn off.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to use a PIR sensor with the Raspberry Pi Pico to detect motion. You learned how to use interrupts to execute tasks when motion is detected. <\/p>\n\n\n\n<p>To keep things simple, we just turned an LED on and off. In a real-world scenario, you may want to send a notification to your smartphone, send an email, turn on a lamp, send a message via MQTT, or any other task.<\/p>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. We have other Raspberry Pi Pico tutorials that you may like:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-outputs-inputs-micropython\/\">Raspberry Pi Pico: Control Digital Outputs and Read Digital Inputs (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-pwm-micropython\/\">Raspberry Pi Pico: PWM Fading an LED (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-dht11-dht22-micropython\/\">Raspberry Pi Pico: DHT11\/DHT22 Temperature and Humidity Sensor (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"#https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-ds18b20-micropython\/\" title=\"\">Raspberry Pi Pico: DS18B20 Temperature Sensor (MicroPython) \u2013 Single and Multiple<\/a><\/li>\n<\/ul>\n\n\n\n<p><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\">Check out all our Raspberry Pi Pico Guides \u00bb<\/a><\/p>\n\n\n\n<p>Learn more about the Raspberry Pi Pico with our exclusive eBook:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\" title=\"\">Learn Raspberry Pi Pico with MicroPython (eBook)<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to interface a PIR motion sensor with the Raspberry Pi Pico to detect motion in your surroundings. We\u2019ll show you how to wire the sensor to the Pico &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico: Detect Motion using a PIR Sensor (MicroPython)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-motion-pir-micropython\/#more-136663\" aria-label=\"Read more about Raspberry Pi Pico: Detect Motion using a PIR Sensor (MicroPython)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":136742,"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":[324,326],"tags":[],"class_list":["post-136663","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-micropython"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/09\/Raspberry-Pi-Pico-PIR-Motion-Sensor-MicroPython.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/136663","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=136663"}],"version-history":[{"count":17,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/136663\/revisions"}],"predecessor-version":[{"id":154880,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/136663\/revisions\/154880"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/136742"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=136663"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=136663"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=136663"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}