from machine import Pin, I2C, ADC, time_pulse_us, deepsleep
import ssd1306, time, network
import ujson
from umqtt.simple import MQTTClient
# todo
# ajouter la partie wifi
# ajouter la partie mqtt
##############
# CONSTANTES #
##############
DEBUG = True #False
# active wifi
WIFI = True
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
# Affichage led
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# potentionmêtre
pot = ADC(Pin(34))
# pot.atten(ADC.ATTN_11DB)
# Affichage
MESSAGE = "distance : "
# Initialisation Variables
new_value=0
new_distance = 0
# Wifi
SSID = "Wokwi-GUEST"
KEY = ""
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather/distance"
##############
def mqtt_connect():
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
return client
def mqtt_update():
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("No change")
time.sleep(1)
def f_deepsleep():
# configure input RTC pin with pull-up on boot
pin = Pin(2, Pin.IN, Pin.PULL_UP)
# disable pull-up and put the device to sleep for 10 seconds
pin.init(pull=None)
deepsleep(10000)
def wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(SSID, KEY)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
ifconfig = sta_if.ifconfig()
return ifconfig
def hc_sr04():
SOUND_SPEED=340 # Vitesse du son dans l'air
TRIG_PULSE_DURATION_US=10
trig_pin = Pin(33, Pin.OUT)
echo_pin = Pin(32, Pin.IN)
# Prepare le signal
trig_pin.value(0)
time.sleep_us(5)
# Créer une impulsion de 10 µs
trig_pin.value(1)
time.sleep_us(TRIG_PULSE_DURATION_US)
trig_pin.value(0)
ultrason_duration = time_pulse_us(echo_pin, 1, 30000) # Renvoie le temps de propagation de l'onde (en µs)
distance_cm = SOUND_SPEED * ultrason_duration / 20000
int_distance_cm = int(distance_cm)
# new_distance = check_new_value(new_distance, int_distance_cm)
print(f"Distance : {distance_cm} cm")
#time.sleep_ms(500)
return int_distance_cm
def oledclear():
"""
clear oled
"""
oled.fill(0)
oled.show()
def oledshow(text, x=0, y=10):
"""
put text on oled with x and y
"""
oled.text(text, x, y)
oled.show()
def check_new_value(nvalue:int, value:int) -> int:
print(f"nvalue before if : {nvalue}")
if nvalue != value:
print(f"nvalue : {nvalue}")
nvalue = value
oledclear()
str_value=str(value)
oledshow(MESSAGE + str_value)
print(f"nvalue before return: {nvalue}")
return nvalue
return nvalue
if WIFI:
ifconfig=wifi()
net1 = "ip: " + ifconfig[0]
net2 = "mask: " + ifconfig[1]
net3 = "gw: " + ifconfig[2]
# connexion mqtt
MQTT_client=mqtt_connect()
while True:
time.sleep(5)
pot_value = pot.read()
print(f"pot value : {pot_value}")
print(f"new value : {new_value}")
# new_value = check_new_value(new_value, pot_value)
# print(pot_value)
int_distance=hc_sr04()
if new_distance != int_distance:
print("Updated!")
new_distance = int_distance
str_distance = str(int_distance)
message1 = "distance :"
message2 = str_distance + " cm"
json_message = ujson.dumps({
"distance": int_distance
})
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, json_message))
if not isinstance(MQTT_client, MQTTClient):
print('Reconnexion MQTT')
MQTT_client=mqtt_connect()
MQTT_client.publish(MQTT_TOPIC, json_message)
MQTT_client.publish(MQTT_TOPIC, json_message)
oledclear()
oledshow(message1, 0, 0)
oledshow(message2, 0, 8)
if (WIFI and DEBUG):
oledshow(net1,0,40)
oledshow(net2,0,48)
oledshow(net3,0,56)
#f_deepsleep()