📅  最后修改于: 2023-12-03 15:04:47.781000             🧑  作者: Mango
Raspberry Pi is a single-board computer that has gained immense popularity among developers for its versatility, affordability, and ease of use. The Python programming language is also a favorite among developers for its simple syntax and readability.
One of the most common uses of Raspberry Pi is as a platform for controlling LEDs. This tutorial will cover the basics of controlling LEDs with Raspberry Pi using Python.
To follow along with this tutorial, you will need the following:
Raspberry Pi comes with Python pre-installed, but we will need to install the RPi.GPIO library to control the GPIO pins. Open a terminal window and run the following command:
sudo apt-get install python-rpi.gpio
Connect the LED to the Raspberry Pi according to the following diagram:
__
| |
GPIO 17 |__|------[220 ohm resistor]------|>|-- GND
Open a new Python file and import the necessary libraries:
import RPi.GPIO as GPIO
import time
Set up the GPIO pins and turn the LED on and off in a loop:
LED_PIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
while True:
GPIO.output(LED_PIN, GPIO.HIGH) # turn the LED on
time.sleep(1) # wait for 1 second
GPIO.output(LED_PIN, GPIO.LOW) # turn the LED off
time.sleep(1) # wait for 1 second
Run the code by executing the following command in the terminal:
python filename.py
The LED should start blinking on and off every second.
In this tutorial, we covered the basics of controlling LEDs with Raspberry Pi using the Python programming language. We learned how to install the RPi.GPIO library, wire the LED to Raspberry Pi, and write a simple Python program to control the LED.
By understanding these concepts, you can apply them to more complex projects and further explore the possibilities of Raspberry Pi and Python.