<?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>ajax | Microcontroller Tutorials</title>
	<atom:link href="https://www.teachmemicro.com/tag/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.teachmemicro.com</link>
	<description>Microcontroller Tutorials and Resources</description>
	<lastBuildDate>Sun, 15 Oct 2023 21:59:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://www.teachmemicro.com/wp-content/uploads/2019/04/blue-icon-65x65.png</url>
	<title>ajax | Microcontroller Tutorials</title>
	<link>https://www.teachmemicro.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Sensor Display on ESP32 Web Server</title>
		<link>https://www.teachmemicro.com/sensor-display-on-esp32-web-server/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sensor-display-on-esp32-web-server</link>
					<comments>https://www.teachmemicro.com/sensor-display-on-esp32-web-server/#comments</comments>
		
		<dc:creator><![CDATA[Roland Pelayo]]></dc:creator>
		<pubDate>Sun, 19 Jan 2020 10:07:13 +0000</pubDate>
				<category><![CDATA[ESP32 Tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[dht11]]></category>
		<category><![CDATA[esp32]]></category>
		<category><![CDATA[iot]]></category>
		<guid isPermaLink="false">https://www.teachmemicro.com/?p=4064</guid>

					<description><![CDATA[<p>Last time, I showed you how to setup the ESP32 development board with the Arduino programming environment. This time, I will be building a simple ESP32 web server where data from a sensor is displayed on a web page. For this tutorial, I will be using the DHT11 Humidity and Temperature sensor. This is a &#8230;</p>
<p>The post <a href="https://www.teachmemicro.com/sensor-display-on-esp32-web-server/">Sensor Display on ESP32 Web Server</a> first appeared on <a href="https://www.teachmemicro.com">Microcontroller Tutorials</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Last time, I showed you <a href="https://www.teachmemicro.com/using-esp32-for-the-first-time/">how to setup the ESP32 development board with the Arduino</a> programming environment. This time, I will be building a simple <a href="https://www.win-source.net/products/detail/espressif/esp32-pico-d4.html"><strong>ESP32</strong></a> <strong>web server</strong> where data from a sensor is displayed on a web page.</p>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-Web-server.jpg"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4248" src="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-Web-server.jpg" alt="ESP32 Web Server" width="700" height="526" srcset="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-Web-server.jpg 700w, https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-Web-server-300x225.jpg 300w, https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-Web-server-320x240.jpg 320w" sizes="auto, (max-width: 700px) 100vw, 700px" /></a></p>
<p><span id="more-4064"></span></p>
<p>For this tutorial, I will be using the <strong>DHT11 Humidity and Temperature sensor</strong>. This is a widely available sensor so I think a lot of you can reproduce the outputs of this tutorial. For those interested, I’ve shown <a href="https://www.teachmemicro.com/how-dht22-sensor-works/">how the similar DHT22 sensor works.</a></p>
<h3><strong>Wiring the DHT11 ESP32 Web Server</strong></h3>
<p>The DHT11 doesn’t produce a time varying signal so there’s no need for an analog-to-digital pin. This gives us a lot of flexibility when using it. There are three usable out of its four pins:</p>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2020/01/DHT11-pinout.jpg"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4065" src="https://www.teachmemicro.com/wp-content/uploads/2020/01/DHT11-pinout.jpg" alt="DHT11 pinout" width="414" height="456" srcset="https://www.teachmemicro.com/wp-content/uploads/2020/01/DHT11-pinout.jpg 414w, https://www.teachmemicro.com/wp-content/uploads/2020/01/DHT11-pinout-272x300.jpg 272w" sizes="auto, (max-width: 414px) 100vw, 414px" /></a></p>
<p>The temperature and humidity are serially read through the DATA pin. Also, the DHT11’s VCC pin can accept either 3.3 V or 5 V.</p>
<p>Meanwhile, here’s the pinout for the ESP-32S development board we are using:</p>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32S-DEV-BOARD-PINOUT.jpg"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4066" src="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32S-DEV-BOARD-PINOUT.jpg" alt="ESP-32S Pinout" width="620" height="699" srcset="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32S-DEV-BOARD-PINOUT.jpg 620w, https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32S-DEV-BOARD-PINOUT-266x300.jpg 266w" sizes="auto, (max-width: 620px) 100vw, 620px" /></a></p>
<p>Make sure you have the same board as I do when following this tutorial. I’m saying this because there are similar looking boards out there that follow different pin arrangements.</p>
<p>We can connect the DHT11’s data pin to any of the ESP32 dev board’s GPIO pins. Here’s the circuit connection I used:</p>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-DHT11-wiring-diagram.jpg"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4246" src="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-DHT11-wiring-diagram.jpg" alt="ESP32 DHT11 Wiring diagram" width="779" height="645" srcset="https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-DHT11-wiring-diagram.jpg 779w, https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-DHT11-wiring-diagram-300x248.jpg 300w, https://www.teachmemicro.com/wp-content/uploads/2020/01/ESP32-DHT11-wiring-diagram-768x636.jpg 768w" sizes="auto, (max-width: 779px) 100vw, 779px" /></a></p>
<h3><strong>Testing the DHT11</strong></h3>
<p>Now that we’ve wired the DHT11 sensor to the ESP32 board, it’s time to test if we can really read temperature and humidity from the sensor. We can do this by uploading a simple sketch that is known to work with Arduino boards. Make sure you’ve followed the instructions from the <a href="https://www.teachmemicro.com/using-esp32-for-the-first-time/">previous post</a> so that you can use the Arduino IDE to program the ESP32.</p>
<p>First, we need to download some libraries for the DHT11. Fire up the Arduino IDE and open <strong>Library Manager</strong> via <em>Sketch &gt; Include Library &gt; Manage Libraries</em> or shortcut key <em>CTRL+SHIFT+I</em>.</p>
<p>Type "DHT" on the search field and look for <strong>Adafruit’s DHT Sensor</strong> library then install it:</p>
<p><img decoding="async" class="aligncenter" src="https://lh6.googleusercontent.com/ALHtpl1xEIl4ppbCiOEm3Um_TbBGzSQ5tyrKG2xNbCE1DgKkWNhLjo0KClyzBXo_5j8zTxsIwO56nQedOXtJPXtQvPilG5d_DHsJAJr8ZwAMRKcqu1RzMpBINP5_QvB8qMmmanFB" /></p>
<p id="ZfvgUgi">You will be prompted to install <strong>Adafruit’s Unified Sensor</strong> library. Click yes.</p>
<p>Once the library is installed, you’ll have access to the <em>DHT_Unified_Sensor</em> example sketch:</p>
<p><img decoding="async" class="aligncenter" src="https://lh5.googleusercontent.com/Gnw-5j3Zd6Sy4qvhwhvdx0b5pae6B5d7fw1L9DbsAQ63oXqIOKKR4Gvdgz0Tv59KmrcsPaE0OC8bjl6nrcLE4nOq-QuXYW48g9LXQCfAQlXGTMw_yKjpSe4J9H3Q4bYTb5ArKmFz" /></p>
<p id="uLvMwYc">Once the sketch open, make sure that the data pin (line 14) and type of sensor (line 19) is correct:</p>
<p><img decoding="async" class="aligncenter" src="https://lh6.googleusercontent.com/WSEfG1abtq_3mZHMR8XBESijgNHGIDoOFxqvGWXm2W8Ntky3oDhOOQNU2ulpDBzL-VxdjNX-fWln4Ybs8HN2WlvqG_QRq3GIE7qcgZ-p2dUg-QUd7r5oPyr_H3X3dvRGT0d26a26" /></p>
<p id="DBWjuMN">Upload the sketch (don’t forget to press and hold the BOOT button while uploading and then press EN if uploading is done) and open serial monitor (baud rate at 9600). The ambient temperature and humidity are now shown:</p>
<p><img decoding="async" class="aligncenter" src="https://lh4.googleusercontent.com/iHvGfN0AIFziS6EjCudFPdTrQA18dBxTkthqjxOhNJHWlVQHGVGfQBfx7L7qQJDM8px4_bhNxu4RNaNY-pthw7yu6rlHVPhlihzUKuuPFALWKHxiCLf8uwQ8RoOa4Yoqa4c0_C3Y" /></p>
<p id="pdleXyV"><em>If you are having problems uploading the sketch, try to remove the wire from the ESP32's 5V to DHT11 and try uploading again.</em></p>
<h3><strong>The DHT11 ESP32 Web Server Sketch, Finally</strong></h3>
<p>Now we can read temperature and humidity from the DHT11. The next step is to create a sketch where the data is visible on a web page.</p>
<p>I’ll go directly to the sketch:</p>
<pre class="lang:arduino decode:true"><pre><code class="language-cpp">#include &lt;WiFi.h&gt;
#include &lt;WiFiClient.h&gt;
#include &lt;WebServer.h&gt;
#include &lt;Adafruit_Sensor.h&gt;
#include &lt;DHT.h&gt;
#include &lt;DHT_U.h&gt;

const char* ssid = &quot;&lt;your WiFi SSID&gt;&quot;;
const char* password = &quot;&lt;your WiFi password&gt;&quot;;

WebServer server(80);

String text= &quot;&quot;;
double temp;
double hum;

#define DHTPIN 2
#define DHTTYPE    DHT11 

DHT_Unified dht(DHTPIN, DHTTYPE);

const String page PROGMEM = &quot;&lt;head&gt;&quot;
            &quot; &lt;script src=\&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\&quot;&gt;&lt;/script&gt;&quot;
            &quot; &lt;/head&gt;&quot;
            &quot; &lt;body&gt;&quot;
            &quot; &lt;h1&gt;Sensor to ESP32 Web Server&lt;/h1&gt;&lt;h2&gt;Temperature:&lt;/h2&gt; &lt;h2 id=\&quot;temp\&quot;&gt;&quot;&quot;&lt;/h2&gt;\r\n&quot;
            &quot; &lt;h2&gt;Humidity:&lt;/h2&gt;&lt;h2 id=\&quot;hum\&quot;&gt;&quot;&quot;&lt;/h2&gt;\r\n&quot; 
            &quot; &lt;script&gt;\r\n&quot;
            &quot; $(document).ready(function(){\r\n&quot;
            &quot; setInterval(getData,1000);\r\n&quot;
            &quot; function getData(){\r\n&quot;
            &quot; $.ajax({\r\n&quot;
            &quot;  type:\&quot;GET\&quot;,\r\n&quot;
            &quot;  url:\&quot;data\&quot;,\r\n&quot;
            &quot;  success: function(data){\r\n&quot;
            &quot;  var s = data.split(\&#039;-\&#039;);\r\n&quot;
            &quot;  $(&#039;#temp&#039;).html(s[0]);\r\n&quot;
            &quot;  $(&#039;#hum&#039;).html(s[1]);\r\n&quot;
            &quot;}\r\n&quot;
            &quot;}).done(function() {\r\n&quot;
            &quot;  console.log(&#039;ok&#039;);\r\n&quot;
            &quot;})\r\n&quot;
            &quot;}\r\n&quot;
            &quot;});&quot;
            &quot;&lt;/script&gt;\r\n&quot;
            &quot;&lt;/body&gt;&quot;;

void setup(void) {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println(&quot;&quot;);
  dht.begin();
  sensor_t sensor;
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(&quot;.&quot;);
  }
  Serial.println(&quot;&quot;);
  Serial.print(&quot;Connected to &quot;);
  Serial.println(ssid);
  Serial.print(&quot;IP address: &quot;);
  Serial.println(WiFi.localIP());

  server.on(&quot;/data&quot;, [](){
    sensors_event_t event;
    dht.temperature().getEvent(&amp;event);
    if(isnan(event.temperature)){
      temp = 0;
    }else{
      temp =  (double)event.temperature;
    }
    delay(1000);
    dht.humidity().getEvent(&amp;event);
    if(isnan(event.relative_humidity)){
      hum = 0;
    }else{
      hum =  (double)event.relative_humidity;
    }
    delay(1000); 
    text = (String)temp;
    text += &quot;-&quot;;
    text += (String)hum;
    Serial.println(text);
    server.send(200, &quot;text/plain&quot;, text);
  });

  server.on(&quot;/&quot;, []() {
   server.send(200, &quot;text/html&quot;, page);
  });

  server.begin();
  Serial.println(&quot;HTTP server started&quot;);
}

void loop(void) {
  server.handleClient();
}</code></pre></pre>
<p>Upload this sketch (again, don’t forget to press and hold the BOOT button and when successful, press the EN button on the board).</p>
<p>If you open the serial monitor, you should see this:</p>
<p><img loading="lazy" decoding="async" class="aligncenter" src="https://lh5.googleusercontent.com/sb5waVlkkUsr3l5eraC1-AJvAonB71hVq9QGvUsKDl1haDGHdfC9PBh1mrZsny3LBqjHCj_qtQzSdOeZ6m6Ts1F-NGGoDNHMORVguElcc4s5TUIKJW_ie6pX9pk8UXal5TG3BY7m" alt="ESP32 web server running 1" width="608" height="371" /></p>
<p id="XIGyycf">It shows the IP address of the server. Using your favorite browser, visit that IP address and you should see this:</p>
<p><img loading="lazy" decoding="async" class="aligncenter" src="https://lh5.googleusercontent.com/xiYTiKwjPOezAjKWxL27BwI-iD6kkFHFjcSlwNwB8TlyoEUpxg8PjHdaZGDhtE86pHO8HIphyzJWrSOqJK9Fo13QXmZWHFHN8mblucmJkzSrGTr-bmZFHZ4uuLT5ClEhuUb95zae" alt="ESP32 web server running 2" width="947" height="715" /></p>
<p id="uTAWGxV">What’s good about my sketch is that you don’t need to refresh the page to update the sensor values. This is through the help of asynchronous javascript or AJAX as shown on <a href="https://www.teachmemicro.com/nodemcu-ajax-dynamic-sensor-data-web-page/">this tutorial</a>. However, I used <a href="https://www.w3schools.com/jquery/ajax_ajax.asp">JQuery AJAX</a> instead of the older method.</p>
<h3><strong>Explaining the Sketch</strong></h3>
<p>What I did is utilize the ESP32's <em>WiFi station mode</em> so it connects to my router. And as long as I am on a computer or smartphone connected to the same router, I can access the ESP32 via its IP address.</p>
<p>The first part of the sketch is just a bunch of declarations:</p>
<pre class="lang:arduino decode:true"><pre><code class="language-cpp">#include &lt;WiFi.h&gt;
#include &lt;WiFiClient.h&gt;
#include &lt;WebServer.h&gt;
#include &lt;Adafruit_Sensor.h&gt;
#include &lt;DHT.h&gt;
#include &lt;DHT_U.h&gt;

const char* ssid = &quot;&lt;your WiFI SSID&quot;;
const char* password = &quot;&lt;your WiFi password&gt;&quot;;

WebServer server(80);

String text= &quot;&quot;;
double temp;
double hum;

#define DHTPIN 2
#define DHTTYPE    DHT11 

DHT_Unified dht(DHTPIN, DHTTYPE);</code></pre></pre>
<p>Here I included all the needed libraries including the DHT11 library from Adafruit.</p>
<p>Don’t forget to change lines 8 and 9 to your own WiFi SSID and password!</p>
<p>Then, I wrote the HTML root page of the server as one multiline string and store it in flash memory:</p>
<pre class="lang:arduino decode:true"><pre><code class="language-cpp">const String page PROGMEM = &quot;&lt;head&gt;&quot;
            &quot; &lt;script src=\&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\&quot;&gt;&lt;/script&gt;&quot;
            &quot; &lt;/head&gt;&quot;
            &quot; &lt;body&gt;&quot;
            &quot; &lt;h1&gt;Sensor to ESP32 Web Server&lt;/h1&gt;&lt;h2&gt;Temperature:&lt;/h2&gt; &lt;h2 id=\&quot;temp\&quot;&gt;&quot;&quot;&lt;/h2&gt;\r\n&quot;
            &quot; &lt;h2&gt;Humidity:&lt;/h2&gt;&lt;h2 id=\&quot;hum\&quot;&gt;&quot;&quot;&lt;/h2&gt;\r\n&quot; 
            &quot; &lt;script&gt;\r\n&quot;
            &quot; $(document).ready(function(){\r\n&quot;
            &quot; setInterval(getData,1000);\r\n&quot;
            &quot; function getData(){\r\n&quot;
            &quot; $.ajax({\r\n&quot;
            &quot;  type:\&quot;GET\&quot;,\r\n&quot;
            &quot;  url:\&quot;data\&quot;,\r\n&quot;
            &quot;  success: function(data){\r\n&quot;
            &quot;  var s = data.split(\&#039;-\&#039;);\r\n&quot;
            &quot;  $(&#039;#temp&#039;).html(s[0]);\r\n&quot;
            &quot;  $(&#039;#hum&#039;).html(s[1]);\r\n&quot;
            &quot;}\r\n&quot;
            &quot;}).done(function() {\r\n&quot;
            &quot;  console.log(&#039;ok&#039;);\r\n&quot;
            &quot;})\r\n&quot;
            &quot;}\r\n&quot;
            &quot;});&quot;
            &quot;&lt;/script&gt;\r\n&quot;
            &quot;&lt;/body&gt;&quot;;</code></pre></pre>
<p>Again, AJAX allows me to get data without refreshing the page. The AJAX part of the page is this part (minus the extra characters):</p>
<pre class="lang:js decode:true"><pre><code class="language-cpp">function getData(){
$.ajax({
  type:&quot;GET&quot;,
  url:&quot;data&quot;,
  success: function(data){
    var s = data.split(&#039;-&#039;);
    $(&#039;#temp&#039;).html(s[0]);
    $(&#039;#hum&#039;).html(s[1]);
  }
}).done(function() {
    console.log(&#039;ok&#039;);
  })
}</code></pre></pre>
<p>Here, the type of request is specified (GET), the url of the data source (data), and <em>what to do</em> when the data retrieval is successful. This function triggers every second through the <a href="https://www.w3schools.com/jsref/met_win_setinterval.asp">javascript <em>setInterval()</em></a> function. Of course this won't work without the jquery library hence this part:</p>
<pre class="lang:arduino decode:true "><pre><code class="language-cpp">&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js&quot;&gt;&lt;/script&gt;</code></pre></pre>
<p>Web developers might have better methods but this one does the job.</p>
<p>Inside <em>setup()</em> we initialize the serial port for debugging and then we make ESP32 a WiFi station:</p>
<pre class="lang:arduino decode:true"><pre><code class="language-cpp">Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println(&quot;&quot;);
dht.begin();
sensor_t sensor;
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(&quot;.&quot;);
}
Serial.println(&quot;&quot;);
Serial.print(&quot;Connected to &quot;);
Serial.println(ssid);
Serial.print(&quot;IP address: &quot;);
Serial.println(WiFi.localIP());</code></pre></pre>
<p>Then we define what the server does when a client accesses the <em>data</em> page:</p>
<pre class="lang:arduino decode:true "><pre><code class="language-cpp">server.on(&quot;/data&quot;, [](){
   sensors_event_t event;
   dht.temperature().getEvent(&amp;event);
   if(isnan(event.temperature)){
      temp = 0;
   }else{
      temp = (double)event.temperature;
   }
   delay(1000);
   dht.humidity().getEvent(&amp;event);
   if(isnan(event.relative_humidity)){
      hum = 0;
   }else{
      hum = (double)event.relative_humidity;
   }
   delay(1000);
   text = (String)temp; 
   text += &quot;-&quot;;
   text += (String)hum;
   Serial.println(text);
   server.send(200, &quot;text/plain&quot;, text);
});</code></pre></pre>
<p>This part is from the <em>DHT_Unified_Sensor</em> sketch earlier. Here, we acquire the temperature and humidity values from the DHT11 and then concatenate these values using ‘-‘ as a delimiter. The client gets this string for every request of the server page <em>data.</em></p>
<p>Now if we go back to the ajax function:</p>
<pre class="lang:arduino decode:true"><pre><code class="language-cpp">success: function(data){
  var s = data.split(&#039;-&#039;);
  $(&#039;#temp&#039;).html(s[0]);
  $(&#039;#hum&#039;).html(s[1]);
}</code></pre></pre>
<p>This catches the sensor values, split it according to the delimiter (the character ‘-’) and then place them inside the <em>divs</em> with id’s <em>temp</em> and <em>hum</em>.</p>
<p>Finally, we pass the <em>page</em> string (the one where the HTML of the web page is) for every request of the root of the server, and then start the server:</p>
<pre class="lang:arduino decode:true "><pre><code class="language-cpp">server.on(&quot;/&quot;, []() {
   server.send(200, &quot;text/html&quot;, page);
});

server.begin();
Serial.println(&quot;HTTP server started&quot;);</code></pre></pre>
<p>The <em>loop()</em> function is just a call to handle the client:</p>
<pre class="lang:arduino decode:true "><pre><code class="language-cpp">void loop(void) {
   server.handleClient();
}</code></pre></pre>
<p>Of course, we need the ESP32 to work continuously so putting this inside the loop is important.</p>
<p>The page looks very simple as it doesn’t contain any styling whatsoever. But if you are familiar with web design, you can surely improve its appearance.</p>
<h3><strong>Closing</strong></h3>
<p>That’s it! Now we have a simple ESP32 web server. If there’s something in this tutorial that you can’t understand, kindly drop it as a comment below.</p>
<p>I’ll be exploring the Bluetooth functions of the ESP32 on the next part of this series.</p><p>The post <a href="https://www.teachmemicro.com/sensor-display-on-esp32-web-server/">Sensor Display on ESP32 Web Server</a> first appeared on <a href="https://www.teachmemicro.com">Microcontroller Tutorials</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.teachmemicro.com/sensor-display-on-esp32-web-server/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>How to Use PIR Sensor with NodeMCU ESP8266</title>
		<link>https://www.teachmemicro.com/pir-sensor-nodemcu-esp8266/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pir-sensor-nodemcu-esp8266</link>
					<comments>https://www.teachmemicro.com/pir-sensor-nodemcu-esp8266/#comments</comments>
		
		<dc:creator><![CDATA[Roland Pelayo]]></dc:creator>
		<pubDate>Sat, 04 May 2019 12:36:23 +0000</pubDate>
				<category><![CDATA[ESP8266 Tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[motion sensor]]></category>
		<category><![CDATA[web server]]></category>
		<guid isPermaLink="false">https://www.teachmemicro.com/?p=3294</guid>

					<description><![CDATA[<p>A Passive Infrared (PIR) sensor is a popular sensor for detecting the presence of a person. This is a type of proximity sensor although you may also call it a motion sensor. This tutorial aims to guide you in using a PIR sensor with your NodeMCU ESP8266 WiFi board. Introduction The human body emits infrared &#8230;</p>
<p>The post <a href="https://www.teachmemicro.com/pir-sensor-nodemcu-esp8266/">How to Use PIR Sensor with NodeMCU ESP8266</a> first appeared on <a href="https://www.teachmemicro.com">Microcontroller Tutorials</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>A Passive Infrared (PIR) sensor is a popular sensor for detecting the presence of a person. This is a type of <a href="https://en.wikipedia.org/wiki/Proximity_sensor">proximity sensor</a> although you may also call it a motion sensor. This tutorial aims to guide you in using a PIR sensor with your NodeMCU <a href="https://www.win-source.net/products/detail/espressif/esp8266ex.html">ESP8266</a> WiFi board.</p>
<p><span id="more-3294"></span></p>
<h3><strong>Introduction</strong></h3>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-featured.jpg"><img loading="lazy" decoding="async" class="wp-image-3297 aligncenter" src="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-featured.jpg" alt="NodeMCU PIR Sensor" width="649" height="487" srcset="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-featured.jpg 800w, https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-featured-300x225.jpg 300w, https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-featured-768x576.jpg 768w, https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-featured-320x240.jpg 320w" sizes="auto, (max-width: 649px) 100vw, 649px" /></a></p>
<p>The human body emits infrared signals by virtue of its temperature. When a person is near a PIR sensor, the infrared detector triggers and the voltage on the output pin goes low.</p>
<p>To enhance the reception of infrared signals, PIR sensors often come with a Fresnel dome. Most of the time, the dome is removable as shown below:</p>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-without-dome.jpg"><img loading="lazy" decoding="async" class="wp-image-3298 aligncenter" src="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-without-dome.jpg" alt="NodeMCU PIR Sensor without dome" width="649" height="487" srcset="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-without-dome.jpg 800w, https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-without-dome-300x225.jpg 300w, https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-without-dome-768x576.jpg 768w, https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-without-dome-320x240.jpg 320w" sizes="auto, (max-width: 649px) 100vw, 649px" /></a></p>
<p>Removing the dome reveals the infrared receiver. The sensor will still work but will only detect persons directly in front of the receiver.</p>
<h3><strong>How to Connect to a PIR Sensor</strong></h3>
<p>PIR sensor modules commonly have three output pins: VCC, OUT and GND.</p>
<p><em>For DFRobot's PIR Sensor Board:</em></p>
<p><img decoding="async" class="aligncenter" title="Infrared_Sensor_new1.jpg" src="https://raw.githubusercontent.com/DFRobot/DFRobotMediaWikiImage/master/Image/Infrared_Sensor_new1.jpg" alt="Infrared_Sensor_new1.jpg" /></p>
<blockquote><p>1 - OUT<br />
2 - VCC<br />
3 - GND<br />
4 - Trigger Select<br />
5 - Sensitivity Adjust</p></blockquote>
<p><em>For HC-SR501 Board:</em></p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1702 aligncenter" src="https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=640%2C640&amp;ssl=1" sizes="auto, (max-width: 640px) 100vw, 640px" srcset="https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?w=800&amp;ssl=1 800w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=150%2C150&amp;ssl=1 150w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=300%2C300&amp;ssl=1 300w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=768%2C768&amp;ssl=1 768w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=65%2C65&amp;ssl=1 65w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=24%2C24&amp;ssl=1 24w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=36%2C36&amp;ssl=1 36w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=48%2C48&amp;ssl=1 48w, https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?resize=120%2C120&amp;ssl=1 120w" alt="HC-SR501 PIR motion sensor underside" width="585" height="585" data-attachment-id="1702" data-permalink="https://www.teachmemicro.com/pir-motion-sensor/pir-motion-sensor-underside-annotated/" data-orig-file="https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?fit=800%2C800&amp;ssl=1" data-orig-size="800,800" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;1&quot;}" data-image-title="PIR-Motion-Sensor-underside-annotated" data-image-description="" data-medium-file="https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?fit=300%2C300&amp;ssl=1" data-large-file="https://i2.wp.com/www.teachmemicro.com/wp-content/uploads/2018/03/PIR-Motion-Sensor-underside-annotated.jpg?fit=640%2C640&amp;ssl=1" /></p>
<p>The VCC pin connects to the positive source voltage of any microcontroller board. PIR sensor modules will work with both 3.3V and 5V levels. Thus, it is safe to connect the VCC pin of the PIR sensor to any of the 3.3V of the NodeMCU. The GND pin, of course, connects to the GND pin of the NodeMCU.</p>
<p>The OUT pin connects to any digital pin of the NodeMCU. This pin will go low when the sensor triggers.</p>
<p>Remember that the numbers on the board is different from the numbers used in programming. The <a href="https://www.teachmemicro.com/nodemcu-pinout/">NodeMCU pinout guide</a> will help you with the correct pin numbers.</p>
<p>Most modules contain a knob for adjusting sensitivity and a jumper for trigger selection. These are covered in a separate <a href="https://www.teachmemicro.com/pir-motion-sensor/">PIR sensor article</a>.</p>
<p>For the rest of this tutorial, we will follow this wiring diagram:</p>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-1.jpg"><img loading="lazy" decoding="async" class="size-full wp-image-3296 aligncenter" src="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-1.jpg" alt="NodeMCU PIR Sensor" width="558" height="522" srcset="https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-1.jpg 558w, https://www.teachmemicro.com/wp-content/uploads/2019/05/nodemcu-pir-sensor-1-300x281.jpg 300w" sizes="auto, (max-width: 558px) 100vw, 558px" /></a></p>
<h3><strong>Programming the NodeMCU with PIR Sensor</strong></h3>
<p>Before continuing, make sure to read <a href="https://www.teachmemicro.com/intro-nodemcu-arduino/">how to use an Arduino IDE to program the NodeMCU</a>.</p>
<p>We’ll start with a basic sketch that will give an output on the serial monitor every time the PIR sensor triggers.</p>
<pre class="lang:arduino decode:true"><pre><code class="language-cpp">const int PIRSensorOutPin = 2;    //PIR Sensor OUT Pin
 void setup() {
    Serial.begin(9600);
    pinMode(PIRSensorOutPin, INPUT);
 }
 void loop()
 {
    if (digitalRead(PIRSensorOutPin) == LOW)
    {
       Serial.println(&quot;Person detected!&quot;);    //Print to serial monitor
    }
    else {;}
 }</code></pre></pre>
<p>As you can see, the sketch is straightforward. We use the same function we used to read a button:</p>
<pre class="lang:arduino decode:true "><pre><code class="language-cpp">digitalRead(PIRSensorOutPin)</code></pre></pre>
<p>We then insert the function above in an if-else statement and execute a print to serial if the if-else returns a zero.</p>
<pre class="lang:arduino decode:true "><pre><code class="language-cpp">if (digitalRead(PIRSensorOutPin) == LOW) 
 { 
    Serial.println(&quot;Person detected!&quot;); //Print to serial monitor 
 }else{;}</code></pre></pre>
<p>The full sketch above is useful for testing if your PIR sensor is working.</p>
<p>However, since we are using a NodeMCU instead of an Arduino in this tutorial, it is best to use the board as it is meant to.</p>
<p>Instead of giving an output to the serial monitor every time a person is detected, we will give an output to a web page hosted by the NodeMCU.</p>
<p>For this example project, we will modify the example sketch that comes with <a href="https://www.teachmemicro.com/nodemcu-ajax-dynamic-sensor-data-web-page/">this tutorial</a>. AJAX is helpful here so that the page will update automatically when the PIR sensor triggers.</p>
<p>This is now the modified sketch:</p>
<pre class="lang:arduino decode:true "><pre><code class="language-cpp">#include &lt;ESP8266WiFi.h&gt;
#include &lt;WiFiClient.h&gt;
#include &lt;ESP8266WebServer.h&gt;
 
// Replace with your network credentials
const char* ssid = &quot;&lt;Your-WiFi-SSID&gt;&quot;;
const char* password = &quot;&lt;Your-WiFi-Password&gt;&quot;;
ESP8266WebServer server(80);   //instantiate server at port 80 (http port)
 
String page = &quot;&quot;;
String text = &quot;&quot;;

int PIRSensorOutputPin = 2;
bool isTriggered = false;
 
void setup(void){
 pinMode(PIRSensorOutputPin, INPUT);
 delay(1000);
 Serial.begin(115200);
 WiFi.begin(ssid, password); //begin WiFi connection
 Serial.println(&quot;&quot;);
 
 // Wait for connection
 while (WiFi.status() != WL_CONNECTED) {
 delay(500);
 Serial.print(&quot;.&quot;);
}
 
 Serial.println(&quot;&quot;);
 Serial.print(&quot;Connected to &quot;);
 Serial.println(ssid);
 Serial.print(&quot;IP address: &quot;);
 Serial.println(WiFi.localIP());
 server.on(&quot;/data.txt&quot;, [](){
   if(isTriggered){
     text = &quot;Person Detected!&quot;;
   }else{
     text = &quot;&quot;;
   }
   server.send(200, &quot;text/html&quot;, text);
 });
 server.on(&quot;/&quot;, [](){
   page = &quot;&lt;h1&gt;PIR Sensor to NodeMCU/h1&gt;&lt;h1&gt;Data:&lt;/h1&gt; &lt;h1 id=\&quot;data\&quot;&gt;&quot;&quot;&lt;/h1&gt;\r\n&quot;;
   page += &quot;&lt;script&gt;\r\n&quot;;
   page += &quot;var x = setInterval(function() {loadData(\&quot;data.txt\&quot;,updateData)}, 1000);\r\n&quot;;
   page += &quot;function loadData(url, callback){\r\n&quot;;
   page += &quot;var xhttp = new XMLHttpRequest();\r\n&quot;;
   page += &quot;xhttp.onreadystatechange = function(){\r\n&quot;;
   page += &quot; if(this.readyState == 4 &amp;&amp; this.status == 200){\r\n&quot;;
   page += &quot; callback.apply(xhttp);\r\n&quot;;
   page += &quot; }\r\n&quot;;
   page += &quot;};\r\n&quot;;
   page += &quot;xhttp.open(\&quot;GET\&quot;, url, true);\r\n&quot;;
   page += &quot;xhttp.send();\r\n&quot;;
   page += &quot;}\r\n&quot;;
   page += &quot;function updateData(){\r\n&quot;;
   page += &quot; document.getElementById(\&quot;data\&quot;).innerHTML = this.responseText;\r\n&quot;;
   page += &quot;}\r\n&quot;;
   page += &quot;&lt;/script&gt;\r\n&quot;;
   server.send(200, &quot;text/html&quot;, page);
});
 
 server.begin();
 Serial.println(&quot;Web server started!&quot;);
}
 
void loop(void){
 if(digitalRead(PIRSensorOutputPin) == 0){
     isTriggered = true;
 }else{
     isTriggered = false;
 }
 server.handleClient();
}</code></pre></pre>
<p>Upload this sketch to the NodeMCU, providing your own WiFi SSID and password on lines 6 and 7. When successful, the serial monitor will give you an IP address. Use a browser and visit that IP address. The page should display "Person detected!" when the sensor is triggered.</p>
<p>Was the tutorial helpful? Kindly comment below for any questions or suggestions you have for this tutorial.</p><p>The post <a href="https://www.teachmemicro.com/pir-sensor-nodemcu-esp8266/">How to Use PIR Sensor with NodeMCU ESP8266</a> first appeared on <a href="https://www.teachmemicro.com">Microcontroller Tutorials</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.teachmemicro.com/pir-sensor-nodemcu-esp8266/feed/</wfw:commentRss>
			<slash:comments>3</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-06-16 20:51:42 by W3 Total Cache
-->