Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

2.2 Micro Switch

Introduction

In this project, we will explore how to use a Micro Switch to control two LEDs. A Micro Switch is a highly sensitive component that requires minimal compression to activate. It is often used in safety systems to prevent machinery or doors from operating under unsafe conditions.


What You’ll Need

To complete this project, you will need the following components:

COMPONENT

PURCHASE LINK

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Micro Switch

-

Capacitor

BUY

Fusion HAT+

-

Raspberry Pi

-


Circuit Diagram

The Micro Switch is connected to GPIO17, and two LEDs are connected to GPIO22 and GPIO27. When the Micro Switch is pressed, the red LED lights up; when released, the yellow LED turns on.

../_images/2.1.2_sch.png

Wiring Diagram

Follow these steps to build the circuit:

  1. Connect one terminal of the Micro Switch to GPIO17 and the other to the ground (GND).

  2. Connect the anodes of the two LEDs to GPIO22 (yellow) and GPIO27 (red) through current-limiting resistors.

  3. Connect the cathodes of both LEDs to GND.

../_images/2.1.2_bb.png

Running the Example

All example code used in this tutorial is available in the ai-lab-kit directory. Follow these steps to run the example:

cd ~/ai-lab-kit/python/
sudo python3 2.2_MicroSwitch.py

This Python script controls two LEDs based on the state of a micro switch connected to a Raspberry Pi. When executed:

  1. Micro Switch Pressed:

    • LED1 (connected to GPIO pin 22) turns on.

    • LED2 (connected to GPIO pin 27) turns off.

  2. Micro Switch Released:

    • LED1 turns off.

    • LED2 turns on.

  3. The program continuously checks the micro switch’s state every 0.5 seconds and adjusts the LEDs accordingly.

  4. The script runs indefinitely until interrupted by pressing Ctrl+C.


Code

The following Python code toggles between two LEDs based on the state of the Micro Switch:

#!/usr/bin/env python3
from fusion_hat.pin import Pin, Mode, Pull
from time import sleep  # Import sleep function for delays

# Initialize micro switch on GPIO pin 17
micro_switch = Pin(17, mode=Mode.IN, pull=Pull.DOWN)
# Initialize LED1 connected to GPIO pin 22
led1 = Pin(22,mode=Mode.OUT)
# Initialize LED2 connected to GPIO pin 27
led2 = Pin(27,mode=Mode.OUT)

try:
   # Continuously check the state of the micro switch and control LEDs accordingly
   while True:
      if micro_switch.value() == 1:  # If the micro switch is pressed
            led1.high()       # Turn on LED1
            led2.low()      # Turn off LED2
      else:  # If the micro switch is not pressed
            led1.low()      # Turn off LED1
            led2.high()       # Turn on LED2

      sleep(0.5)  # Pause for 0.5 seconds before checking the switch again

except KeyboardInterrupt:
   # Handle KeyboardInterrupt (Ctrl+C) to exit the loop gracefully
   pass

Understanding the Code

  1. Library Import

    The fusion_hat library provides simple GPIO control, and the time library enables delays.

    from fusion_hat.pin import Pin, Mode, Pull
    from time import sleep  # Import sleep function for delays
    
  2. Component Initialization

    The Micro Switch is connected to GPIO17 with pull-up disabled, while the LEDs are connected to GPIO22 and GPIO27.

    # Initialize micro switch on GPIO pin 17
    micro_switch = Pin(17, mode=Mode.IN, pull=Pull.DOWN)
    # Initialize LED1 connected to GPIO pin 22
    led1 = Pin(22,mode=Mode.OUT)
    # Initialize LED2 connected to GPIO pin 27
    led2 = Pin(27,mode=Mode.OUT)
    
  3. Switch State Handling

    The program checks the state of the Micro Switch in a loop. When pressed, LED1 turns on and LED2 off. When released, LED1 turns off and LED2 on.

    while True:
       if micro_switch.value() == 1:
          led1.on()
          led2.off()
       else:
          led1.off()
          led2.on()
       sleep(0.5)
    
  4. Interrupt Handling

    The try-except block ensures the script exits cleanly when interrupted using Ctrl+C.

    except KeyboardInterrupt:
       pass
    

Troubleshooting

  1. LEDs Do Not Respond

    • Cause: Incorrect GPIO wiring or pin configuration.

    • Solution: Ensure LED1 is connected to GPIO pin 22, LED2 to GPIO pin 27, and both LEDs have appropriate resistors. Verify the micro switch connection to GPIO pin 17.

  2. Micro Switch Not Detected

    • Cause: The micro switch might not be configured properly or needs a pull-up/pull-down resistor.

    • Solution: Confirm that pull = Pin.PULL_UP matches your switch configuration. If the switch requires a pull-up, enable it in the initialization.

  3. LEDs Flicker or Behave Erratically

    • Cause: Button debounce issues.

    • Solution: Add software debounce by introducing a short delay after detecting a press:

    if micro_switch.value() == 1:
       sleep(0.05)  # Debounce delay
    

Extendable Ideas

  1. Adjustable Delay

    Allow the user to change the delay dynamically to fine-tune LED responsiveness:

    delay = float(input("Enter delay in seconds: "))
    while True:
       sleep(delay)
    
  2. Audio Feedback

    Add a buzzer to provide an audible signal when the switch is pressed or released:

    from fusion_hat import Buzzer
    buzzer = Buzzer(Pin(22))
    if micro_switch.value() == 1:
       buzzer.on()
    else:
       buzzer.off()
    

Conclusion

This project demonstrates how to use a Micro Switch to control LEDs with the Fusion HAT+. Micro Switches are versatile components widely used in safety systems, user interfaces, and industrial controls. Experimenting with them can open up opportunities for creating more advanced projects.