<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>mqtt Archives | Teach Me Microcontrollers!</title>
	<atom:link href="https://www.teachmemicro.com/tag/mqtt/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.teachmemicro.com/tag/mqtt/</link>
	<description>Microcontroller Tutorials and Resources</description>
	<lastBuildDate>Sun, 15 Oct 2023 22:05:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://www.teachmemicro.com/wp-content/uploads/2019/04/blue-icon-65x65.png</url>
	<title>mqtt Archives | Teach Me Microcontrollers!</title>
	<link>https://www.teachmemicro.com/tag/mqtt/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>NodeMCU MQTT Tutorial</title>
		<link>https://www.teachmemicro.com/nodemcu-mqtt-tutorial/</link>
					<comments>https://www.teachmemicro.com/nodemcu-mqtt-tutorial/#comments</comments>
		
		<dc:creator><![CDATA[Roland Pelayo]]></dc:creator>
		<pubDate>Fri, 06 Oct 2017 08:34:00 +0000</pubDate>
				<category><![CDATA[ESP8266 Tutorial]]></category>
		<category><![CDATA[iot]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mqtt]]></category>
		<guid isPermaLink="false">https://www.teachmemicro.com/?p=1134</guid>

					<description><![CDATA[<p>So far, we've been using HTTP in our NodeMCU web servers and while it works, the protocol is not really the best way for sending and receiving small-sized data for IoT applications. In this tutorial, I will introduce you to MQTT using ESP8266. What is MQTT? MQTT (Message Queue Telemetry Transport) is a publish-subscribe messaging &#8230;</p>
<p>The post <a href="https://www.teachmemicro.com/nodemcu-mqtt-tutorial/">NodeMCU MQTT Tutorial</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So far, we've been using HTTP in our <a href="https://www.teachmemicro.com/simple-nodemcu-web-server/">NodeMCU web servers</a> and while it works, the protocol is not really the best way for sending and receiving small-sized data for IoT applications. In this tutorial, I will introduce you to MQTT using <a href="https://www.win-source.net/products/detail/espressif/esp8266ex.html">ESP8266</a>.</p>
<p><span id="more-1134"></span></p>
<h3><strong>What is MQTT?</strong></h3>
<p><span style="font-weight: 400;">MQTT (Message Queue Telemetry Transport) is a publish-subscribe messaging protocol widely used in IoT applications. This protocol is designed for data transfer between devices with limited network bandwidth and power. Thus, it is highly recommended for microcontroller projects that sends data over the internet. In this tutorial, I will show you how to use the MQTT protocol in sending data from the NodeMCU to any web page.</span></p>
<p><span style="font-weight: 400;">In our previous <a href="https://www.teachmemicro.com/nodemcu-ajax-dynamic-sensor-data-web-page/">NodeMCU tutorials</a>, we send data to web servers thru HTTP (Hyper Text Transfer Protocol), which is the de facto standard of how web pages are acquired by web browsers. However, HTTP is document-centric which consumes a lot of network bandwidth. MQTT, in contrast, transfers data as a byte array which is more lightweight. HTTP is also a more sophisticated protocol that can drain more power from microcontrollers and embedded computers.</span></p>
<h3><strong>How MQTT Works</strong></h3>
<p><span style="font-weight: 400;">Communication through MQTT needs a "broker" which is responsible for distributing messages to clients based on a certain "topic". A publisher sends data to the broker while subscribers reads data from the broker:</span></p>
<p><img loading="lazy" decoding="async" class="aligncenter" src="https://lh5.googleusercontent.com/1r63cCp28i6DqahqRJ_ZuaIYDy0VmkLacYzXGNlblLsIjk0EbsCkfwLJP4RV8i3wwv48NNX1I8A8aoIRmWP3RW4KyBTPaSPICPSklSBnOSyFvHOkjXCU76UY2TVast1Vz3hBYV8t" alt="Image result for MQTT" width="430" height="328" /></p>
<p id="ontTNcl">You can create your own MQTT broker through apps like <a href="https://mosquitto.org/">mosquitto</a> on a <a href="https://www.teachmemicro.com/raspberry-pi-lcd-hd44780/">Raspberry Pi</a>. You can also use web-based brokers like <a href="https://www.hivemq.com/">hiveMQ</a>, <a href="https://io.adafruit.com">Adafruit IO</a> and <a href="https://shiftr.io">shiftr.io</a>.  For this tutorial, we will be using  shiftr.io.</p>
<p><span style="font-weight: 400;">A typical MQTT </span><b>connection</b><span style="font-weight: 400;"> needs a host name, port, client ID, username and password. Once these are specified, you can </span><b>subscribe</b><span style="font-weight: 400;"> to a topic and start receiving messages on that topic. You can also </span><b>publish</b><span style="font-weight: 400;"> messages on that topic. Unlike HTTP which requires requests to be continually made in order to continually receive a response, the data will continue to go through the MQTT channel until you </span><b>unsubscribe</b><span style="font-weight: 400;"> and </span><b>disconnect</b><span style="font-weight: 400;">.</span></p>
<p><span style="font-weight: 400;">The MQTT protocol is used on top of TCP/IP which means you still need an Internet connection. This tutorial uses NodeMCU which relies on the ESP8266 WiFi library. However, you can also use other devices (Arduino UNO, Arduino Yun, Arduino Ethernet) and use the appropriate libraries to create an Internet connection.</span></p>
<h3><strong>Building the NodeMCU MQTT Sketch</strong></h3>
<p><span style="font-weight: 400;">You'll be needing the Arduino MQTT library which can be downloaded in</span><a href="https://github.com/256dpi/arduino-mqtt"> <span style="font-weight: 400;">256dpi's repository</span></a><span style="font-weight: 400;">.  </span></p>
<p><span style="font-weight: 400;">Once this library is installed on the Arduino IDE, you can now add the &lt;MQQTClient.h&gt; header on your sketch. </span></p>
<p><span style="font-weight: 400;">The Arduino MQTT library is not complicated and uses only a few functions to establish MQTT connection. The bare minimum are:</span></p>
<pre class="lang:arduino decode:true "><code>void begin(const char hostname[], int port, Client &amp;client);
boolean connect(const char clientId[], const char username[], const char password[]);
boolean subscribe(const String &amp;topic);
boolean publish(const char topic[], const char payload[]);</code></pre>
<p><span style="font-weight: 400;">We will start with a simple sketch that publishes sensor readings to shiftr.io's neat web interface. Shiftr.io has a</span><a href="https://shiftr.io/try#terminal"> <span style="font-weight: 400;">"try" channel</span></a><span style="font-weight: 400;"> that you can use without needing to create an account:</span></p>
<p><img decoding="async" src="https://lh5.googleusercontent.com/StayOJWP86z8ZNvUTF6MhJd6KmBFHVoOQMTNyuTDt62SjMYdBCrV3fSxJP3XWltc6j2vH9ah25lghYleWTromF5KqojrnNdu-lh0sNisnSpzGGK8XKPdp2jY7Nxc-WNWpACs3y8N" /></p>
<p id="SbTWZna">Here we see the different subscriber nodes (light grey) connected to the broker (big circle). The name of these nodes are their client ID. The dark grey nodes are the topics. If a subscriber is connected to a topic then it will appear in the diagram as a light grey node. Here a subscriber with client ID javascript is connected to the nodemcu/photocell topic:</p>
<p><img decoding="async" src="https://lh6.googleusercontent.com/IhKfr1ZS2BQ46SadMT36qnh99zqhw6qphacvoGZUjgWepQwk62TFh7jzoTKMM-AlBmZqZxLryymbdvT2Zk0HqIasoMPqP6PsckQknIqhmPoaQl_PDCGqcYtR6_rqVECM6dujvP_-" /></p>
<p id="SmIxETv">The try channel uses “try” as both the username and password. To connect to this channel we use the following function:</p>
<pre class="lang:arduino decode:true "><code>client.connect(“arduino”, "try", "try")</code></pre>
<p><span style="font-weight: 400;">For example, if we want to publish a message to the topic photocell, which is under nodemcu, then the following function is used:</span></p>
<pre class="lang:arduino decode:true "><code>client.publish("nodemcu/photocell", (String)val);</code></pre>
<p><span style="font-weight: 400;">You see that the message is shown on the upper left side of the interface.</span></p>
<p><span style="font-weight: 400;">Here’s a full code that displays sensor readings to the topic nodemcu/photocell on the same try channel:</span></p>
<pre class="lang:arduino decode:true"><code>#include &lt;ESP8266WiFi.h&gt;
#include &lt;MQTTClient.h&gt;


const char* ssid     = "&lt;Your-WiFi-SSID&gt;";
const char* password = "&lt;Your-WiFi-Password&gt;";

WiFiClient WiFiclient;
MQTTClient client;

unsigned long lastMillis = 0;

void setup() {
 Serial.begin(115200);
 delay(10);
 Serial.println();
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);

 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }

 Serial.println("");
 Serial.println("WiFi connected");  
 Serial.println("IP address: ");
 Serial.println(WiFi.localIP());
 delay(2000);

 Serial.print("connecting to MQTT broker...");
 client.begin("broker.shiftr.io", WiFiclient);
 connect();
}

