from machine import Pin, I2C, ADC, PWM
import time
import dht
import math
# Pin definitions
TRIG_PIN = 3
ECHO_PIN = 2
LED_BLUE_PIN = 15
LED_RED_PIN = 14
LED_GREEN_PIN = 13
THERMISTOR_PIN = 28
RGB_RED_PIN = 8
RGB_GREEN_PIN = 7
RGB_BLUE_PIN = 6
IR_RECV_PIN = 11
LDR_AO_PIN = 26
DHT22_SDA_PIN = 22
# Constants
SERIES_RESISTOR = 10000.0 # Series resistor value in ohms
NOMINAL_RESISTANCE = 10000.0 # Resistance of the thermistor at 25°C
NOMINAL_TEMPERATURE = 25 # Nominal temperature in Celsius
BETA_COEFFICIENT = 3950 # Beta coefficient for the thermistor
GAMMA = 0.7 # Gamma value for LDR calculations
RL10 = 50 # Resistance of the LDR at 10 lux
# Initialize DHT22 sensor
try:
dht22 = dht.DHT22(Pin(DHT22_SDA_PIN))
except Exception as e:
print("Failed to initialize DHT22 sensor: ", e)
# Initialize pins
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
led_blue = Pin(LED_BLUE_PIN, Pin.OUT)
led_red = Pin(LED_RED_PIN, Pin.OUT)
led_green = Pin(LED_GREEN_PIN, Pin.OUT)
thermistor_adc = ADC(Pin(THERMISTOR_PIN))
ldr_adc = ADC(Pin(LDR_AO_PIN))
# Initialize I2C and LCD
try:
i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
devices = i2c.scan()
if not devices:
print("No I2C devices found!")
while True:
pass
I2C_ADDR = devices[0]
from pico_i2c_lcd import I2cLcd
lcd = I2cLcd(i2c, I2C_ADDR, 4, 20) # 4 rows, 20 columns LCD
except Exception as e:
print("Failed to initialize LCD: ", e)
# Initialize PWM for RGB LED
try:
red_pwm = PWM(Pin(RGB_RED_PIN))
green_pwm = PWM(Pin(RGB_GREEN_PIN))
blue_pwm = PWM(Pin(RGB_BLUE_PIN))
red_pwm.freq(1000)
green_pwm.freq(1000)
blue_pwm.freq(1000)
except Exception as e:
print("Failed to initialize PWM for RGB LED: ", e)
# Keys for IR Remote
remote_Key = {
0xa2: 'POWER',0x68: '0', 0x4a: '8',
0xe2: 'MENU', 0x30: '1', 0x52: '9',
0x22: 'TEST', 0x18: '2', 0xb0: 'C',
0x02: 'PLUS', 0x7a: '3', 0x90: 'NEXT',
0xc2: 'BACK', 0x10: '4',
0xe0: 'PREV', 0x38: '5',
0xa8: 'PLAY', 0x5a: '6',
0x98: 'MINUS',0x42: '7',
}
# IR Receiver callback function
def ir_callback(data, addr, ctrl):
if data > 0:
print("IR Data Received: ", data)
if data == 0x68: # Button 0 -> Turn off RGB LED
set_rgb_color(0, 0, 0)
elif data == 0x30: # Button 1 -> Set RGB to Red
set_rgb_color(65535, 0, 0)
elif data == 0x18: # Button 2 -> Set RGB to Green
set_rgb_color(0, 65535, 0)
elif data == 0x7a: # Button 3 -> Set RGB to Blue
set_rgb_color(0, 0, 65535)
elif data == 0x10: # Button 4 -> Set RGB to Cyan
set_rgb_color(0, 65535, 65535)
elif data == 0x38: # Button 5 -> Set RGB to Magenta
set_rgb_color(65535, 0, 65535)
elif data == 0x5a: # Button 6 -> Set RGB to Yellow
set_rgb_color(65535, 65535, 0)
elif data == 0x42: # Button 7 -> Set RGB to White
set_rgb_color(65535, 65535, 65535)
else:
print("Other button pressed")
# Initialize IR Receiver
try:
from ir_rx import NEC_16
ir = NEC_16(Pin(IR_RECV_PIN, Pin.IN), ir_callback)
except Exception as e:
print("Failed to initialize IR receiver: ", e)
# Function to measure distance using HC-SR04 ultrasonic sensor
def measure_distance():
try:
trig.low()
time.sleep(0.002) # Ensure trigger pin is low for a short period
trig.high()
time.sleep(0.01) # Trigger signal for 10 microseconds
trig.low()
while echo.value() == 0:
pass
start = time.ticks_us() # Record the start time
while echo.value() == 1:
pass
end = time.ticks_us() # Record the end time
duration = time.ticks_diff(end, start)
distance = (duration / 2) * 0.0343 # Calculate distance in cm
return distance
except Exception as e:
print("Error measuring distance: ", e)
return None
# Function to measure temperature using a thermistor
def thermistor_temperature():
try:
sensor_value = thermistor_adc.read_u16() / 65535 * 1023
resistance = SERIES_RESISTOR / ((1023.0 / sensor_value) - 1.0)
steinhart = resistance / NOMINAL_RESISTANCE
steinhart = math.log(steinhart) # Natural log of resistance ratio
steinhart /= BETA_COEFFICIENT
steinhart += 1.0 / (NOMINAL_TEMPERATURE + 273.15)
steinhart = 1.0 / steinhart
return steinhart - 273.15 # Convert to Celsius
except Exception as e:
print("Error reading thermistor temperature: ", e)
return None
# Function to read temperature and humidity from DHT22 sensor
def read_dht22():
try:
dht22.measure()
return dht22.humidity(), dht22.temperature()
except Exception as e:
print("Error reading DHT22 sensor: ", e)
return None, None
# Function to measure brightness using an LDR
def measure_brightness():
try:
analog_value = ldr_adc.read_u16()
voltage = analog_value / 65535.0 * 3.3 # Convert ADC value to voltage
if voltage >= 3.3:
voltage = 3.3 # Prevent division by zero or invalid values
resistance = 2000 * voltage / (3.3 - voltage)
lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA)) / 10
return lux
except Exception as e:
print("Error measuring brightness: ", e)
return None
# Function to control RGB LED colors
def set_rgb_color(red, green, blue):
red_pwm.duty_u16(red)
green_pwm.duty_u16(green)
blue_pwm.duty_u16(blue)
# Main loop
while True:
lcd.clear() # Clear the LCD screen before updating
# Measure temperature from thermistor
tempC = thermistor_temperature()
if tempC is not None:
tempF = (tempC * 9.0 / 5.0) + 32.0 # Convert Celsius to Fahrenheit
lcd.move_to(0, 0) # Set beginning of the text at first column, first row on LCD
lcd_line1 = "Temp: {:.1f}{}C|{:.1f}{}F".format(tempC, chr(223), tempF, chr(223))
lcd.putstr(lcd_line1) # Print text to appropriate beginning of LCD screen
# Turn on the red LED if the temperature exceeds 40°C
led_red.value(1 if tempC >= 40.0 else 0)
# Measure temperature and humidity from DHT22 sensor
humidity, temp2 = read_dht22()
if humidity is not None and temp2 is not None:
lcd.move_to(0, 1) # Set beginning of the text at second column, first row on LCD
lcd_line2 = "Hmd: {:.1f}% - {:.1f}{}C".format(humidity, temp2, chr(223))
lcd.putstr(lcd_line2) # Print text to appropriate beginning of LCD screen
# Measure distance from ultrasonic sensor
distance = measure_distance()
if distance is not None:
lcd.move_to(0, 2) # Set beginning of the text at third column, first row on LCD
lcd_line3 = "Distance: {:.1f} cm".format(distance)
lcd.putstr(lcd_line3) # Print text to appropriate beginning of LCD screen
# Turn on the blue LED if the distance is less than 40 cm
led_blue.value(1 if distance < 40.0 else 0)
# Measure brightness from LDR
brightness = measure_brightness()
if brightness is not None:
lcd.move_to(0, 3) # Set beginning of the text at fourth column, first row on LCD
lcd_line4 = "Br: {:.1f} lux".format(brightness)
lcd.putstr(lcd_line4) # Print text to appropriate beginning of LCD screen
# Turn on the green LED if brightness is below 20 lux
led_green.value(1 if brightness < 20.0 else 0)
time.sleep(1) # Delay for 1 second before the next iteration