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 |
|---|---|
- |
|
- |
|
Raspberry Pi |
- |
Circuit Diagram
Refer to the following diagrams for connecting the tilt switch:
Wiring Diagram
Follow these steps to set up the circuit:
Connect the tilt switch to GPIO pin 17 on the Raspberry Pi.
Connect the green LED to GPIO pin 27 with a resistor.
Connect the red LED to GPIO pin 22 with a resistor.
Complete the connections by wiring the cathodes of both LEDs to GND.
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:
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).
If the tilt sensor remains upright (in its normal vertical position):
Turns off the red LED.
Turns on the green LED.
The program continuously monitors the tilt sensor’s state and adjusts the LEDs accordingly.
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
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
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
Detect Function
The
detectfunction 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
Main Loop
Assign the
detectfunction to handlewhen_pressedandwhen_releasedevents 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
Script Does Not Respond to Tilting
Cause: Event listeners (
when_activatedandwhen_deactivated) not functioning properly.Solution: Confirm that
detect()is correctly linked to bothwhen_activatedandwhen_deactivatedevents.
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
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()
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.