void connect() {
 while (!client.connect("nodemcu", "try", "try")) {
   Serial.print(".");
 }

 Serial.println("\nconnected!");
 client.subscribe("nodemcu");
}

void loop() {
 int val = analogRead(A0);
 client.loop();
 if(!client.connected()) {
   connect();
 }

 if(millis() - lastMillis &gt; 1000) {
   lastMillis = millis();
   client.publish("nodemcu/photocell", (String)val);
 }
}</code></pre>
<p><span style="font-weight: 400;">Upload this sketch to your NodeMCU and open serial monitor. If successful, you should see this message:</span></p>
<p><img decoding="async" src="https://lh4.googleusercontent.com/G3T5qqBEuQ_Vu_3c383kF4wnWSG5lvIUnIdbJyWpskEPFcaqcsV98lgBVO3XFQXgYHbiEyi2fx9frxvunmfFPh8hb1UbfWRR408YWdxU07a7MLbhuUIekEn0V1VbMtuiP63kSu0A" /></p>
<p id="jOjYlJC">Now go to <a href="https://shiftr.io/try#terminal">https://shiftr.io/try#terminal</a> to see the dynamic sensor data being displayed.</p>
<h3><strong>Another NodeMCU as MQTT Client</strong></h3>
<p><span style="font-weight: 400;">How do you read the data you just sent? You can use an MQTT client which can be another NodeMCU, a smartphone or a web browser.</span></p>
<p><span style="font-weight: 400;">Using another NodeMCU, you can modify the same NodeMCU sketch we used so that it will start accepting messages from the MQTT broker:</span></p>
<p>&nbsp;</p>
<pre class="lang:arduino decode:true "><code>#include &lt;ESP8266WiFi.h&gt;
#include &lt;MQTTClient.h&gt;

