Section outline

  • GPIO Control with Python – Interfacing Hardware

    One of the most powerful features of the Raspberry Pi is its GPIO (General Purpose Input/Output) pins, which allow it to interface with the physical world. This section explores how to control LEDs, buttons, sensors, and other components using Python scripts and the Pi’s GPIO headers.

    • Understanding GPIO:

      • The Pi has a 40-pin GPIO header; not all pins are programmable.
      • Some pins are for power (3.3V, 5V), ground, and others are used for I2C, SPI, and UART communication.
      • GPIO pins are used to read inputs (like button presses) or send outputs (like turning on LEDs or motors).

      GPIO Pin Modes:

      • BCM: Uses GPIO numbering
      • BOARD: Uses physical pin positions on the board
    • Setting Up the GPIO Library:

      import RPi.GPIO as GPIO
      import time
      
      GPIO.setmode(GPIO.BCM)  # or GPIO.BOARD
      GPIO.setwarnings(False)

      Controlling an LED:

      • Connect the LED’s long leg to a GPIO pin (e.g., GPIO 17) via a resistor, and the short leg to ground.
      • Use the following code to turn the LED on and off:
      LED_PIN = 17
      GPIO.setup(LED_PIN, GPIO.OUT)
      
      GPIO.output(LED_PIN, GPIO.HIGH)  # LED ON
      time.sleep(2)
      GPIO.output(LED_PIN, GPIO.LOW)   # LED OFF
      GPIO.cleanup()

      Reading a Button Input:

      • Connect one side of a push button to a GPIO pin and the other to ground.
      • Use a pull-up or pull-down resistor in code:
      BUTTON_PIN = 18
      GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
      
      while True:
          if GPIO.input(BUTTON_PIN) == GPIO.LOW:
              print("Button Pressed")
              break
    • Common GPIO Projects:

      • LED blinking patterns
      • Button-controlled lights or motors
      • Reading temperature or distance sensors
      • Building a simple burglar alarm using motion sensors

      Best Practices:

      • Always add resistors to protect components and pins.
      • Use GPIO.cleanup() to reset pin states when exiting scripts.
      • Double-check the GPIO pin layout to avoid wrong connections.

      Activity: Try wiring up a basic LED and button circuit. Write a Python script where pressing the button toggles the LED. You can expand this into a more interactive circuit later for projects like games or alert systems.

      GPIO control gives your Raspberry Pi real-world interaction capabilities, making it a true bridge between computing and electronics. It is the cornerstone of building robots, IoT devices, and interactive hardware systems using Python.