RajivCodeLabRajiv Sharma
Published © GPL3+

How to Build a REST API on Raspberry Pi Pico W & Control LED

On this step-by-step tutorial, guides you through How to build a REST API on Raspberry Pi Pico W and control the LEDs from Postman Client.

IntermediateProtip2 hours3,069
How to Build a REST API on Raspberry Pi Pico W & Control LED

Things used in this project

Hardware components

Raspberry Pi Pico W
Raspberry Pi Pico W
×1
Micro-USB to USB Cable (Generic)
Micro-USB to USB Cable (Generic)
×1
Breadboard (generic)
Breadboard (generic)
×1
Male/Male Jumper Wires
×3
Resistor 330 ohm
Resistor 330 ohm
×2
Thonny IDE
×1
Postman Client
×1

Story

Read more

Schematics

LED Connection to Raspberry Pi Pico

Code

LED_CONTROL_REST_API.py

Python
from phew import server, connect_to_wifi
import machine
import json

ip = connect_to_wifi("YOUR_SSID", "YOUR_PASSWORD")

led_green = machine.Pin(0, machine.Pin.OUT)
led_red = machine.Pin(1, machine.Pin.OUT)

print("connected to IP ", ip)

@server.route("/api/temperature", methods=["GET"])
def get_temperature(request):
    adc = machine.ADC(4)  # Use ADC pin GP4
    conversion_factor = 3.3 / (65535)  # ADC conversion factor
    sensor_value = adc.read_u16() * conversion_factor
    temperature = 27 - (sensor_value - 0.706) / 0.001721  # Convert sensor value to temperature (formula may vary)
    
    return json.dumps({"temperature" : temperature}), 200, {"Content-Type": "application/json"}

@server.route("/api/control-led", methods=["POST"])
def ledCommand(request):
    led_red.value(request.data["ledRed"])
    led_green.value(request.data["ledGreen"])
    return json.dumps({"message" : "Command sent successfully!"}), 200, {"Content-Type": "application/json"}

@server.catchall()
def catchall(request):
    return json.dumps({"message" : "URL not found!"}), 404, {"Content-Type": "application/json"}

server.run()

Credits

RajivCodeLab
7 projects • 4 followers
Creates YT videos on DIY IoT Projects: Raspberry Pi Pico, Raspberry Pi Zero, Arduino, ESP32,
Contact
Rajiv Sharma
18 projects • 71 followers
Having more than 10 years of experience in IoT and software technology. Founded IoTBoys to share knowledge with IoT enthusiasts.
Contact

Comments

Please log in or sign up to comment.