Connect ESP32/ESP8266 & C# .NET Core Using MQTT – Easy Tutorial

Here’s a tutorial that shows you how to quickly connect a Windows PC C# application to an ESP32, ESP32 CAM or ESP8266 microcontroller over wifi. The two connected devices will communicate with each other using the MQTT protocol. This is a lightweight Internet of Things (IoT) protocol and it’s supported by both C# and the ESP32 and ESP8266 controllers. Because it uses a standard wifi connection there doesn’t need to be a physical cable connection between the PC and the microcontroller device.

This video largely demonstrates how to get the two devices communicating successfully. In particular I cover what libraries to use, as well as troubleshooting the major issues I had in getting MQTT working on my own home wifi network (including which IP address to connect to and Windows Defender Firewall issues). If you want to send and receive anything useful then watch my other MQTT videos.

The .NET Core server code is derived from the samples in the MQTTnet libraries (also available as Nuget packages).

MQTT (MQ Telemetry Transport) is a client-server model. The server is called a broker and multiple clients may connect to it. In this example I’ve set the PC up as the server, and an ESP32 CAM device as the client using the PubSubClient library. You might think it would be better the other way round. However, it’s much easier to get microcontrollers running as the client.

If you want to test your MQTT applications then download the MQTT application. There’s also an application called MyMQTT that is in the Play Store for Android devices.

Source Code

//Basic Arduino IDE sketch required to connect to MQTT server
//using ESP32, ESP32 CAM or ESP8266 microcontroller
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti WiFiMulti;
 
#include <PubSubClient.h>
 
// Update these with values suitable for your network.
 
const char* ssid = "MY_WIFI_NETWORK_SSID";
const char* password = "MY_WIFI_NETWORK_PASSWORD";
const char* mqtt_server = "IP_ADDRESS_OF_MQTT_SERVER";
 
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
 
void setup_wifi() {
 
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  randomSeed(micros());
 
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
 
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
 
}
 
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
 
void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
 
void loop() {
 
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
 
  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *