Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
đ Ready to explore and create with us? Click [here] and join today!
1.1 Blinking LEDď
Introduction
Welcome to your first project! In this tutorial, we will learn how to make an LED blink using Python programming and the GPIO pins. This project is an excellent introduction to hardware and software integration, demonstrating how simple code can interact with real-world components.
Before we start, letâs briefly explain the basics:
What is an LED?
An LED (Light Emitting Diode) is a small electronic component that lights up when an electrical current flows through it. LEDs are widely used in electronics because they are efficient and long-lasting.
What is a GPIO Pin?
GPIO stands for General Purpose Input/Output. These pins allow the Raspberry Pi to communicate with external devices, such as LEDs, sensors, or buttons. Each pin can be programmed to send signals (output) or read signals (input).
In this tutorial, weâll connect an LED to a GPIO pin and write a Python program to make it blink. Letâs get started!
What Youâll Need
Hereâs the list of components and their purposes:
COMPONENT |
PURCHASE LINK |
|---|---|
- |
|
Raspberry Pi |
- |
Circuit Diagram
The resistor limits the current flowing through the LED, preventing it from burning out. Without a resistor, the LED may draw too much current, which can damage both the LED and the Raspberry Pi.
Wiring Diagram
Follow the wiring diagram below to connect your components:
Run the Code
Letâs write the Python code to control the LED. Youâll create a script that turns the LED on and off at regular intervals.
Navigate to the Code Directory:
Open your terminal and type:
cd ~/ai-lab-kit/python
Run the Program:
Use the following command to execute the script:
sudo python3 1.1_LED.py
You should see the LED blinking on and off at regular intervals.
Edit the Code (Optional):
To modify the program, open the code file in a text editor:
nano 1.1_LED.py
Make your changes, then press
Ctrl+Xto exit. Save your modifications by typingYwhen prompted. Run the script again to see your changes.
Code
Hereâs the complete Python script for this project:
#!/usr/bin/env python3
from fusion_hat.pin import Pin, Mode
from time import sleep
# Initialize an LED connected to GPIO pin 17 as an output pin.
led = Pin(17,mode=Mode.OUT)
try:
# Start an infinite loop to toggle the LED state.
while True:
# Turn on the LED and print a message to the console.
led.high()
print('...LED ON')
# Wait for 0.5 seconds with the LED on.
sleep(0.5)
# Turn off the LED and print a message to the console.
led.low()
print('LED OFF...')
# Wait for 0.5 seconds with the LED off.
sleep(1)
except KeyboardInterrupt:
# Gracefully handle a keyboard interrupt (Ctrl+C) by breaking the loop.
pass
This Python script controls an LED connected to GPIO pin 17 of a Raspberry Pi. When executed, the LED alternates between turning on and off in half-second intervals. Simultaneously, the console prints âLED is ONâ and âLED is OFFâ to indicate the LEDâs current state. The program runs indefinitely until interrupted by a user pressing Ctrl+C.
Understanding the Code
Imports:
The
fusion_hatlibrary simplifies controlling GPIO devices. ThePinclass allows you to control an LED with basic methods likeon()andoff(). Thesleepfunction introduces delays between commands.Note
For the usage of fusion-hat, please refer to the fusion-hat documentation .
Initialization:
The line
led = Pin(17,mode=Mode.OUT)tells the Raspberry Pi that an LED is connected to GPIO pin 17.Main Loop:
Inside the
while Trueloop: The LED turns on (led.on()) and off (led.off()) with a 0.5-second pause (sleep(0.5)) in between.Graceful Exit:
The
try...exceptblock ensures the program stops cleanly when interrupted (e.g., by pressingCtrl+C).
Troubleshooting
LED Does Not Light Up
Cause: Incorrect GPIO pin or faulty wiring.
Solution: Double-check the LEDâs connection to GPIO pin 17 and ensure the resistor is correctly placed to prevent damage to the LED.
KeyboardInterrupt Not Working
Cause: The program does not exit gracefully.
Solution: Ensure the script is running in a terminal where
Ctrl+Cis captured, not as a background process.
Incorrect GPIO Setup
Cause:
fusion_hatlibrary is not installed.Solution: See Install fusion-hat module.
LED Flickers or Behaves Erratically
Cause: Unstable power supply or poor connections.
Solution: Ensure a stable power source and secure wiring.
Extendable Ideas
Variable Blink Speed: Add user input to control the LEDâs blinking speed dynamically:
interval = float(input("Enter blink interval in seconds: ")) while True: led.on() sleep(interval) led.off() sleep(interval)
Multi-LED Control: Connect multiple LEDs to different GPIO pins and control them in patterns (e.g., sequential lighting or simultaneous blinking).
Conclusion
Congratulations! Youâve completed your first Raspberry Pi project. By controlling an LED, youâve learned how to use GPIO pins and write Python scripts to interact with hardware. This foundational knowledge will serve as a stepping stone for more complex projects. Keep experimenting and exploring!