import time
from machine import Pin, SoftI2C, ADC
from dht import DHT22
import ujson
from ssd1306 import SSD1306_I2C
from Foto import LDR
import network
from umqtt.simple import MQTTClient
# MQTT Server Parameter
MQTT_CLIENT_ID = "FI21"
MQTT_BROKER = "ec2-34-234-203-222.compute-1.amazonaws.com"
MQTT_USER = "FI21"
MQTT_PASSWORD = "FI21"
MQTT_TOPIC = "Met/FI/Ruell"
# Connecting to WLAN
print("Verbinde mit WLAN", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('Wokwi-GUEST', '')
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Verbunden!")
# Connecting to MQTT-Broker
print("Verbinde mit MQTT-Broker... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Verbunden!")
#analoge Werte
sensor = DHT22(Pin(15))
ldr = ADC(Pin(34))
# Variante 1: Konstante Kennwerte Fotowiderstand über Foto.py
Fotowiderstand = LDR()
gamma = Fotowiderstand.GAMMA
rl10 = Fotowiderstand.RL10
# Variante 2: Konstante Kennwerte Fotowiderstand
GAMMA = 0.7
RL10 = 50
#digitale Werte
button = Pin(4, Pin.IN)
led = Pin(2, Pin.OUT)
led_red = Pin(19, Pin.OUT)
led_yellow = Pin(18, Pin.OUT)
led_green = Pin(5, Pin.OUT)
# ESP32 Pin Zuweisung
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = SSD1306_I2C(oled_width, oled_height, i2c)
#Nachkommastellen beschränken
def trim(num, n):
integer = int(num * (10**n))/(10**n)
return float(integer)
while True:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
#Berechnung Lux über analog.read(), Spannung und Widerstandswert
av=ldr.read()/4
v=av/1024*5
r=2000 * v / (1 - v / 5)
lux = pow(rl10 * 1e3 * pow(10, gamma) / r, (1 / gamma))
oled.fill(0)
oled.text('Temperatur: ' , 0, 10)
oled.text(' %.1f C' %temp, 0, 20)
oled.text('Luftfeuchtigkeit:' , 0, 30)
oled.text(' %.1f %%' %hum , 0, 40)
oled.show()
message = ujson.dumps({
"Temperatur": sensor.temperature(),
"Luftfeuchtigkeit": sensor.humidity(),
"Helligkeit": trim(lux,1),
"Bewegungsmelder": button.value()})
#print (message)
json_object = ujson.loads(message)
#print("Temperatur:", json_object["Temperatur"], "°C")
if button.value()==1:
led.value(1)
else:
led.value(0)
if temp >= 30:
led_red.value(1)
led_yellow.value(0)
led_green.value(0)
elif temp < 30 and temp >= 25:
led_red.value(0)
led_yellow.value(1)
led_green.value(0)
else:
led_red.value(0)
led_yellow.value(0)
led_green.value(1)
print("Übermittlung der Parameter an MQTT-Topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
time.sleep(1)