const char* ssid &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;= "&lt;Your-WiFi-SSID&gt;"; 
const char* password = "&lt;Your-WiFi-Password&gt;";

WiFiClient WiFiclient;
MQTTClient client;

unsigned long lastMillis = 0;

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
       delay(500);
       Serial.print(".");
    }

  Serial.println("");
  Serial.println("WiFi connected"); 
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  delay(2000);
  client.onMessage(messageReceived);
  Serial.print("connecting to MQTT broker...");
  client.begin("broker.shiftr.io", WiFiclient);

  connect();
}

void connect() {
  while (!client.connect("nodemcu", "try", "try")) {
    Serial.print(".");
  }

  Serial.println("\nconnected!");
  client.subscribe("nodemcu");
}

void loop() {
  int val = analogRead(A0);
  client.loop();
  if(!client.connected()) {
     connect();
  }
}

void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
  Serial.print("incoming: ");
  Serial.print(topic);
  Serial.print(" - ");
  Serial.print(payload);
  Serial.println();
}</code></pre>
<p><span style="font-weight: 400;">We removed the <em>client.publish()</em> part and added a <em>messageReceived()</em> function. The data from the topic you subscribed to will be shown on the serial monitor.</span></p>
<h3><strong>Smartphone MQTT Client</strong></h3>
<p><span style="font-weight: 400;">You can use free smartphone apps to get data from a MQTT topic. I used the iOS app, <em>Mqtt</em> which when run, asks you for the hostname, port, username and password:</span></p>
<p><img loading="lazy" decoding="async" class="aligncenter" src="https://lh4.googleusercontent.com/4T9RDR0RQvVCHsmxLW8KlKoQXjkPQKvOpDh5u5fRZpxzgGeeXH55uIHxdjS6f4xyGwbayfZoshZdZf5Yz4LapdmANbLugRQFfyUqykLXv1C421CBtS68NR4ZzwFP_9wzWk9arVc8" width="251" height="446" /></p>
<p id="wOVSFec">After that, you have the main interface. You can subscribe to a topic on the upper half and publish a message on the lower half:</p>
<p><img loading="lazy" decoding="async" class="aligncenter" src="https://lh4.googleusercontent.com/9_a2ygIMSmSh65Ss11ZdBVqC0xOemmdfhnm89N8hPeRhKD95DbgHuyyzRC4wikqXHfVOx2uVcjW79iY3863zHXEL0nkYk0QIwPnlFS6BZCQY5wopxiUiHrhWtFdqjRVusoqwxYlV" width="251" height="446" /></p>
<p id="deoSmyv">Here we see the sensor data being displayed.</p>
<p><strong>Web Browser MQTT Client</strong></p>
<p><span style="font-weight: 400;">To embed the sensor data to a web page, you need to invoke the mqtt.js library. Here’s an example script that you can use:</span></p>
<pre class="lang:js decode:true "><code>$(function(){
 var client = mqtt.connect('mqtt://try:try@broker.shiftr.io', {
   clientId: 'browser-client'
 });

 client.on('connect', function(){
   console.log('client has connected!');
 });

 client.on('message', function(topic, message) {
  $('#data').text(message.toString());
 });
   client.subscribe('nodemcu/photocell');
})</code></pre>
<p><span style="font-weight: 400;">Save the script above as script.js.</span></p>
<p><span style="font-weight: 400;">Here’s a very simple HTML for displaying the data:</span></p>
<pre class="lang:xhtml decode:true"><code>&lt;html&gt;
&lt;title&gt;NodeMCU Photocell Data&lt;/title&gt;
&lt;head&gt;
   &lt;script src="https://code.jquery.com/jquery-2.2.3.min.js"&gt;&lt;/script&gt;
   &lt;script src="https://assets.shiftr.io/js/mqtt-latest.js"&gt;&lt;/script&gt;
   &lt;script src="script.js" charset="utf-8"&gt;&lt;/script&gt;
