import time
import urequests
from machine import Pin, ADC, I2C
import dht
import ssd1306
# ThingSpeak Configuration
THINGSPEAK_API_KEY = 'P9G0TN0EPG9A5R9N'
THINGSPEAK_URL = 'https://api.thingspeak.com/update?api_key=' + THINGSPEAK_API_KEY
# Initialize I2C for SSD1306
i2c = I2C(0, scl=Pin(22), sda=Pin(21)) # Adjust GPIO pins as needed
oled = ssd1306.SSD1306_I2C(128, 64, i2c) # Adjust width and height as needed
# Set up sensors
dht_sensor = dht.DHT22(Pin(15)) # GPIO 15 for DHT22 Data
ldr = ADC(Pin(34)) # GPIO 34 (A0) for LDR
ldr.atten(ADC.ATTN_11DB) # Set attenuation for full range (0 to 3.3V)
# Define thresholds for "Good Weather"
TEMP_MIN = 20 # Minimum temperature for good weather (in Celsius)
TEMP_MAX = 30 # Maximum temperature for good weather (in Celsius)
HUMIDITY_MIN = 30 # Minimum humidity for good weather (in %)
HUMIDITY_MAX = 60 # Maximum humidity for good weather (in %)
LIGHT_THRESHOLD = 1000 # Light intensity threshold for good weather
# Function to analyze weather based on sensor readings
def analyze_weather(temperature, humidity, light_intensity):
if TEMP_MIN <= temperature <= TEMP_MAX and \
HUMIDITY_MIN <= humidity <= HUMIDITY_MAX and \
light_intensity >= LIGHT_THRESHOLD:
return "Good Weather"
else:
return "Bad Weather"
# Function to display weather status on SSD1306 OLED
def display_on_oled(status):
oled.fill(0) # Clear the display
oled.text('Weather Status:', 0, 0)
oled.text(status, 0, 16) # Display status
oled.show()
# Function to send data to ThingSpeak
def send_to_thingspeak(temperature, humidity, light_intensity):
url = f"{THINGSPEAK_URL}&field1={temperature}&field2={humidity}&field3={light_intensity}"
response = urequests.get(url)
print('ThingSpeak Response:', response.text)
response.close()
# Main function to collect and analyze data
def main():
while True:
# Measure DHT22 data
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Read light intensity from LDR
light_intensity = ldr.read() # Value between 0 and 4095
# Store data in a dictionary
data = {
"temperature": temperature,
"humidity": humidity,
"light_intensity": light_intensity
}
# Analyze whether the weather is good or bad
weather_status = analyze_weather(temperature, humidity, light_intensity)
data["weather_status"] = weather_status # Add weather status to the data
# Print sensor data and analysis result
print(f"Data: {data}")
print(f"Weather Status: {weather_status}")
# Display result on OLED
display_on_oled(weather_status)
# Send data to ThingSpeak
send_to_thingspeak(temperature, humidity, light_intensity)
# Sleep for 10 seconds before the next reading
time.sleep(10)
# Run the main function
main()