"""
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ 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 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
"""
# Shows that the Pi is on by turning on the built-in LED
LED = machine.Pin("LED", machine.Pin.OUT) # Built-in LED on the Pico
LED.on() # Turn on the LED to signal the device is powered and operational
from imu import MPU6050 # Import the MPU6050 library for sensor interfacing
from time import sleep # Import sleep for adding delays
from machine import Pin, I2C # Import Pin and I2C for GPIO and communication
# Initialize RGB LED pins
red = Pin(18, Pin.OUT) # Red LED connected to GPIO 18
green = Pin(17, Pin.OUT) # Green LED connected to GPIO 17
blue = Pin(16, Pin.OUT) # Blue LED connected to GPIO 16
# Configure I2C communication with the MPU6050
# 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) # SDA on GPIO 0, SCL on GPIO 1
imu = MPU6050(i2c) # Initialize the MPU6050 sensor with the I2C instance
print("Change the value of the X-axis Rotation")
# Infinite loop to monitor the X-axis gyro readings and control RGB LEDs
while True:
gx = round(imu.gyro.x) # Read and round the gyro's X-axis angular velocity
print("X-Axis", gx, " ", end="\r") # Display the X-axis reading dynamically
sleep(0.2) # Small delay for stability and readability
# Control the RGB LED color based on the gyro's X-axis readings
if gx <= 30 and gx > 0: # Tilt detected with small X-axis rotation
red.value(1) # Turn on the red LED
green.value(0) # Turn off the green LED
blue.value(0) # Turn off the blue LED
elif gx > 30 and gx <= 60: # Moderate tilt detected
green.value(1) # Turn on the green LED
red.value(0) # Turn off the red LED
blue.value(0) # Turn off the blue LED
elif gx > 60 and gx <= 90: # Larger tilt detected
blue.value(1) # Turn on the blue LED
red.value(0) # Turn off the red LED
green.value(0) # Turn off the green LED
elif gx > 90: # Extreme tilt detected
blue.value(1) # Turn on the blue LED
red.value(1) # Turn on the red LED
green.value(1) # Turn on the green LED
else: # No significant tilt detected
red.value(0) # Turn off the red LED
green.value(0) # Turn off the green LED
blue.value(0) # Turn off the blue LED