Last active
June 9, 2025 15:46
-
-
Save ajangrahmat/4c6803c5619a76e0440b42af9e5d7077 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import network | |
import time | |
from umqtt.simple import MQTTClient | |
import esp32 | |
import random # Import the random module | |
wifi = network.WLAN(network.STA_IF) | |
wifi.active(True) | |
wifi.connect('Wokwi-GUEST', '') | |
client_id = "ESP32_AJANG_1829121" | |
broker = "broker.emqx.io" | |
topik = "hello/09021021/kirimdata" | |
while not wifi.isconnected(): | |
print("Menghubungkan ke WiFi...") | |
time.sleep(0.5) | |
print("Terhubung ke Wi-Fi!") | |
print("Alamat IP:", wifi.ifconfig()[0]) | |
client = MQTTClient(client_id, broker) | |
client.connect() | |
print("Terhubung ke broker MQTT") | |
while True: | |
suhu_raw = esp32.raw_temperature() | |
suhu_celsius = (suhu_raw - 32) * 5/9 | |
# Add a random float between -2.0 and 2.0 to the temperature | |
random_offset = random.uniform(-2.0, 2.0) | |
suhu_with_random = suhu_celsius + random_offset | |
print(f"Suhu ESP32 (asli): {suhu_celsius:.2f}°C") | |
print(f"Random offset: {random_offset:.2f}") | |
print(f"Suhu ESP32 (dengan random): {suhu_with_random:.2f}°C") | |
# Use the temperature with the random offset for publishing | |
pesan = str(suhu_with_random) | |
client.publish(topik.encode(), pesan.encode(), 1) | |
print("Pesan terkirim:", pesan) | |
time.sleep(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment