import network
import time
from machine import Pin, ADC
import ujson
from umqtt.simple import MQTTClient
import math
# MQTT Server Parameters
MQTT_CLIENT_ID = ""
MQTT_BROKER = "160.187.144.142"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "pcr/24mttka/test/ldr"
GAMMA = 0.7
RL10 = 50
sensor = ADC(Pin(4))
sensor.atten(ADC.ATTN_11DB)
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!")
print("Connecting to MQTT server...", end="")
client = MQTTClient(
MQTT_CLIENT_ID,
MQTT_BROKER,
user=MQTT_USER,
password=MQTT_PASSWORD
)
client.connect()
print("Connected!")
while True:
print("Membaca cahaya resistor...")
sensor_value = int(sensor.read() / 4)
print(sensor_value)
voltage = sensor_value / 1024.0 * 5.0
resistance = 2000.0 * voltage / (1 - voltage / 5.0)
lux = math.pow(
RL10 * 1e3 * math.pow(10, GAMMA) / resistance,
1 / GAMMA
)
print(lux)
message = ujson.dumps({
"lux": lux,
"isLight": True if lux >= 50 else False,
})
# Sesuai contoh Pak Agus:
# client.publish(MQTT_TOPIC, message)
client.publish(MQTT_TOPIC, str(lux))
time.sleep(2)Loading
aitewinrobot-esp32c3-supermini
aitewinrobot-esp32c3-supermini