"""
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Interfacing A Tilt Sensor On The Raspberry Pi (MicroPython) ┃
┃ ┃
┃ The group is tasked with creating a tilt-controlled light ┃
┃ display using Raspberry Pi and a tilt sensor. The goal is ┃
┃ to design a system that changes the color of an RGB LED ┃
┃ based on the tilt angle detected by the tilt sensor. ┃
┃ ┃
┃ Copyright (c) 2024 CPE4B - Group 1 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
"""
# Import necessary libraries
from imu import MPU6050 # For interacting with the MPU6050 sensor
from time import sleep # For adding delays between iterations
from machine import Pin, I2C # For GPIO control and I2C communication
# Built-in LED setup to indicate that the Raspberry Pi Pico is powered on
LED = Pin("LED", Pin.OUT)
LED.on() # Turn on the built-in LED to signal the program is running
# Initialize pins for RGB LEDs
red = Pin(18, Pin.OUT) # GPIO 18 for Red LED
green = Pin(17, Pin.OUT) # GPIO 17 for Green LED
blue = Pin(16, Pin.OUT) # GPIO 16 for Blue LED
# Setup I2C communication
# Uncomment the appropriate line for your device
# For XIAO RP2040:
# i2c = I2C(1, sda=Pin(6), scl=Pin(7), freq=400000)
# For Raspberry Pi Pico:
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000) # GPIO 0 (SDA), GPIO 1 (SCL)
# Initialize the MPU6050 sensor with the configured I2C
imu = MPU6050(i2c)
# Inform the user about what the program does
print("Change the value of the X-axis Rotation")
# Infinite loop to read sensor data and control the RGB LED
while True:
# Read the gyro's X-axis angular velocity and round it to an integer
gx = round(imu.gyro.x)
# Display the X-axis gyro reading on the console dynamically
print("X-Axis:", gx, " ", end="\r")
# Small delay to stabilize readings and reduce flickering
sleep(0.2)
# Determine RGB LED behavior based on the X-axis value
if 0 < gx <= 30: # Low tilt angle
red.value(1) # Red LED ON
green.value(0) # Green LED OFF
blue.value(0) # Blue LED OFF
elif 30 < gx <= 60: # Moderate tilt angle
green.value(1) # Green LED ON
red.value(0) # Red LED OFF
blue.value(0) # Blue LED OFF
elif 60 < gx <= 90: # High tilt angle
blue.value(1) # Blue LED ON
red.value(0) # Red LED OFF
green.value(0) # Green LED OFF
elif gx > 90: # Extreme tilt
blue.value(1) # Blue LED ON
red.value(1) # Red LED ON
green.value(1) # Green LED ON
else: # If the tilt is negligible or negative
red.value(0) # Turn off all LEDs
green.value(0)
blue.value(0)