import machine
import network
import time
from simple import MQTTClient
from machine import SoftI2C, Pin
from i2c_lcd import I2cLcd
# Replace with your Wi-Fi credentials
SSID = 'Wokwi-GUEST'
PASSWORD = ''
# MQTT settings
MQTT_BROKER = 'test.mosquitto.org'
MQTT_PORT = 1883
MQTT_TOPIC_TURBIDITY = b'water/turbidity'
MQTT_TOPIC_PH = b'water/ph'
# Initialize ADCs (Analog to Digital Converters)
adc_turbidity = machine.ADC(machine.Pin(34))
adc_turbidity.width(machine.ADC.WIDTH_10BIT) # 10-bit width, values from 0 to 1023
adc_turbidity.atten(machine.ADC.ATTN_11DB) # Full range: 0-3.3V
adc_ph = machine.ADC(machine.Pin(35))
adc_ph.width(machine.ADC.WIDTH_10BIT) # 10-bit width, values from 0 to 1023
adc_ph.atten(machine.ADC.ATTN_11DB) # Full range: 0-3.3V
# Initialize I2C for LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# Mapping function to scale the turbidity value
def map_turbidity(value):
return (value / 1023) * 100
# Mapping function to scale the pH value
def map_ph(value):
return ((value - 0) * (7 - 1) / (1023 - 0)) + 1
# Connect to Wi-Fi
def connect_wifi(ssid, password):
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('Connecting to network...')
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
time.sleep(1)
print('Network connected:', sta_if.ifconfig())
# Connect to MQTT broker
def connect_mqtt():
client = MQTTClient('esp32_client', MQTT_BROKER, port=MQTT_PORT)
client.connect()
print('Connected to MQTT broker')
return client
# Main program
def main():
connect_wifi(SSID, PASSWORD)
client = connect_mqtt()
try:
while True:
turbidity_value = adc_turbidity.read()
turbidity_scaled = map_turbidity(turbidity_value)
ph_value = adc_ph.read()
ph_scaled = map_ph(ph_value)
print('Turbidity value:', turbidity_scaled)
print('pH value:', ph_scaled)
# Display Turbidity on LCD
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr(f"Turbidity: {turbidity_scaled:.2f}")
if turbidity_scaled > 50:
print("Water is dirty")
lcd.move_to(0, 1)
lcd.putstr("Water is dirty")
else:
print("Water is pure")
lcd.move_to(0, 1)
lcd.putstr("Water is pure")
time.sleep(10) # Wait for 10 seconds
# Display pH on LCD
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr(f"pH Value: {ph_scaled:.2f}")
if 5 <= ph_scaled <= 7:
print("pH acceptable")
lcd.move_to(0, 1)
lcd.putstr("pH acceptable")
else:
print("pH unacceptable")
lcd.move_to(0, 1)
lcd.putstr("pH unacceptable")
time.sleep(5) # Wait for 5 seconds
client.publish(MQTT_TOPIC_TURBIDITY, str(turbidity_scaled))
client.publish(MQTT_TOPIC_PH, str(ph_scaled))
except KeyboardInterrupt:
print('Program stopped')
finally:
client.disconnect()
print('Disconnected from MQTT broker')
if __name__ == '__main__':
main()