from machine import Pin, SoftI2C, PWM
import machine
import time
import dht
import ssd1306
import network
import urequests
url = 'https://apiv2.favoriot.com/v2/streams'
Device_ID = 'Dummy_Data_Sensor@irfanharris'
Access_Token = 'JDuaBRjUXK7zTsbT9O6zyurr0KRYDvwh'
# Connect to Internet
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Initialize I2C bus and OLED display
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oled)
# DHT22 sensor configuration
dht_pin = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)
sensor = dht.DHT22(dht_pin)
# RGB LED configuration
led1_red_pin = machine.Pin(13, machine.Pin.OUT)
led1_green_pin = machine.Pin(12, machine.Pin.OUT)
led1_blue_pin = machine.Pin(14, machine.Pin.OUT)
led2_red_pin = machine.Pin(27, machine.Pin.OUT)
led2_green_pin = machine.Pin(26, machine.Pin.OUT)
led2_blue_pin = machine.Pin(25, machine.Pin.OUT)
def set_led_colors(temperature, humidity):
# Set LED1 color based on temperature
if temperature >= 40:
led1_color = (1, 0, 0)
elif temperature <= 15:
led1_color = (0, 0, 1)
else:
led1_color = (0, 1, 0)
# Set LED2 color based on humidity
if humidity >= 70:
led2_color = (0, 1, 1)
elif humidity <= 30:
led2_color = (1, 1, 0)
else:
led2_color = (1, 0, 1)
# Set LED colors (inverse logic for common anode)
led1_red_pin.value(1 - led1_color[0])
led1_green_pin.value(1 - led1_color[1])
led1_blue_pin.value(1 - led1_color[2])
led2_red_pin.value(1 - led2_color[0])
led2_green_pin.value(1 - led2_color[1])
led2_blue_pin.value(1 - led2_color[2])
while True:
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
data_from_sensor = {'device_developer_id': Device_ID,
'data': {'field1': temperature, 'field2': humidity}}
http_header = {'Content-Type': 'application/json',
'Apikey': Access_Token}
data_submission = urequests.post(url, json=data_from_sensor, headers=http_header)
print(data_submission.status_code)
data_submission.close() # Free up memory
set_led_colors(temperature, humidity)
# Display data on OLED
oled.fill(0)
oled.text("Temp: {:.1f}C".format(temperature), 0, 0)
oled.text("Humidity: {:.1f}%".format(humidity), 0, 12)
oled.show()
print("The Temperature is: {:.1f}C\nThe Humidity is: {:.1f}%".format(temperature, humidity))
time.sleep(5)
except Exception as e:
print("Error:", e)
time.sleep(2)