Raspberry Pi Led Blink

11 Dec 2020 - Syed Muhammad Shahrukh Hussain

Write a python program in raspberry pi to blink an LED using GPIO PINS.

Brief

This program will blink LED on a breadboard connected to GPIO pins using jumper wires. Raspberry pi provides GPIO python module to interact with the PINS.

imports python modules

#!/usr/bin/python3
import RPi.GPIO as PIN
from time import sleep
import signal
import sys

defines / constants

Initialize GPIO pin defined by PIN_NO.

Set pin mode to PIN.BOARD, this will use board pin numbers printed on the board.

TM_500_MS = 0.5
PIN_NO = 16 

signal handler

Assign signal handler functions to OS signal.

Add handler for OS signals Ctrl + C

def signal_handler(sig, frame):
    """
    Handle SIGINT, SIGQUIT and SIGTERM
    """
    # reset the pin on exit
    PIN.output(PIN_NO, PIN.LOW)
    PIN.cleanup()
    sys.exit(0)

init function

def init():
    """
    Initialize board pins and signal handling.
    """
    PIN.setwarnings(False)
    PIN.setmode(PIN.BOARD)
    PIN.setup(PIN_NO, PIN.OUT)
    # setup signals handler
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGQUIT, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

main function

def main():
    init()
    print("Running blink.")
    while True:
        PIN.output(PIN_NO, PIN.HIGH)
        # sleep for 500ms.
        sleep(TM_500_MS)
        # turn off the led
        PIN.output(PIN_NO, PIN.LOW)
        # sleep for 500 ms.
        sleep(TM_500_MS)


if __name__ == '__main__':
    main()