&lt;/head&gt;
 &lt;body&gt;
   &lt;p id="data"&gt;&lt;/p&gt;
 &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p><span style="font-weight: 400;">Save the HTML file and then open it using your web browser. You should now be able to see the data:</span></p>
<p><img decoding="async" class="aligncenter" src="https://lh5.googleusercontent.com/KbAHBSQuG0NePOlAXGFDe4BIHEab5ZGkjWIYB57BDBKxodijypHiBdsNEHY2M-o9MzYUv5aJMP6DRnSbBsLDhCeYpMYOTPDxIzETyAY7TIJnmcIzf-WaQpuwE97bP8O22rP2OYAO" /></p>
<p id="QDnMele">Hopefully, this opens the way for you to make greater IoT applications using NodeMCU or Arduino. On my next tutorial, I will show how to create your own MQTT broker with the Raspberry Pi.</p>
<p><span style="font-weight: 400;">Was this tutorial useful? Place a comment below!</span></p>
<p>&nbsp;</p>
<p>The post <a href="https://www.teachmemicro.com/nodemcu-mqtt-tutorial/">NodeMCU MQTT Tutorial</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.teachmemicro.com/nodemcu-mqtt-tutorial/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: www.teachmemicro.com @ 2026-11-25 01:24:17 by W3 Total Cache
-->