Python Program 1 : Interfacing LED/Buzzer with Raspberry Pi

OBJECTIVE:

To interface an LED or Buzzer with the Raspberry Pi and write a program to control it using delays.


RESOURCES REQUIRED:


THEORY:

  • LED Basics:

    • An LED has two legs: Anode (+) and Cathode (-).

    • The longer leg is the Anode (positive), and the shorter leg is the Cathode (negative).

  • Current Limiting Resistor:

    • A 330Ω resistor is connected in series with the LED.

    • This resistor limits the current flowing through the LED to prevent it from burning out.

    • Without this resistor, the LED might draw too much current and get damaged.

  • GPIO Pins on Raspberry Pi:

    • The Raspberry Pi comes with General Purpose Input/Output (GPIO) pins.

    • These pins can be programmed to act as either input or output.

    • We can connect components like LEDs or buzzers to these pins to control them through Python programs.

  • Circuit Design:

    • The Anode of the LED is connected to GPIO pin (e.g., GPIO 18).

    • The Cathode is connected to the ground through a 330Ω resistor.

    • The GPIO pin is programmed to send HIGH or LOW signals to turn the LED ON or OFF.


Python Code: Controlling LED with Raspberry Pi

import RPi.GPIO as GPIO

import time

pin = 18 # GPIO pin to which LED is connected
# Set the pin numbering mode to BCM
GPIO.setmode(GPIO.BCM)
# Set GPIO pin 18 as output
GPIO.setup(pin, GPIO.OUT)
try:
while True:
GPIO.output(pin, True) # Turn ON LED
time.sleep(2) # Wait for 2 seconds
GPIO.output(pin, False) # Turn OFF LED
time.sleep(2) # Wait for 2 seconds
except KeyboardInterrupt:
GPIO.cleanup() # Reset GPIO settings
exit()


Explanation of the Program:

  1. Import Libraries:

    • RPi.GPIO is used to control GPIO pins.

    • time is used to create time delays.

  2. Pin Setup:

    • pin = 18 sets GPIO pin 18 for LED connection.

    • GPIO.setmode(GPIO.BCM) configures pin numbering mode as BCM (Broadcom chip-specific).

    • GPIO.setup(pin, GPIO.OUT) sets pin 18 as an output pin.

  3. Main Loop:

    • The while True: loop runs indefinitely.

    • GPIO.output(pin, True) turns the LED ON.

    • time.sleep(2) creates a 2-second delay.

    • GPIO.output(pin, False) turns the LED OFF.

    • Another 2-second delay is added before repeating.

  4. Exit Handling:

    • The program runs until you press Ctrl + C.

    • On exit, GPIO.cleanup() resets the GPIO pins to a safe state.


👉 If you found this helpful, don’t forget to like, follow, comment, and share! 💬🔁
Let’s keep learning and growing together — team up with me, let’s complete this assignment together! 💻✨

📘 Assignment: Drop your answer in the comments below!
Task: Write a Python program for a Binary Counter using Raspberry Pi.

🕒 Check back in the comments tomorrow to see if your solution matches the correct one!



Comments

Popular posts from this blog

Fundamental of python : 1.Python Numbers