The Raspberry Pi is a popular single-board computer that is often used for Internet of Things (IoT) projects. One of the many things you can do with a Raspberry Pi is control hardware, such as an LED. In this article, we will show you how to use Python and the FastAPI library to create a simple endpoint that can be used to turn on an LED attached to a Raspberry Pi.
Setting up the hardware
To control an LED with a Raspberry Pi, you will need the following hardware:
- A Raspberry Pi
- An LED
- A breadboard
- Some jumper wires
To set up the hardware, follow these steps:
- Connect the positive leg of the LED to a GPIO pin on the Raspberry Pi using a jumper wire. We will use GPIO pin 18 in this example.
- Connect the negative leg of the LED to a ground pin on the Raspberry Pi using a jumper wire.
- Place the LED onto the breadboard.
Now that the hardware is set up, we can move on to writing the Python code.
Writing the Python code
To control the LED with a Python script, we will use the RPi.GPIO
library, which provides easy-to-use functions for controlling the GPIO pins on a Raspberry Pi. We will also use the FastAPI
library, which makes it easy to create APIs with Python.
First, we need to import the libraries and set up the GPIO pins for the LED:
import RPi.GPIO as GPIO
from fastapi import FastAPI
# Set up the GPIO pins for the LED
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
Next, we will create a FastAPI app and define the endpoint that will be used to turn on the LED:
# Create the FastAPI app and define the endpoint
app = FastAPI()
@app.post("/led/on")
def turn_on_led():
# Turn on the LED
GPIO.output(18, GPIO.HIGH)
return {"message": "LED turned on!"}
This endpoint can be accessed via a POST request and will turn on the LED when called.
To run the code, you will need to have the RPi.GPIO
and FastAPI
libraries installed on your Raspberry Pi. You can install them using pip
:
pip install RPi.GPIO
pip install fastapi
Once the libraries are installed, you can run the Python script and test the endpoint using a tool like curl
or Postman
. When you make a POST request to the endpoint, the LED attached to the Raspberry Pi should turn on.
Conclusion
In this article, we showed you how to use Python and the FastAPI library to create a simple endpoint that can be used to control an LED attached to a Raspberry Pi. This is just one example of the many things you can do with a Raspberry Pi and Python. With a little creativity and some basic knowledge of electronics, you can build all sorts of interesting projects with a Raspberry Pi.