from machine import ADC, Pin, I2C
import network
import urequests
import time
# Constants
THINGSPEAK_API_KEY = 'YOUR_THINGSPEAK_WRITE_API_KEY'
THINGSPEAK_CHANNEL_ID = 'YOUR_CHANNEL_ID'
# Sensor Pins
voltage_sensor_pin = ADC(Pin(34)) # Voltage sensor connected to GPIO34
current_sensor_pin = ADC(Pin(35)) # Current sensor connected to GPIO35
lm35_sensor_pin = ADC(Pin(32)) # LM35 sensor connected to GPIO32
ldr_sensor_pin = ADC(Pin(33)) # LDR sensor connected to GPIO33
# Function to read sensors
def read_sensors():
voltage = voltage_sensor_pin.read() * (5 / 1023) # Convert ADC value to voltage
current = current_sensor_pin.read() * (5 / 1023) # Convert ADC value to current
temperature = lm35_sensor_pin.read() * (5 / 1023) * 100 # Convert to Celsius
light_intensity = ldr_sensor_pin.read() # Read LDR value
return voltage, current, temperature, light_intensity
# Function to send data to ThingSpeak
def send_to_thingspeak(voltage, current, temperature, light_intensity):
url = f"https://api.thingspeak.com/update?api_key={THINGSPEAK_API_KEY}&field1={voltage}&field2={current}&field3={temperature}&field4={light_intensity}"
response = urequests.get(url)
print(response.text)
response.close()
# Connect to Wi-Fi
def connect_to_wifi():
ssid = 'YOUR_SSID'
password = 'YOUR_PASSWORD'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
# Main loop
def main():
connect_to_wifi()
while True:
voltage, current, temperature, light_intensity = read_sensors()
send_to_thingspeak(voltage, current, temperature, light_intensity)
time.sleep(60) # Send data every 60 seconds
if __name__ == '__main__':
main()