import network
import time
import ubinascii
import machine
from umqtt.simple import MQTTClient
from ds18x20 import DS18X20
from onewire import OneWire
import urequests
import random # Untuk simulasi di Wokwi
# Konfigurasi WiFi
SSID = "Wokwi-GUEST"
PASSWORD = ""
# Konfigurasi Ubidots
UBIDOTS_TOKEN = "BBUS-wPE0hFaW61j05borzjgipWf5ma0bRZ"
MQTT_BROKER = "industrial.api.ubidots.com"
DEVICE_LABEL = "demo-machine"
TOPIC = b"/v1.6/devices/%s" % DEVICE_LABEL
# API untuk MongoDB
API_URL = "http://0.0.0.0:5000/sensor-data"
# Inisialisasi WiFi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
while not wifi.isconnected():
time.sleep(1)
print("WiFi Connected:", wifi.ifconfig())
# Inisialisasi MQTT
client_id = ubinascii.hexlify(machine.unique_id())
mqtt_client = MQTTClient(client_id, MQTT_BROKER, user=UBIDOTS_TOKEN, password="")
# Inisialisasi Sensor
ds_pin = machine.Pin(18)
ow = OneWire(ds_pin)
ds_sensor = DS18X20(ow)
roms = ds_sensor.scan()
sensor_gas = machine.ADC(machine.Pin(32)) # MQ-4
sensor_tekanan = machine.ADC(machine.Pin(33)) # MPX5700AP
if not roms:
raise RuntimeError("Sensor DS18B20 tidak ditemukan!")
def read_sensors():
ds_sensor.convert_temp()
time.sleep(1)
temp = ds_sensor.read_temp(roms[0]) if roms else None
methane = sensor_gas.read() * (5.0 / 1024.0) # Volt
pressure = sensor_tekanan.read() * (5.0 / 1024.0) # Volt
# Simulasi nilai di Wokwi
if "wokwi" in wifi.ifconfig()[0]:
temp = round(random.uniform(30, 50), 2)
methane = round(random.uniform(0.2, 1.2), 2)
pressure = round(random.uniform(0.5, 2.5), 2)
return temp, methane, pressure
def send_data():
temp, methane, pressure = read_sensors()
# Kirim ke Ubidots
payload = {
"temperature": {"value": temp},
"methane": {"value": methane},
"pressure": {"value": pressure}
}
mqtt_client.connect()
mqtt_client.publish(TOPIC, str(payload).replace("'", '"'))
mqtt_client.disconnect()
print("Data sent to Ubidots:", payload)
# Kirim ke API MongoDB
try:
response = urequests.post(API_URL, json=payload)
print("Data sent to MongoDB:", response.text)
except Exception as e:
print("Error sending to MongoDB:", e)
while True:
send_data()
time.sleep(10)Loading
ds18b20
ds18b20