Running a web server on the **Raspberry Pi Pico W** (which has Wi-Fi capability) is possible using **MicroPython** or **C/C++ (with the Pico SDK)**. Below, I'll guide you through setting up a simple web server using **MicroPython** (the easiest method).
---
### **Steps to Run a Web Server on Raspberry Pi Pico W**
#### **1. Set Up MicroPython on Pico W**
- Download the latest **MicroPython firmware** for Pico W from:
[https://micropython.org/download/rp2-pico-w/](https://micropython.org/download/rp2-pico-w/)
- Flash it onto the Pico W by holding the **BOOTSEL** button while plugging it into USB, then drag the `.uf2` file to the `RPI-RP2` drive.
#### **2. Connect to Wi-Fi**
Use the following script to connect your Pico W to Wi-Fi:
```python
import network
import time
# Configure Wi-Fi
ssid = "YOUR_WIFI_SSID"
password = "YOUR_WIFI_PASSWORD"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connection
max_wait = 10
while max_wait > 0:
if wlan.isconnected():
break
max_wait -= 1
time.sleep(1)
if not wlan.isconnected():
raise RuntimeError("Network connection failed")
else:
print("Connected to Wi-Fi")
print("IP Address:", wlan.ifconfig()[0])
```
#### **3. Create a Simple Web Server**
Here’s a basic HTTP server that responds with "Hello, Pico W!":
```python
import socket
# HTML content to serve
html = """<!DOCTYPE html>
<html>
<head>
<title>Pico W Web Server</title>
</head>
<body>
<h1>Hello, Pico W!</h1>
</body>
</html>
"""
# Set up socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print("Listening on", addr)
# Serve requests
while True:
try:
conn, addr = s.accept()
print("Client connected from", addr)
request = conn.recv(1024)
response = html
conn.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n")
conn.send(response)
conn.close()
except OSError as e:
print("Connection closed")
```
#### **4. Run the Web Server**
- Save the script as `main.py` on your Pico W so it runs on boot.
- Reset the Pico W (or unplug/replug it).
- Open a browser and enter the **IP address** printed in the REPL.
You should see the **"Hello, Pico W!"** page.
---
### **Enhancements (Optional)**
- **Handle multiple requests** (avoid crashing after one request).
- **Add routes** (e.g., `/`, `/led`).
- **Control GPIO pins** (toggle an LED via HTTP).
- **Use `microdot` (a lightweight MicroPython web framework)**:
```python
from microdot import Microdot
app = Microdot()
@app.route('/')
def index(request):
return "Hello from MicroDot!"
app.run(port=80)
```
(Install `microdot` via `mip` or manually.)
---
### **Troubleshooting**
- **Can't connect to Wi-Fi?** Check credentials and signal strength.
- **Port 80 not working?** Ensure no other device is using it.
- **Script crashes?** Wrap in `try-except` blocks.
---
This is a basic example, but you can expand it to control sensors, LEDs, or serve dynamic content. Let me know if you need help with more advanced features!