{"id":149479,"date":"2024-03-08T11:38:39","date_gmt":"2024-03-08T11:38:39","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=149479"},"modified":"2024-12-16T16:13:07","modified_gmt":"2024-12-16T16:13:07","slug":"raspberry-pi-pico-w-asynchronous-web-server-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-asynchronous-web-server-micropython\/","title":{"rendered":"Raspberry Pi Pico W: Asynchronous Web Server (MicroPython)"},"content":{"rendered":"\n<p>In this guide, you\u2019ll learn how to build a basic asynchronous local web server with the Raspberry Pi Pico W programmed with MicroPython using the <em>asyncio <\/em>module. Using an asynchronous approach, the Raspberry Pi Pico W can handle multiple clients at a time and can also do other tasks while still waiting for clients to connect.<\/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\/Raspberry-Pi-Pico-Async-Web-Server-Micropython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico W Asynchronous Web Server MicroPython\" class=\"wp-image-149494\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Async-Web-Server-Micropython.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Async-Web-Server-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\/Raspberry-Pi-Pico-Async-Web-Server-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\/Raspberry-Pi-Pico-Async-Web-Server-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>We\u2019ll create a web page to control an LED on and off and fetch some random values generated by the Pico. At the same time, the Pico will continuously blink an LED and run some tasks in the loop to show the asynchronous nature of the program. This example can be easily modified or extended to control multiple outputs and fetch data from sensors instead of random numbers.<\/p>\n\n\n\n<p>This project is similar to this one (<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\" title=\"\">Raspberry Pi Pico: Web Server &#8211; MicroPython)<\/a>, but uses asynchronous programming.<\/p>\n\n\n\n<p class=\"rntbox rntclblue\">Want to learn more about <strong>asynchronous programming<\/strong>? Get started with this guide: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-raspberry-pi-pico-asynchronous-programming\/\">Raspberry Pi Pico Asynchronous Programming \u2013 Run Multiple Tasks (MicroPython)<\/a><\/p>\n\n\n\n<p class=\"rntbox rntclgreen\">This tutorial is <strong>only compatible with the Raspberry Pi Pico W<\/strong> that comes with Wi-Fi support. Throughout this tutorial whenever we refer to the Raspberry Pi Pico, we&#8217;re referring to the Raspberry Pi Pico W.<\/p>\n\n\n\n<p class=\"rntbox rntclgray\"><strong>New to the Raspberry Pi Pico?<\/strong> Start here: <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/\" title=\"\">Getting Started with Raspberry Pi Pico<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">Prerequisites<\/h2>\n\n\n\n<p>Before proceeding, make sure you check the following prerequisites.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"prerequisites\">MicroPython Firmware<\/h3>\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<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"725\" height=\"569\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/message-after-installing-micropython-Raspberry-Pi-Pico.png?resize=725%2C569&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython Firmware Raspberry Pi Pico Board\" class=\"wp-image-130894\" style=\"width:463px;height:auto\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/message-after-installing-micropython-Raspberry-Pi-Pico.png?w=725&amp;quality=100&amp;strip=all&amp;ssl=1 725w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/message-after-installing-micropython-Raspberry-Pi-Pico.png?resize=300%2C235&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 725px) 100vw, 725px\" \/><\/figure><\/div>\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is <strong>Thonny IDE<\/strong>. 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<h3 class=\"wp-block-heading\">Basic Web Server Concepts<\/h3>\n\n\n\n<p>If you&#8217;re not familiar with basic web server concepts, we recommend following the next tutorial first:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\" title=\"\">Raspberry Pi Pico: Web Server (MicroPython)<\/a><\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"317\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Web-Server-example-1024x317.png?resize=1024%2C317&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Basic Web Server Concepts Raspberry Pi Pico W Board\" class=\"wp-image-144691\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Web-Server-example.png?resize=1024%2C317&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Web-Server-example.png?resize=300%2C93&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Web-Server-example.png?resize=768%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Web-Server-example.png?w=1135&amp;quality=100&amp;strip=all&amp;ssl=1 1135w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"project-overview\">Raspberry Pi Pico Asynchronous Web Server &#8211; Project Overview<\/h2>\n\n\n\n<p>Let\u2019s take a quick look at the project we\u2019ll build so that it\u2019s easier to understand the code later on.<\/p>\n\n\n\n<p>This web server behaves exactly <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\" title=\"\">like the one in this project<\/a>, but it is asynchronous and non-blocking allowing you to handle multiple clients simultaneously and do other tasks while waiting for client requests.<\/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\/2024\/03\/Raspberry-Pi-Pico-Async-Web-Server.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Asynchronous web server\" class=\"wp-image-149488\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Async-Web-Server.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Async-Web-Server.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>Here\u2019s what our example does:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Creates a web server that serves a web page with:<ul><li>two buttons to control an LED on and off (GPIO 19)<\/li><\/ul>\n<ul class=\"wp-block-list\">\n<li>a section to display a random value (can be replaced with sensor readings)<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>It runs a concurrent task that blinks an LED (GPIO 20)<\/li>\n\n\n\n<li>It also does other things in the main loop while still listening to client requests.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"716\" height=\"471\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-WebServer.png?resize=716%2C471&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Basic Web Server\" class=\"wp-image-144652\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-WebServer.png?w=716&amp;quality=100&amp;strip=all&amp;ssl=1 716w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-WebServer.png?resize=300%2C197&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 716px) 100vw, 716px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgreen\"><strong>Want to learn more about the Raspberry Pi Pico?<\/strong> Take a look at our ebook: <em><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\" title=\"\">Learn Raspberry Pi Pico with MicroPython<\/a><\/em>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"asyncio-micropython\"><strong>The <em>asyncio<\/em> MicroPython Module<\/strong><\/h3>\n\n\n\n<p>To create the asynchronous web server, we&#8217;ll take advantage of the <span class=\"rnthl rntliteral\">asyncio<\/span> MicroPython module. This module is already included in MicroPython firmware by default, so you don&#8217;t need to install any additional Modules.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Advantages of Asynchronous Programming<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">asyncio<\/span> MicroPython module allows you to run multiple tasks concurrently, creating the illusion of multitasking and avoiding blocking your code on long-running tasks.<\/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=\"555\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/synchronous-vs-asynchronous-programming.png?resize=750%2C555&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Synchronous vs Asynchronous programming\" class=\"wp-image-149491\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/synchronous-vs-asynchronous-programming.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/synchronous-vs-asynchronous-programming.png?resize=300%2C222&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>For example, your program can be waiting for the response of a server and still be able to do other tasks like checking if a button was pressed or blinking an LED at the same time. Asynchronous programming can be very useful in the case of setting the Raspberry Pi Pico as a web server because it allows it to handle multiple clients at the same time while still being able to run other tasks in the loop.<\/p>\n\n\n\n<p>The MicroPython <span class=\"rnthl rntliteral\">asyncio<\/span> module is a lightweight asynchronous I\/O framework inspired by Python&#8217;s <span class=\"rnthl rntliteral\">asyncio<\/span> module. You can check all the details about this MicroPython module on the following link: <a href=\"https:\/\/docs.micropython.org\/en\/latest\/library\/asyncio.html\" target=\"_blank\" rel=\"noopener\" title=\"\">documentation for asyncio<\/a> MicroPython module.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wiring the Circuit<\/h2>\n\n\n\n<p>To test this project, wire two LEDs to the Raspberry Pi Pico. One LED is connected to GPIO 19 and another one is connected to GPIO 20. You can use the diagram below as a reference.<\/p>\n\n\n\n<p><strong>Parts Required<\/strong><\/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 W<\/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 resistors<\/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<p>You can use any other GPIOs as long as you modify the code accordingly\u2014take a look at the <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\" title=\"\">Raspberry Pi Pico Pinout<\/a>. <\/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=\"969\" height=\"683\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-pico-two-LEDs-circuit-diagram.png?resize=969%2C683&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico W wiring two LEDs circuit diagram\" class=\"wp-image-149483\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-pico-two-LEDs-circuit-diagram.png?w=969&amp;quality=100&amp;strip=all&amp;ssl=1 969w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-pico-two-LEDs-circuit-diagram.png?resize=300%2C211&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-pico-two-LEDs-circuit-diagram.png?resize=768%2C541&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 969px) 100vw, 969px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"async-web-server-micropython-code\">Raspberry Pi Pico Asynchronous Web Server &#8211; MicroPython Code<\/h2>\n\n\n\n<p>Create a new file in Thonny IDE and copy the following code.<\/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-w-asynchronous-web-server-micropython\/\n\n# Import necessary modules\nimport network\nimport asyncio\nimport socket\nimport time\nimport random\nfrom machine import Pin\n\n# Wi-Fi credentials\nssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'\n\n# Create several LEDs\nled_blink = Pin(20, Pin.OUT)\nled_control = Pin(19, Pin.OUT)\n\n# Initialize variables\nstate = &quot;OFF&quot;\nrandom_value = 0\n\n# HTML template for the webpage\ndef webpage(random_value, state):\n    html = f&quot;&quot;&quot;\n        &lt;!DOCTYPE html&gt;\n        &lt;html&gt;\n        &lt;head&gt;\n            &lt;title&gt;Pico Web Server&lt;\/title&gt;\n            &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;\n        &lt;\/head&gt;\n        &lt;body&gt;\n            &lt;h1&gt;Raspberry Pi Pico Web Server&lt;\/h1&gt;\n            &lt;h2&gt;Led Control&lt;\/h2&gt;\n            &lt;form action=&quot;.\/lighton&quot;&gt;\n                &lt;input type=&quot;submit&quot; value=&quot;Light on&quot; \/&gt;\n            &lt;\/form&gt;\n            &lt;br&gt;\n            &lt;form action=&quot;.\/lightoff&quot;&gt;\n                &lt;input type=&quot;submit&quot; value=&quot;Light off&quot; \/&gt;\n            &lt;\/form&gt;\n            &lt;p&gt;LED state: {state}&lt;\/p&gt;\n            &lt;h2&gt;Fetch New Value&lt;\/h2&gt;\n            &lt;form action=&quot;.\/value&quot;&gt;\n                &lt;input type=&quot;submit&quot; value=&quot;Fetch value&quot; \/&gt;\n            &lt;\/form&gt;\n            &lt;p&gt;Fetched value: {random_value}&lt;\/p&gt;\n        &lt;\/body&gt;\n        &lt;\/html&gt;\n        &quot;&quot;&quot;\n    return str(html)\n\n# Init Wi-Fi Interface\ndef init_wifi(ssid, password):\n    wlan = network.WLAN(network.STA_IF)\n    wlan.active(True)\n    # Connect to your network\n    wlan.connect(ssid, password)\n    # Wait for Wi-Fi connection\n    connection_timeout = 10\n    while connection_timeout &gt; 0:\n        print(wlan.status())\n        if wlan.status() &gt;= 3:\n            break\n        connection_timeout -= 1\n        print('Waiting for Wi-Fi connection...')\n        time.sleep(1)\n    # Check if connection is successful\n    if wlan.status() != 3:\n        print('Failed to connect to Wi-Fi')\n        return False\n    else:\n        print('Connection successful!')\n        network_info = wlan.ifconfig()\n        print('IP address:', network_info[0])\n        return True\n\n# Asynchronous functio to handle client's requests\nasync def handle_client(reader, writer):\n    global state\n    \n    print(&quot;Client connected&quot;)\n    request_line = await reader.readline()\n    print('Request:', request_line)\n    \n    # Skip HTTP request headers\n    while await reader.readline() != b&quot;\\r\\n&quot;:\n        pass\n    \n    request = str(request_line, 'utf-8').split()[1]\n    print('Request:', request)\n    \n    # Process the request and update variables\n    if request == '\/lighton?':\n        print('LED on')\n        led_control.value(1)\n        state = 'ON'\n    elif request == '\/lightoff?':\n        print('LED off')\n        led_control.value(0)\n        state = 'OFF'\n    elif request == '\/value?':\n        global random_value\n        random_value = random.randint(0, 20)\n\n    # Generate HTML response\n    response = webpage(random_value, state)  \n\n    # Send the HTTP response and close the connection\n    writer.write('HTTP\/1.0 200 OK\\r\\nContent-type: text\/html\\r\\n\\r\\n')\n    writer.write(response)\n    await writer.drain()\n    await writer.wait_closed()\n    print('Client Disconnected')\n    \nasync def blink_led():\n    while True:\n        led_blink.toggle()  # Toggle LED state\n        await asyncio.sleep(0.5)  # Blink interval\n\nasync def main():    \n    if not init_wifi(ssid, password):\n        print('Exiting program.')\n        return\n    \n    # Start the server and run the event loop\n    print('Setting up server')\n    server = asyncio.start_server(handle_client, &quot;0.0.0.0&quot;, 80)\n    asyncio.create_task(server)\n    asyncio.create_task(blink_led())\n    \n    while True:\n        # Add other tasks that you might need to do in the loop\n        await asyncio.sleep(5)\n        print('This message will be printed every 5 seconds')\n        \n\n# Create an Event Loop\nloop = asyncio.get_event_loop()\n# Create a task to run the main function\nloop.create_task(main())\n\ntry:\n    # Run the event loop indefinitely\n    loop.run_forever()\nexcept Exception as e:\n    print('Error occurred: ', e)\nexcept KeyboardInterrupt:\n    print('Program Interrupted by the user')\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\/async_web_server.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>This code creates an asynchronous web server. Before running the code, make sure you insert your network credentials.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Wi-Fi credentials\nssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>This code is similar to the one in <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\" title=\"\">this previous project<\/a>. In this article, we&#8217;ll just take a look at the relevant parts of code for the asynchronous web server. So, if you&#8217;re still not familiar with a basic socket server, read the code explanation of <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\" title=\"\">this project first<\/a>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Importing the <em>asyncio<\/em> Module<\/h4>\n\n\n\n<p>First, we need to import the <span class=\"rnthl rntliteral\">asyncio<\/span> module to use its functionalities for asynchronous programming.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import asyncio<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Asynchronous Functions<\/h4>\n\n\n\n<p>The functions <span class=\"rnthl rntliteral\">handle_client()<\/span> and <span class=\"rnthl rntliteral\">blink_led()<\/span> are defined as asynchronous functions (defined by the keywords <span class=\"rnthl rntliteral\">async def<\/span>) allowing them to run concurrently and cooperatively with other coroutines.<\/p>\n\n\n\n<p>The main function <span class=\"rnthl rntliteral\">main()<\/span> is also defined as an asynchronous function to organize the startup of the server and other tasks.<\/p>\n\n\n\n<p>An event loop <span class=\"rnthl rntliteral\">asyncio.get_event_loop()<\/span> is created to manage and execute asynchronous tasks.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>loop = asyncio.get_event_loop()<\/code><\/pre>\n\n\n\n<p>The main function <span class=\"rnthl rntliteral\">main()<\/span> is registered as a task in the event loop using <span class=\"rnthl rntliteral\">loop.create_task(main())<\/span>, allowing it to be scheduled and executed asynchronously.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>loop.create_task(main())<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Asynchronous Server Setup<\/h4>\n\n\n\n<p>Instead of using <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\" title=\"\">traditional socket programming<\/a>, the <span class=\"rnthl rntliteral\">asyncio<\/span> function <span class=\"rnthl rntliteral\">asyncio.start_server()<\/span> is used to create an asynchronous TCP server.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>server = asyncio.start_server(handle_client, \"0.0.0.0\", 80)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">handle_client()<\/span> coroutine is passed as the callback function to handle incoming client connections.<\/p>\n\n\n\n<p>Basically, this previous line sets up a server that listens for incoming connections on a specified host and port. It returns an object that represents the server task (<span class=\"rnthl rntliteral\">server<\/span>).<\/p>\n\n\n\n<p>When the server accepts a new client connection, it calls the <span class=\"rnthl rntliteral\">handle_client<\/span> function (or any other coroutine specified as the client handler).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Client Connection<\/h4>\n\n\n\n<p>When a client connects to the server, <span class=\"rnthl rntliteral\">asyncio.start_server()<\/span> creates a pair of stream objects: a <span class=\"rnthl rntliteral\">StreamReader<\/span> for reading data from the client and a <span class=\"rnthl rntliteral\">StreamWriter<\/span> for writing data to the client. Learn more about <a href=\"https:\/\/docs.micropython.org\/en\/latest\/library\/asyncio.html#tcp-stream-connections\" target=\"_blank\" rel=\"noopener\" title=\"\">TCP stream connections with asyncio<\/a>.<\/p>\n\n\n\n<p>These stream objects (<span class=\"rnthl rntliteral\">reader<\/span> and <span class=\"rnthl rntliteral\">writer<\/span>) are passed as parameters to the coroutine specified as the client handler (<span class=\"rnthl rntliteral\">handle_client<\/span> in this case).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>async def handle_client(reader, writer):<\/code><\/pre>\n\n\n\n<p>Inside the <span class=\"rnthl rntliteral\">handle_client()<\/span> function, the <span class=\"rnthl rntliteral\">reader<\/span> and <span class=\"rnthl rntliteral\">writer<\/span> objects are used to asynchronously read data from the client and write data back to the client, respectively.<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">reader<\/span> object (<span class=\"rnthl rntliteral\">StreamReader<\/span>) provides methods for reading data from the client&#8217;s socket connection asynchronously (<span class=\"rnthl rntliteral\">await reader.readline()<\/span>).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>print(\"Client connected\")\nrequest_line = await reader.readline()\nprint('Request:', request_line)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">writer<\/span> object (<span class=\"rnthl rntliteral\">StreamWriter<\/span>) provides methods for writing data to the client&#8217;s socket connection asynchronously (<span class=\"rnthl rntliteral\">writer.write()<\/span>).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>writer.write('HTTP\/1.0 200 OK\\r\\nContent-type: text\/html\\r\\n\\r\\n')\nwriter.write(response)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">reader<\/span> and <span class=\"rnthl rntliteral\">writer<\/span> objects are provided by the <span class=\"rnthl rntliteral\">asyncio.start_server()<\/span> function when a client connects to the server. These objects allow the server to asynchronously communicate with the client by reading incoming data and writing outgoing data.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Running the Tasks Concurrently<\/h4>\n\n\n\n<p>The asyncio function <span class=\"rnthl rntliteral\">asyncio.create_task()<\/span> is used to create tasks for handling client connections and LED blinking concurrently. This allows the server to accept multiple client connections and blink the LED simultaneously without blocking.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>asyncio.create_task(server)\nasyncio.create_task(blink_led())<\/code><\/pre>\n\n\n\n<p>Additionally, we also have other asynchronous operations in the <span class=\"rnthl rntliteral\">main()<\/span> function using <span class=\"rnthl rntliteral\">await asyncio.sleep()<\/span>\u2014the non-blocking version of <span class=\"rnthl rntliteral\">time.sleep()<\/span>. In this case, we&#8217;re simply printing a message to the shell every 5 seconds, but you can add any other tasks you need. You can add more operations if needed.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>while True:\n    # Add other tasks that you might need to do in the loop\n    await asyncio.sleep(5)\n    print('This message will be printed every 5 seconds')<\/code><\/pre>\n\n\n\n<p>The event loop (<span class=\"rnthl rntliteral\">loop.run_forever()<\/span>) runs indefinitely, continuously processing tasks and handling client connections. This ensures that the server remains active and responsive to incoming requests.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>loop.run_forever()<\/code><\/pre>\n\n\n\n<p>In summary, we use asynchronous operations throughout the code, such as reading from clients <span class=\"rnthl rntliteral\">await reader.readline()<\/span>, sending responses <span class=\"rnthl rntliteral\">writer.write()<\/span>, and toggling an LED <span class=\"rnthl rntliteral\">await asyncio.sleep()<\/span>. <\/p>\n\n\n\n<p>These operations allow the server to perform other tasks while waiting for operations to complete, making it non-blocking and more efficient.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Testing the Code<\/h2>\n\n\n\n<p>Run the previous code on your Raspberry Pi Pico.<\/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=\"470\" height=\"114\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?resize=470%2C114&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Testing the MicroPython Code Raspberry Pi Pico Board\" class=\"wp-image-144594\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?w=470&amp;quality=100&amp;strip=all&amp;ssl=1 470w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?resize=300%2C73&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 470px) 100vw, 470px\" \/><\/figure><\/div>\n\n\n<p>After connecting to the internet, open a web browser on the same network and type the Pico IP address to access the web server.<\/p>\n\n\n\n<p>You can open multiple tabs on your web browser or multiple devices at the same time without any problem and still be able to control the LED on and off and request a new random value.<\/p>\n\n\n\n<div class=\"wp-block-jetpack-tiled-gallery aligncenter is-style-rectangular\"><div class=\"tiled-gallery__gallery\"><div class=\"tiled-gallery__row\"><div class=\"tiled-gallery__col\" style=\"flex-basis:24.88534%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Basic-Webserver-Smartphone.png?strip=info&#038;w=361&#038;ssl=1 361w\" alt=\"\" data-height=\"723\" data-id=\"144695\" data-link=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/raspberry-pi-pico-basic-webserver-smartphone\/#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Basic-Webserver-Smartphone.png\" data-width=\"361\" src=\"https:\/\/i2.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/Raspberry-Pi-Pico-Basic-Webserver-Smartphone.png?ssl=1\" data-amp-layout=\"responsive\"\/><\/figure><\/div><div class=\"tiled-gallery__col\" style=\"flex-basis:75.11466%\"><figure class=\"tiled-gallery__item\"><img decoding=\"async\" srcset=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/web-server-fetch-value.png?strip=info&#038;w=600&#038;ssl=1 600w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/web-server-fetch-value.png?strip=info&#038;w=741&#038;ssl=1 741w\" alt=\"Raspberry Pi Pico Basic Web Server\" data-height=\"490\" data-id=\"144649\" data-link=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/web-server-fetch-value\/#main\" data-url=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/web-server-fetch-value.png\" data-width=\"741\" src=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/web-server-fetch-value.png?ssl=1\" data-amp-layout=\"responsive\"\/><\/figure><\/div><\/div><\/div><\/div>\n\n\n\n<p>All of this can be handled while blinking an LED and printing messages to the shell at different rates.<\/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=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Asynchronous-programming.jpg?resize=750%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico W Asynchronous Programming\" class=\"wp-image-149487\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Asynchronous-programming.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Asynchronous-programming.jpg?resize=300%2C168&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"689\" height=\"753\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/rpi-pico-async-web-server-printing-loop-shell.png?resize=689%2C753&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Testing Raspberry Pi Pico W Asynchronous Web Server script upload run\" class=\"wp-image-149485\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/rpi-pico-async-web-server-printing-loop-shell.png?w=689&amp;quality=100&amp;strip=all&amp;ssl=1 689w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/rpi-pico-async-web-server-printing-loop-shell.png?resize=275%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 275w\" sizes=\"(max-width: 689px) 100vw, 689px\" \/><\/figure><\/div>\n\n\n<p>You should now understand that instead of blinking an LED and printing messages, you can run more complex asynchronous tasks and the Pico will still be able to handle the web server and serve multiple clients.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Uploading the Code to the Raspberry Pi Pico<\/h2>\n\n\n\n<p>If you want the Raspberry Pi Pico to run the webserver without being connected to your computer, you need to upload the code as&nbsp;<em>main.py<\/em>&nbsp;to the Raspberry Pi Pico filesystem. For that, after copying the code to a new file, go to&nbsp;<strong>File&nbsp;<\/strong>&gt;&nbsp;<strong>Save as<\/strong>&nbsp;and 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=\"Save Files to Raspberry Pi Pico Thonny IDE\" class=\"wp-image-130899\"\/><\/figure><\/div>\n\n\n<p>Name the file<strong> main.py<\/strong> and click OK to save the file on the Raspberry Pi Pico. Now, it will run the&nbsp;<em>main.py&nbsp;<\/em>file on boot without the need to be connected to the computer.<\/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<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, we&#8217;ve shown you how to build an asynchronous web server with the Raspberry Pi Pico using the asyncio MicroPython module. Using an asynchronous approach allows the Raspberry Pi Pico to handle multiple clients at the same time and still perform other tasks concurrently.<\/p>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. If you&#8217;re new to web servers with the Raspberry Pi Pico, we recommend starting with this <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-web-server-micropython\/\" title=\"\">more basic web server example<\/a> and then proceeding to the asynchronous approach.<\/p>\n\n\n\n<p>If you would like to learn more about the Raspberry Pi Pico, make sure you don&#8217;t miss our ebook:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\"><strong>Learn Raspberry Pi Pico\/Pico W with MicroPython (<em>eBook<\/em>)<\/strong><\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, you\u2019ll learn how to build a basic asynchronous local web server with the Raspberry Pi Pico W programmed with MicroPython using the asyncio module. Using an asynchronous &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico W: Asynchronous Web Server (MicroPython)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-asynchronous-web-server-micropython\/#more-149479\" aria-label=\"Read more about Raspberry Pi Pico W: Asynchronous Web Server (MicroPython)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":149494,"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-149479","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\/2024\/03\/Raspberry-Pi-Pico-Async-Web-Server-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\/149479","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=149479"}],"version-history":[{"count":18,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/149479\/revisions"}],"predecessor-version":[{"id":164704,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/149479\/revisions\/164704"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/149494"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=149479"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=149479"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=149479"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}