import network
import _thread
import time
from machine import Pin, I2C
import machine
import ssd1306
from umqtt.simple import MQTTClient
current_speed = 0
dir_pin = machine.Pin(14,machine.Pin.OUT)
step_pin = machine.Pin(12,machine.Pin.OUT)
MQTT_CLIENT_ID = "esp32-variant-2-master"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_TOPIC = "test/tues/wokwi/variant-2"
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!")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
print("Connected to MQTT!")
i2c = I2C(0, scl=Pin(22), sda=Pin(23))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
def getSpeed(temp):
if temp >= 22 and temp <= 24:
return 60
elif temp > 24:
return 120
return 0
def display_speed(speed):
oled.fill(0)
speed_text = f"{speed} rpm"
x = (oled_width - len(speed_text) * 8) // 2
oled.text(speed_text, x, oled_height // 2 - 4)
oled.show()
def move_stepper():
global current_speed
while True:
if current_speed == 0:
step_pin.value(0)
time.sleep(0.1)
continue
dir_pin.value(1)
step_delay = 60 / (current_speed * 200)
step_pin.value(1)
time.sleep(step_delay / 2)
step_pin.value(0)
time.sleep(step_delay / 2)
def sub_cb(topic, msg):
global current_speed
if topic == MQTT_TOPIC.encode():
try:
data = eval(msg)
speed = getSpeed(data['temp'])
display_speed(speed)
current_speed = speed
except Exception as e:
print("Could not parse message: ", e)
client.set_callback(sub_cb)
client.subscribe(MQTT_TOPIC)
_thread.start_new_thread(move_stepper, ())
try:
while True:
client.check_msg()
time.sleep(0.1)
except KeyboardInterrupt:
print('Interrupted')
finally:
oled.fill(0)
oled.show()