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.4 Tilt Switch

Introduction

In this project, we will explore the tilt switch module, a ball tilt-switch containing a small metal ball inside. This switch is designed to detect slight inclinations and can be utilized in various applications like motion detection, angle measurement, and balance monitoring.


What You’ll Need

To complete this project, gather the following components:

COMPONENT INTRODUCTION

PURCHASE LINK

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Tilt Switch

-

Fusion HAT+

-

Raspberry Pi

-


Circuit Diagram

Refer to the following diagrams for connecting the tilt switch:

../_images/2.1.5_sch.png

Wiring Diagram

Follow these steps to set up the circuit:

  1. Connect the tilt switch to GPIO pin 17 on the Raspberry Pi.

  2. Connect the green LED to GPIO pin 27 with a resistor.

  3. Connect the red LED to GPIO pin 22 with a resistor.

  4. Complete the connections by wiring the cathodes of both LEDs to GND.

../_images/2.1.5_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.4_Tilt.py

This Python script uses a tilt sensor to control two LEDs and display status messages on the console. When executed:

  1. If the tilt sensor (connected to GPIO pin 17) detects a tilt:

    • Prints a message to the console.

    • Turns on the red LED (connected to GPIO pin 22).

    • Turns off the green LED (connected to GPIO pin 27).

  2. If the tilt sensor remains upright (in its normal vertical position):

    • Turns off the red LED.

    • Turns on the green LED.

  3. The program continuously monitors the tilt sensor’s state and adjusts the LEDs accordingly.

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


Code

Below is the Python script to control the tilt switch and LEDs:

#!/usr/bin/env python3
from fusion_hat.pin import Pin, Mode, Pull
from signal import pause  # Import pause function from signal module

TiltPin = Pin(17, mode=Mode.IN, pull=Pull.DOWN)  # Tilt sensor connected to GPIO pin 17
green_led = Pin(27,mode=Mode.OUT)  # Green LED connected to GPIO pin 27
red_led = Pin(22,mode=Mode.OUT)   # Red LED connected to GPIO pin 22

def detect():
   """
   Detect the tilt sensor state and control the LEDs.
   Turns on the red LED and turns off the green LED when tilted.
   Turns off the red LED and turns on the green LED when not tilted.
   """
   if TiltPin.value() == 0:  # Check if the sensor is tilted
      print('    *************')
      print('    *   Tilt!   *')
      print('    *************')
      red_led.high()   # Turn on red LED
      green_led.low()  # Turn off green LED
   else:  # If the sensor is not tilted
      red_led.low()  # Turn off red LED
      green_led.high()  # Turn on green LED

try:
   # Set up a callback to detect changes in the tilt sensor state
   TiltPin.when_activated = detect
   TiltPin.when_deactivated = detect
   pause()

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

Understanding the Code

  1. Imports

    The script imports necessary classes for LED and Button control and initializes them with appropriate GPIO pins.

    from fusion_hat.pin import Pin, Mode, Pull
    from signal import pause  # Import pause function from signal module
    
  2. Initialization

    Configure the tilt switch and LEDs connected to GPIO pins 17, 27, and 22.

    TiltPin = Pin(17, mode=Mode.IN, pull=Pull.DOWN)  # Tilt sensor connected to GPIO pin 17
    green_led = Pin(27,mode=Mode.OUT)  # Green LED connected to GPIO pin 27
    red_led = Pin(22,mode=Mode.OUT)   # Red LED connected to GPIO pin 22
    
  3. Detect Function

    The detect function checks the state of the tilt switch and updates the LEDs accordingly. If the switch is tilted, the red LED lights up and the green LED turns off.

    def detect():
       if TiltPin.value() == 0:  # Check if the sensor is tilted
          print('    *************')
          print('    *   Tilt!   *')
          print('    *************')
          red_led.high()   # Turn on red LED
          green_led.low()  # Turn off green LED
       else:  # If the sensor is not tilted
          red_led.low()  # Turn off red LED
          green_led.high()  # Turn on green LED
    
  4. Main Loop

    Assign the detect function to handle when_pressed and when_released events of the tilt sensor. The loop continues until interrupted.

    try:
       # Set up a callback to detect changes in the tilt sensor state
       TiltPin.when_activated = detect
       TiltPin.when_deactivated = detect
       pause()
    
    except KeyboardInterrupt:
       # Handle KeyboardInterrupt (Ctrl+C) to exit the loop gracefully
       pass
    

Troubleshooting

  1. Script Does Not Respond to Tilting

    • Cause: Event listeners (when_activated and when_deactivated) not functioning properly.

    • Solution: Confirm that detect() is correctly linked to both when_activated and when_deactivated events.

  2. LEDs Flicker

    • Cause: Sensor noise or debounce issues.

    • Solution: Add a short delay to stabilize the signal:

    from time import sleep
    def detect():
          sleep(0.05)  # Debounce delay
          if TiltPin.value() == 0:
             red_led.on()
             green_led.off()
          else:
             red_led.off()
             green_led.on()
    

Extendable Ideas

  1. Sound Feedback

    Add a buzzer to provide audio feedback when the tilt sensor is activated:

    from fusion_hat import Buzzer,Pin
    buzzer = Buzzer(Pin(4))
    if TiltPin.value() == 0:
       buzzer.on()
    else:
       buzzer.off()
    
  2. Timed Alerts

    Trigger an alert if the sensor remains tilted for a specified duration:

    from threading import Timer
    def alert():
       print("Tilt detected for too long!")
       red_led.on()
       sleep(0.5)
       red_led.off()
    
    if TiltPin.value() == 0:
       Timer(5, alert).start()  # Trigger alert if tilted for 5 seconds
    

Conclusion

This project demonstrates how to use a tilt switch with a Fusion HAT+ to detect inclinations and control LEDs. Tilt switches are a cost-effective solution for simple motion and angle detection, offering practical applications in robotics and home automation.