from gpiozero import RGBLED, MCP3008
import time
import math
# Initialize RGB LED with GPIO pins
led = RGBLED(red=17, green=27, blue=22)
# Initialize MCP3008 channels for ADXL335
x_channel = MCP3008(channel=0) # X-axis output
y_channel = MCP3008(channel=1) # Y-axis output
def get_tilt_angle(x, y):
return math.degrees(math.atan2(y, x))
def set_rgb_color(angle):
"""Smoothly change RGB LED color based on tilt angle."""
if 0 <= angle <= 30:
led.color = (1, 0, 0) # Red
elif 31 <= angle <= 60:
# Smooth transition from red to green
red_intensity = (60 - angle) / 30
green_intensity = (angle - 30) / 30
led.color = (red_intensity, green_intensity, 0)
elif 61 <= angle <= 90:
# Smooth transition from green to blue
green_intensity = (90 - angle) / 30
blue_intensity = (angle - 60) / 30
led.color = (0, green_intensity, blue_intensity)
try:
while True:
# Read ADC values from ADXL335
x_val = x_channel.value * 3.3 # Convert to voltage (0-3.3V)
y_val = y_channel.value * 3.3 # Convert to voltage (0-3.3V)
print(f"x_analog: {x_channel.value} | x_val: {x_val}")
print(f"y_analog: {y_channel.value} | y_val: {y_val}")
# Calculate tilt angle based on x and y values
angle = math.abs(get_tilt_angle(x_val - 1.65, y_val - 1.65) - 90) # Offset for ADXL335
print(f"Angle: {angle}")
# Update RGB LED color based on tilt angle
set_rgb_color(angle)
# Wait a bit before next reading
time.sleep(0.1)
except KeyboardInterrupt:
led.off()
print("Program terminated.")