How to use Python to control the GPIO pins on your Raspberry Pi?

 

LED Blinker using GPIO and Python

This simple project teaches you how to use Python to control the GPIO pins on your Raspberry Pi—blinking an LED on and off.




 What You Need:

  • Raspberry Pi (any model)

  • 1x LED

  • 1x 330Ω resistor

  • Breadboard and jumper wires

  • Python 3 (pre-installed)

  • GPIO library (RPi.GPIO)


 Wiring the Circuit:

  1. Connect the long leg of the LED (anode) to GPIO pin 18 (physical pin 12).

  2. Connect a 330Ω resistor from the LED's short leg (cathode) to GND (physical pin 6).

  3. Use a breadboard for easy wiring.


 Python Code:

Open the terminal and create the script:

bash

nano led_blink.py

Paste this code:

python

import RPi.GPIO as GPIO import time LED_PIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) try: while True: GPIO.output(LED_PIN, GPIO.HIGH) print("LED ON") time.sleep(1) GPIO.output(LED_PIN, GPIO.LOW) print("LED OFF") time.sleep(1) except KeyboardInterrupt: print("Program stopped") GPIO.cleanup()

Save and exit (Ctrl+X, then Y, then Enter).


 Run the Script:

bash

python3 led_blink.py

You should see the LED blink every second.


 What You Learn:

  • GPIO control in Python

  • Basic electronics with LEDs

  • Writing and executing Python scripts

评论

此博客中的热门博文

Detailed Explanation of STM32 HAL Library Clock System

How To Connect Stm32 To PC?

How to add a GPS sensor to ESP32 for Wokwi?