"""
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ 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 Pi is on by turning on LED when plugged in
LED = machine.Pin("LED", machine.Pin.OUT) # Built-in LED on Raspberry Pi Pico
LED.on() # Turn on the built-in LED to indicate the system is running
from imu import MPU6050 # Import the MPU6050 library for interfacing with the IMU sensor
from time import sleep # Import sleep for creating delays
from machine import Pin, I2C # Import Pin and I2C for hardware control
# Define 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
# Initialize I2C communication
# 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 I2C communication
print("Change the value of the X-axis Rotation")
# Infinite loop to continuously check tilt and control the RGB LED
while True:
gx = round(imu.gyro.x) # Read the gyro's X-axis value and round it to the nearest integer
print("X-Axis", gx, " ", end="\r") # Print the X-axis value, overwriting the same line
sleep(0.2) # Small delay to reduce flickering and stabilize readings
# Determine LED color based on tilt angle (gyro X-axis value)
if gx <= 30 and gx > 0: # If tilt angle is between 0 and 30 degrees
red.value(1) # Turn on Red LED
green.value(0) # Turn off Green LED
blue.value(0) # Turn off Blue LED
elif gx > 30 and gx <= 60: # If tilt angle is between 31 and 60 degrees
green.value(1) # Turn on Green LED
red.value(0) # Turn off Red LED
blue.value(0) # Turn off Blue LED
elif gx > 60 and gx <= 90: # If tilt angle is between 61 and 90 degrees
blue.value(1) # Turn on Blue LED
red.value(0) # Turn off Red LED
green.value(0) # Turn off Green LED
elif gx > 90: # If tilt angle exceeds 90 degrees
blue.value(1) # Turn on Blue LED
red.value(1) # Turn on Red LED
green.value(1) # Turn on Green LED
else: # If no significant tilt is detected
red.value(0) # Turn off Red LED
green.value(0) # Turn off Green LED
blue.value(0) # Turn off Blue LED