Introduction: MQTT Based on MicroPython ESP32

I like to keep pet cats. After a day of intense work, the cat can relax me when I get home. After hard training, this cat has a good habit of eating regularly in the "restaurant" every day. But recently I have to travel for a few days and no one is taking care of the cat at home, so I want to use MQTT for remote control feeding. If the cat is eating, this can remind me and let me rest assured


MQTT is a client-server based message publish / subscribe transfer protocol. The MQTT protocol is lightweight, simple, open, and easy to implement, and these features make it widely applicable.

Publish and subscribe

The MQTT protocol defines two types of entities in the network: a message broker and some clients. The agent is a server that receives all messages from the client and then routes these messages to the relevant target client. The client is anything that can interact with the agent to send and receive messages. The client can be an on-site IoT sensor or an application that processes IoT data in a data center.

Step 1: Supplies


MakePython ESP32 is an ESP32 board with an integrated SSD1306 OLED display.


  • uPyCraft IDE

Click to download uPyCraft IDE for Windows

Step 2: Wiring

MakePython ESP32 -- Servo

  • 3V3 -- VCC (red line)
  • GND -- GND (brown line)
  • IO14 -- Signal (orange line)

MakePython ESP32 -- HC-SR04

  • 3V3 -- VCC
  • IO13 -- Trig
  • IO12 -- Echo
  • GND -- GND

Step 3: Code

Download and run the code provided here.

Make the following changes to the file, then save and run.

  • Modify SSID and PSW to connect WiFi
  • Modify the IP of your MQTT broker and determine the topics for publication and subscription
topic_sub = b'feed'
topic_pub = b'state'

Connect and subscribe to topics

def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  client = MQTTClient(client_id, mqtt_server)
  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  return client

publish messages

client = connect_and_subscribe()
client.publish(topic_pub, msg)

Step 4: MQTT Settings

You can download and install the MQTT client here, allowing you to perform remote control on your mobile phone or computer.

  • Open and click to Create MQTT Client
  • Name input feed
  • Protocol select mqtt / tcp
  • Host input:
  • Click save

Step 5: Publish and Subscribe

  • After connecting, topic to publish input: feed. Payload input: on, and then click publish

The servo motor rotates and starts feeding.

  • Topic to subscribe input state, and then click subscribe

When the cat is near the feeder to eat, the subscription topic receives: cat is eating..., the cat receives after leaving: The cat left.

Even if you leave the cat at home, you don't have to worry about it becoming hungry.