As I noted at the end of my last log, I was going to test message passing in the reverse direction, from the PC to the ESP32. I am happy to report that my test was successful! I have put the code below so there is a record of what was functional at this stage.
boot.py file. I have removed my network, password, and IP address for security.
import time
import array
from umqtt.simple import MQTTClient
import ubinascii
import machine
from machine import Pin
import micropython
import network
import esp
# wifi network credentials
ssid = '<YOUR_NETWORK>'
password = '<YOUR_PASSWORD>'
mqtt_server = '<SERVER_IP>'
# assigning what topic to subscribe to and publish to
topic_sub = 'motors'
client_id = 'ESP32'
# connects the esp 32 to the wifi network
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
main.py file. I stripped the core functions from the main_PWM.py file, so I was able to verify that the functions that were previously written are operational. The only part that is missing are the PWM pulse instructions that are activated upon receiving a message from the server.
def sub_cb(topic_sub, msg):
m_decode = msg
dir_decode = m_decode.decode('ignore')
print('dir_decode ', dir_decode) # Print to see the message
# PWM pulse instructions will go here
def connect_and_subscribe():
global client_id, mqtt_server, topic_sub
client = MQTTClient(client_id, mqtt_server)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('connected to %s MQTT broker, subscribed to %s topic' %(mqtt_server, topic_sub))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting ...')
time.sleep(2)
machine.reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg()
except OSError as e:
restart_and_reconnect()
See the screenshots below to see the messages passed from my PC to the ESP32!

My next steps will be to test PWM motor functionality.
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.