Raspberry Pi 4 Led Blink Codes

  There are different ways to write code to blink a LED connected to Raspberry Pi 4(Model B)

Below is circuit diagram that blink a LED connected to Raspberry Pi GPIO pin 4(GPIO4).

led blink

The Raspberry Pi led blinking code is below.

import RPi.GPIO as GPIO
import time

# Set up the GPIO pin
LED_PIN = 4 # GPIO4
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)


try:
    while True:
        GPIO.output(LED_PIN, GPIO.HIGH) # Turn on LED
        time.sleep(1)                   # Wait 1 second
        GPIO.output(LED_PIN, GPIO.LOW)  # Turn off LED
        time.sleep(1)                   # Wait 1 second
except KeyboardInterrupt:
    GPIO.cleanup() # Clean up on exit

The code is a Python script used to control a physical LED through a Raspberry Pi's GPIO pin 4. It is structured to handle setup, operation, and a safe shutdown.

1. Library Imports

  • import RPi.GPIO as GPIO: This line imports the Raspberry Pi GPIO library, which is necessary to control the pins. The as GPIO part creates a shorter nickname to use later in the script.

  • import time: This imports the time library, which allows the program to pause or wait to use the sleep function.

2. Hardware Configuration

  • LED_PIN = 4: This creates a variable that identifies GPIO4 as the pin used for the LED.

  • GPIO.setmode(GPIO.BCM): This command tells the Raspberry Pi to use the Broadcom (BCM) pin numbering system rather than the physical pin numbers.

  • GPIO.setup(LED_PIN, GPIO.OUT): This configures GPIO4 to act as an Output, allowing the Pi to send voltage to the LED.

3. The Execution Loop

  • try:: This begins a block of code that the system will attempt to run continuously.

  • while True:: This starts an infinite loop, meaning the steps inside will repeat forever until the program is manually stopped.

  • GPIO.output(LED_PIN, GPIO.HIGH): This turns the LED ON by sending 3.3V to the pin.

  • time.sleep(1): This pauses the execution for 1 second.

  • GPIO.output(LED_PIN, GPIO.LOW): This turns the LED OFF by setting the pin voltage to 0V.

4. Safe Exit

  • except KeyboardInterrupt:: This tells the program what to do if you stop it manually, typically by pressing Ctrl+C on your keyboard

  • GPIO.cleanup(): This is a vital step that resets the pins to a safe state, ensuring the LED doesn't accidentally stay on after the program closes.

Another way of writing LED blinking code for Raspberry Pi:

import RPi.GPIO as GPIO         # Import Raspberry Pi GPIO library
from time import sleep          # Import the sleep function 

pinLED = 4                      # LED GPIO Pin

GPIO.setmode(GPIO.BCM)          # Use GPIO pin number
GPIO.setwarnings(False)         # Ignore warnings in our case
GPIO.setup(pinLED, GPIO.OUT)    # GPIO pin as output pin

while True:                          # Endless Loop
    GPIO.output(pinLED, GPIO.HIGH)   # Turn on
    print("LED on")                    # Prints state to console
    sleep(1)                         # Pause 1 second
    GPIO.output(pinLED, GPIO.LOW)    # Turn off
    print("LED off")                   # Prints state to console
    sleep(1)                         # Pause 1 second

The difference between the two scripts comes down to coding style, syntax, and safety. While both achieve the same result- blinking an LED—they handle the "behind-the-scenes" details differently.

1. Import Method (Syntax)

  • Previous Code: Used import time. To use the sleep function, we had to type time.sleep(1).

  • Current Code: Uses from time import sleep. This allows you to simply type sleep(1). It saves a little bit of typing and is a common way to keep code clean.

2. Warning Management

  • Previous Code: Did not address warnings. If you ran the code twice without cleaning up, the Raspberry Pi might show a warning that the "Channel is already in use."

  • Current Code: Includes GPIO.setwarnings(False). This explicitly tells the Pi to ignore those "already in use" warnings, which makes the console output look cleaner during repetitive testing.

3. Feedback (Console Output)

  • Previous Code: Was silent. The only way to know it was working was to look at the LED in the Proteus schematic.

  • Current Code: Includes print("LED on") and print("LED off"). This gives you immediate feedback in the Proteus VSM terminal or your computer console, which is very helpful for troubleshooting if the LED doesn't light up.

4. Safety and Cleanup (The Biggest Difference)

  • Previous Code: Used a try...except block with GPIO.cleanup(). This is "Safe Code." If you stop the simulation, the pins are reset to a neutral state.

  • Current Code: Does not include a cleanup function. If you stop the simulation while the LED is ON, the pin technically remains in an "Output HIGH" state. In real hardware, this could lead to accidental short circuits if you start moving wires around afterward.


Post a Comment

Previous Post Next Post