<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fernaldi Fauzie on Medium]]></title>
        <description><![CDATA[Stories by Fernaldi Fauzie on Medium]]></description>
        <link>https://medium.com/@fernaldifz?source=rss-908796d811ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*krMA8DpkI66TpGUKz7oRxg.png</url>
            <title>Stories by Fernaldi Fauzie on Medium</title>
            <link>https://medium.com/@fernaldifz?source=rss-908796d811ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 01:00:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fernaldifz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Embedded System Project 11: ESP32 + Visualizing Sensor Readings from Anywhere in the World]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-11-esp32-visualizing-sensor-readings-from-anywhere-in-the-world-3e354a9b1f55?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e354a9b1f55</guid>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[bmp280]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Fri, 16 Apr 2021 15:29:28 GMT</pubDate>
            <atom:updated>2021-04-19T03:22:10.443Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi guys! In this project, you will learn to create a web page that displays sensor readings in a plot that you can access from anywhere in the world. In this case, you will learn to build an ESP32 client that makes a request to a PHP script to publish sensor readings (In my case is BMP280 sensor readings) in a MySQL database. Although I will use ESP32 and BMP280, you may use a different sensor or multiple boards.</p><p>For this embedded system project, I will use this <a href="https://randomnerdtutorials.com/visualize-esp32-esp8266-sensor-readings-from-anywhere/">randomnerdtutorials</a> as references. Notable differences are I will use BMP280 instead of BME280 and get approximate altitude instead of humidity!</p><h4>Technologies needed</h4><ul><li>ESP32 programmed with Arduino IDE software</li><li>Hosting server and domain name</li><li>PHP script to insert data into MySQL database and display it on a web page</li><li>MySQL database to store readings</li><li>PHP script to plot data from database in charts</li></ul><p>Ah, right! Before we continue, you may want to check my <a href="https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b">previous project</a> which is about the mini weather station with a database! Because it could be said that this final project is the continuation of the previous project!</p><h3>Let’s do this!</h3><p><strong>First, you need to host your PHP application and MySQL database.</strong> Here’s a pretty good high-level overview for this project! I used this <a href="https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2019/08/ESP32-MySQL-Charts-Project-Overview.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1">link</a> as a reference with some modifications!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*i8e8AePaQtm_jlTFcixBcQ.png" /><figcaption>Overview (references to <a href="https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2019/08/ESP32-MySQL-Charts-Project-Overview.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1">randomnerdtutorials</a>)</figcaption></figure><p>If you still don’t have your own domain name and hosting account that allows you to store sensor readings from the ESP32, I recommend checking my <a href="https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b">previous project</a>! In my case, I used <a href="https://www.000webhost.com/">000webhost</a>.</p><p>Next, you need to prepare your MySQL database and make PHP script HTTP POST to insert data in the MySQL database. But, because this is already explained in the previous project, to make this project as brief as possible, I will skip these parts.</p><p>After that, you need to create a PHP script to visualize database content in the chart. To do this, create another PHP file in the <strong>/public_html</strong> directory that will plot the database content in a chart on a web page. Personally, I named it “ESP_CHART”</p><p>You may copy the following snippet:</p><pre>&lt;!--<br>  This code references to: Rui Santos<br>  Complete project details at https://RandomNerdTutorials.com<br>  <br>  Permission is hereby granted, free of charge, to any person obtaining a copy<br>  of this software and associated documentation files.<br>  <br>  The above copyright notice and this permission notice shall be included in all<br>  copies or substantial portions of the Software.<br><br>--&gt;<br>&lt;?php<br><br>$servername = &quot;localhost&quot;;<br><br>// REPLACE with your Database name<br>$dbname = &quot;REPLACE_WITH_YOUR_DATABASE_NAME&quot;;<br>// REPLACE with Database user<br>$username = &quot;REPLACE_WITH_YOUR_USERNAME&quot;;<br>// REPLACE with Database user password<br>$password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;<br><br>// Create connection<br>$conn = new mysqli($servername, $username, $password, $dbname);<br>// Check connection<br>if ($conn-&gt;connect_error) {<br>    die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);<br>}</pre><pre>$sql = &quot;SELECT id, value1, value2, value3, reading_time FROM SensorData order by reading_time desc limit 40&quot;;</pre><pre>$result = $conn-&gt;query($sql) or die($conn-&gt;error);</pre><pre>while ($data = $result-&gt;fetch_assoc()){<br>    $sensor_data[] = $data;<br>}</pre><pre>$readings_time = array_column($sensor_data, &#39;reading_time&#39;);</pre><pre>$i = 0;<br>foreach ($readings_time as $reading){<br>    $readings_time[$i] = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;$reading + 7 hours&quot;)); //convert timezone to +7<br>    $i += 1;<br>}</pre><pre>$value1 = json_encode(array_reverse(array_column($sensor_data, &#39;value1&#39;)), JSON_NUMERIC_CHECK);<br>$value2 = json_encode(array_reverse(array_column($sensor_data, &#39;value2&#39;)), JSON_NUMERIC_CHECK);<br>$value3 = json_encode(array_reverse(array_column($sensor_data, &#39;value3&#39;)), JSON_NUMERIC_CHECK);<br>$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);</pre><pre>/*echo $value1;<br>echo $value2;<br>echo $value3;<br>echo $reading_time;*/</pre><pre>$result-&gt;free();<br>$conn-&gt;close();<br>?&gt;</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>  &lt;script src=&quot;<a href="https://code.highcharts.com/highcharts.js">https://code.highcharts.com/highcharts.js</a>&quot;&gt;&lt;/script&gt;<br>  &lt;style&gt;<br>    body {<br>      min-width: 310px;<br>     max-width: 1280px;<br>     height: 500px;<br>      margin: 0 auto;<br>    }<br>    h2 {<br>      font-family: Arial;<br>      font-size: 2.5rem;<br>      text-align: center;<br>    }<br>  &lt;/style&gt;<br>  &lt;body&gt;<br>    &lt;h2&gt;ESP Weather Station&lt;/h2&gt;<br>    &lt;div id=&quot;chart-temperature&quot; class=&quot;container&quot;&gt;&lt;/div&gt;<br>    &lt;div id=&quot;chart-approximate-altitude&quot; class=&quot;container&quot;&gt;&lt;/div&gt;<br>    &lt;div id=&quot;chart-pressure&quot; class=&quot;container&quot;&gt;&lt;/div&gt;<br>&lt;script&gt;</pre><pre>var value1 = &lt;?php echo $value1; ?&gt;;<br>var value2 = &lt;?php echo $value2; ?&gt;;<br>var value3 = &lt;?php echo $value3; ?&gt;;<br>var reading_time = &lt;?php echo $reading_time; ?&gt;;</pre><pre>var chartT = new Highcharts.Chart({<br>  chart:{ renderTo : &#39;chart-temperature&#39; },<br>  title: { text: &#39;BMP280 Temperature&#39; },<br>  series: [{<br>    showInLegend: false,<br>    data: value1<br>  }],<br>  plotOptions: {<br>    line: { animation: false,<br>      dataLabels: { enabled: true }<br>    },<br>    series: { color: &#39;#059e8a&#39; }<br>  },<br>  xAxis: { <br>    type: &#39;datetime&#39;,<br>    categories: reading_time<br>  },<br>  yAxis: {<br>    title: { text: &#39;Temperature (Celsius)&#39; }<br>    //title: { text: &#39;Temperature (Fahrenheit)&#39; }<br>  },<br>  credits: { enabled: false }<br>});</pre><pre>var chartH = new Highcharts.Chart({<br>  chart:{ renderTo:&#39;chart-pressure&#39; },<br>  title: { text: &#39;BMP280 Pressure&#39; },<br>  series: [{<br>    showInLegend: false,<br>    data: value2<br>  }],<br>  plotOptions: {<br>    line: { animation: false,<br>      dataLabels: { enabled: true }<br>    }<br>  },<br>  xAxis: {<br>    type: &#39;datetime&#39;,<br>    //dateTimeLabelFormats: { second: &#39;%H:%M:%S&#39; },<br>    categories: reading_time<br>  },<br>  yAxis: {<br>    title: { text: &#39;Pressure (Pa)&#39; }<br>  },<br>  credits: { enabled: false }<br>});</pre><pre>var chartP = new Highcharts.Chart({<br>  chart:{ renderTo:&#39;chart-approximate-altitude&#39; },<br>  title: { text: &#39;BMP280 Approximate Altitude&#39; },<br>  series: [{<br>    showInLegend: false,<br>    data: value3<br>  }],<br>  plotOptions: {<br>    line: { animation: false,<br>      dataLabels: { enabled: true }<br>    },<br>    series: { color: &#39;#18009c&#39; }<br>  },<br>  xAxis: {<br>    type: &#39;datetime&#39;,<br>    categories: reading_time<br>  },<br>  yAxis: {<br>    title: { text: &#39;Approximate Altitude (m)&#39; }<br>  },<br>  credits: { enabled: false }<br>});</pre><pre>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>As usual, don’t forget to change this part just like the previous project!</p><pre>// Your Database name <br>$dbname = &quot;example_esp_data&quot;; </pre><pre>// Your Database user <br>$username = &quot;example_esp_board&quot;; </pre><pre>// Your Database user password <br>$password = &quot;YOUR_USER_PASSWORD&quot;;</pre><p>If you don’t really follow my <a href="https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b">previous project</a>, you also need this PHP file in the <strong>/public_html</strong> directory. Personally, I named it “POST_DATA”.</p><pre>&lt;?php</pre><pre>/*<br>  Rui Santos<br>  Complete project details at <a href="https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/">https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/</a><br>  <br>  Permission is hereby granted, free of charge, to any person obtaining a copy<br>  of this software and associated documentation files.<br>  <br>  The above copyright notice and this permission notice shall be included in all<br>  copies or substantial portions of the Software.<br>*/</pre><pre>$servername = &quot;localhost&quot;;</pre><pre>// Your Database name <br>$dbname = &quot;example_esp_data&quot;;</pre><pre>// Your Database user <br>$username = &quot;example_esp_board&quot;;</pre><pre>// Your Database user password <br>$password = &quot;YOUR_USER_PASSWORD&quot;;</pre><pre>// Keep this API Key value to be compatible with the ESP32 code provided in the project page. <br>// If you change this value, the ESP32 sketch needs to match<br>$api_key_value = &quot;tPmAT5Ab3j7F9&quot;;</pre><pre>$api_key= $sensor = $location = $value1 = $value2 = $value3 = &quot;&quot;;</pre><pre>if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) {<br>    $api_key = test_input($_POST[&quot;api_key&quot;]);<br>    if($api_key == $api_key_value) {<br>        $sensor = test_input($_POST[&quot;sensor&quot;]);<br>        $location = test_input($_POST[&quot;location&quot;]);<br>        $value1 = test_input($_POST[&quot;value1&quot;]);<br>        $value2 = test_input($_POST[&quot;value2&quot;]);<br>        $value3 = test_input($_POST[&quot;value3&quot;]);<br>        <br>        // Create connection<br>        $conn = new mysqli($servername, $username, $password, $dbname);<br>        // Check connection<br>        if ($conn-&gt;connect_error) {<br>            die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);<br>        } <br>        <br>        $sql = &quot;INSERT INTO SensorData (sensor, location, value1, value2, value3)<br>        VALUES (&#39;&quot; . $sensor . &quot;&#39;, &#39;&quot; . $location . &quot;&#39;, &#39;&quot; . $value1 . &quot;&#39;, &#39;&quot; . $value2 . &quot;&#39;, &#39;&quot; . $value3 . &quot;&#39;)&quot;;<br>        <br>        if ($conn-&gt;query($sql) === TRUE) {<br>            echo &quot;New record created successfully&quot;;<br>        } <br>        else {<br>            echo &quot;Error: &quot; . $sql . &quot;&lt;br&gt;&quot; . $conn-&gt;error;<br>        }<br>    <br>        $conn-&gt;close();<br>    }<br>    else {<br>        echo &quot;Wrong API Key provided.&quot;;<br>    }</pre><pre>}<br>else {<br>    echo &quot;No data posted with HTTP POST.&quot;;<br>}</pre><pre>function test_input($data) {<br>    $data = trim($data);<br>    $data = stripslashes($data);<br>    $data = htmlspecialchars($data);<br>    return $data;<br>}</pre><p>In the end, this will be how the <strong>/public_html</strong> directory looked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVG2b_27L-UYbrpbhvXLtA.png" /><figcaption>/public_html</figcaption></figure><p>Don’t need to worry with DATA.php! As we don’t need it for this project (that PHP file is needed for the previous project),</p><p>Also, I would like to point out to be careful in naming! For example, in a previous project, I named the table “Sensor_Data”</p><pre>$sql = &quot;SELECT id, value1, value2, value3, reading_time FROM Sensor_Data order by reading_time desc limit 40&quot;;</pre><p>Meanwhile, randomnerdtutorials used “Sensor” instead of “Sensor_Data”!</p><pre>$sql = &quot;SELECT id, value1, value2, value3, reading_time FROM Sensor order by reading_time desc limit 40&quot;;</pre><p>In my case, I can visit this <a href="https://choleraic-authoriza.000webhostapp.com/ESP_CHART.php">link</a> to view the chart! Why? Well, because I already have sensor readings from the <a href="https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b">previous project</a>! So, this time I can instantly view it! But, don’t worry! I will explain it again below, so feel free to scroll down! (Yours should be http://example.com/ESP-CHART.php)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRtzS-IaRWkbV3IztxBrnA.png" /><figcaption>BMP280 Temperature (Celcius)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gwdab5YSHjGY_vPx-ISFAw.png" /><figcaption>BMP280 Approximate Altitude (m)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RjIzdY_oMKTQZQhikIyYQ.png" /><figcaption>BMP280 Pressure (Pa)</figcaption></figure><h4>Components and Parts Required</h4><ul><li>ESP32 board</li><li>BMP280 sensor</li><li>Jumper wires (I’m using male to male jumper wires)</li><li>Breadboard</li></ul><h4>Schematics Diagram</h4><p>Pretty much the same as the <a href="https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b">previous project</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*5Gna_ylJlkW8btjUczRcpw.png" /><figcaption>My Schematic Diagram</figcaption></figure><p>Some important notes:</p><ul><li>ESP32 3v3 connected to BMP280 VCC</li><li>ESP32 GND connected to BMP280 GND</li><li>GPIO 21 connected to BMP280 SCL</li><li>GPIO22 connected to BMP280 SDA</li></ul><p>As I explained before in the previous project, although in the schematics diagram I used BMP180, BMP280 can also work as long you pay attention to the pins! (I can’t found the BMP280 sensor in fritzing, that’s why I used BMP180 instead of BMP280)</p><h4>ESP32 Code</h4><p>Still pretty much the same as the <a href="https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b">previous project</a>! You may copy the following code to upload it with Arduino IDE to your ESP32.</p><pre>/*<br>  This code references to: Rui Santos<br>  Complete project details at <a href="https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/">https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/</a><br>  <br>  Permission is hereby granted, free of charge, to any person obtaining a copy<br>  of this software and associated documentation files.<br>  <br>  The above copyright notice and this permission notice shall be included in all<br>  copies or substantial portions of the Software.</pre><pre>*/</pre><pre>#include &lt;WiFi.h&gt;<br>#include &lt;HTTPClient.h&gt;</pre><pre>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BMP280.h&gt;</pre><pre>// Replace with your network credentials<br>const char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;</pre><pre>// REPLACE with your Domain name and URL path or IP address with path<br>const char* serverName = &quot;DOMAIN_NAME&quot;;</pre><pre>// Keep this API Key value to be compatible with the PHP code provided in the project page. <br>// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key <br>String apiKeyValue = &quot;tPmAT5Ab3j7F9&quot;;</pre><pre>String sensorName = &quot;BMP280&quot;;<br>String sensorLocation = &quot;Home&quot;;</pre><pre>#define SEALEVELPRESSURE_HPA (1013.25)</pre><pre>Adafruit_BMP280 bmp; // I2C<br>//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI<br>//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);</pre><pre>void setup() {<br>  Serial.begin(115200);<br>  <br>  WiFi.begin(ssid, password);<br>  Serial.println(&quot;Connecting&quot;);<br>  while(WiFi.status() != WL_CONNECTED) { <br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  Serial.println(&quot;&quot;);<br>  Serial.print(&quot;Connected to WiFi network with IP Address: &quot;);<br>  Serial.println(WiFi.localIP());</pre><pre>// (you can also pass in a Wire library object like &amp;Wire2)<br>  bool status = bmp.begin(0x76);<br>  if (!status) {<br>    Serial.println(&quot;Could not find a valid BMP280 sensor, check wiring or change I2C address!&quot;);<br>    while (1);<br>  }<br>}</pre><pre>void loop() {<br>  //Check WiFi connection status<br>  if(WiFi.status()== WL_CONNECTED){<br>    HTTPClient http;<br>    <br>    // Your Domain name with URL path or IP address with path<br>    http.begin(serverName);<br>    <br>    // Specify content-type header<br>    http.addHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);<br>    <br>    // Prepare your HTTP POST request data<br>    String httpRequestData = &quot;api_key=&quot; + apiKeyValue + &quot;&amp;sensor=&quot; + sensorName<br>                          + &quot;&amp;location=&quot; + sensorLocation + &quot;&amp;value1=&quot; + String(bmp.readTemperature())<br>                          + &quot;&amp;value2=&quot; + String(bmp.readPressure()) + &quot;&amp;value3=&quot; + String((bmp.readAltitude(SEALEVELPRESSURE_HPA))) + &quot;&quot;;<br>    Serial.print(&quot;httpRequestData: &quot;);<br>    Serial.println(httpRequestData);<br>    <br>    // You can comment the httpRequestData variable above<br>    // then, use the httpRequestData variable below (for testing purposes without the BMP280 sensor)<br>    //String httpRequestData = &quot;api_key=tPmAT5Ab3j7F9&amp;sensor=BMP280&amp;location=Office&amp;value1=24.75&amp;value2=49.54&amp;value3=1005.14&quot;;</pre><pre>// Send HTTP POST request<br>    int httpResponseCode = http.POST(httpRequestData);<br>     <br>    // If you need an HTTP request with a content type: text/plain<br>    //http.addHeader(&quot;Content-Type&quot;, &quot;text/plain&quot;);<br>    //int httpResponseCode = http.POST(&quot;Hello, World!&quot;);<br>    <br>    // If you need an HTTP request with a content type: application/json, use the following:<br>    //http.addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    //int httpResponseCode = http.POST(&quot;{\&quot;value1\&quot;:\&quot;19\&quot;,\&quot;value2\&quot;:\&quot;67\&quot;,\&quot;value3\&quot;:\&quot;78\&quot;}&quot;);<br>        <br>    if (httpResponseCode&gt;0) {<br>      Serial.print(&quot;HTTP Response code: &quot;);<br>      Serial.println(httpResponseCode);<br>    }<br>    else {<br>      Serial.print(&quot;Error code: &quot;);<br>      Serial.println(httpResponseCode);<br>    }<br>    // Free resources<br>    http.end();<br>  }<br>  else {<br>    Serial.println(&quot;WiFi Disconnected&quot;);<br>  }<br>  //Send an HTTP POST request every 30 seconds (30.000 mili seconds)<br>  delay(30000);  <br>}</pre><p>Don’t forget to change the SSID, password, and domain name before uploading!</p><pre>// Replace with your network credentials<br>const char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;</pre><pre>// REPLACE with your Domain name and URL path or IP address with path<br>const char* serverName = &quot;DOMAIN_NAME&quot;;</pre><p>If your code succeeds, you should be able to see this in your serial monitor in Arduino IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7WistMIZKTBw2FLhyLsrQ.png" /><figcaption>Serial Monitor in Arduino IDE</figcaption></figure><h4>Result?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRdLenwYhJIVcwFidhYL3g.png" /><figcaption>BMP280 Temperature (Celcius)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Te3uY6Em9ur0XFN6lWHIg.png" /><figcaption>BMP280 Approximate Altitude (m)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0IJG3uMPaVgVt3QLb6f3Q.png" /><figcaption>BMP280 Pressure (Pa)</figcaption></figure><p>Additional information, in the Database Manager &gt; Manage &gt; PhpMyAdmin, you may find something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezrgHwwAQsXFZIS9Ixxmzg.png" /></figure><p>You may manage the data stored in your SensorData table. You can edit it, copy it, delete it, etc.</p><h4>BONUS</h4><p>Personally, I want to change the measurement of pressure, so that instead of in Pa, I want to measure it in hPa. So, I need to make a change in ESP_chart.php, like this:</p><pre>var chartH = new Highcharts.Chart({<br>  chart:{ renderTo:&#39;chart-pressure&#39; },<br>  title: { text: &#39;BMP280 Pressure&#39; },<br>  series: [{<br>    showInLegend: false,<br>    data: value2<br>  }],<br>  plotOptions: {<br>    line: { animation: false,<br>      dataLabels: { enabled: true }<br>    }<br>  },<br>  xAxis: {<br>    type: &#39;datetime&#39;,<br>    //dateTimeLabelFormats: { second: &#39;%H:%M:%S&#39; },<br>    categories: reading_time<br>  },<br>  yAxis: {<br>    title: { text: &#39;Pressure (hPa)&#39; }<br>  },<br>  credits: { enabled: false }<br>});</pre><p>Also, I need to make a change in the ESP32 code, like this:</p><pre>// Prepare your HTTP POST request data<br>    String httpRequestData = &quot;api_key=&quot; + apiKeyValue + &quot;&amp;sensor=&quot; + sensorName<br>                          + &quot;&amp;location=&quot; + sensorLocation + &quot;&amp;value1=&quot; + String(bmp.readTemperature())<br>                          + &quot;&amp;value2=&quot; + String(bmp.readPressure()/100.0F) + &quot;&amp;value3=&quot; + String((bmp.readAltitude(SEALEVELPRESSURE_HPA))) + &quot;&quot;;</pre><p>Next, I need to delete all previous data in the SensorData table.</p><h4>Result?</h4><p>Fortunately, it seems that I did it! The result that can be seen in this <a href="https://choleraic-authoriza.000webhostapp.com/ESP_CHART.php">link</a> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwR6AclAyy1LO9KFHrP3SQ.png" /><figcaption>BMP280 Temperature (Celcius)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-eqzSQ53r_i5BrcpjW3kQ.png" /><figcaption>BMP280 Approximate Altitude (m)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn51NgPz9M0vxhJlBYRb2w.png" /><figcaption>BMP280 Pressure (hPa)</figcaption></figure><h4>Code Explanation</h4><p>Pretty much the same as the <a href="https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b">previous project</a>, but instead of displaying it in the table, this time we display it in the graph (ESP_CHART.php instead of DATA.php). For further understanding, you may want to check my previous project.</p><p>I would like to point out again that in the loop(), you make the HTTP POST request every 30 seconds (because we put a delay(30000) in the end) with the latest BMP280 readings:</p><pre>// Your Domain name with URL path or IP address with path<br>http.begin(serverName);<br>    <br>// Specify content-type header<br>http.addHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);<br>       <br>// Prepare your HTTP POST request data<br>String httpRequestData = &quot;api_key=&quot; + apiKeyValue + &quot;&amp;sensor=&quot; + sensorName<br>                          + &quot;&amp;location=&quot; + sensorLocation + &quot;&amp;value1=&quot; + String(bmp.readTemperature())<br>                          + &quot;&amp;value2=&quot; + String(bmp.readPressure()/100.0F) + &quot;&amp;value3=&quot; + String((bmp.readAltitude(SEALEVELPRESSURE_HPA))) + &quot;&quot;;</pre><pre>// Send HTTP POST request<br>int httpResponseCode = http.POST(httpRequestData);</pre><p>If you want, you may comment on the httpRequestData variable above that concatenates all the BMP280 readings and use the httpRequestData variable below to test your code.</p><pre>// You can comment the httpRequestData variable above<br>// then, use the httpRequestData variable below (for testing purposes without the BMP280 sensor)<br>//String httpRequestData = &quot;api_key=tPmAT5Ab3j7F9&amp;sensor=BMP280&amp;location=Office&amp;value1=24.75&amp;value2=49.54&amp;value3=1005.14&quot;;</pre><h4>Conclusion</h4><p>Finally, we are done. In this project, you have learned how to publish sensor data into a database in your own server domain that you can access from anywhere in the world as the graph. Personally, I used <a href="https://www.000webhost.com/">000webhost</a> because it’s free. If you are interested in this project, after understanding this project, you should be able to change the web page appearance, publish different sensor readings, publish from multiple ESP boards, etc.</p><p>To be honest, this is my last embedded system project that will be published in Medium. Actually, I still have 1 more project which will be my final project, but I don’t think I will publish it in Medium because I will do it in a team of 3 persons and we will make it in a document, not an article. I hope that all of my embedded system projects can bring you guys benefits! Keep learning and don’t forget to have fun!</p><blockquote>See you later!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e354a9b1f55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded System Project 10: Mini Weather Station + Database]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-10-mini-weather-station-database-155214171c8b?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/155214171c8b</guid>
            <category><![CDATA[bmp280]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[arduino-ide]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 14:54:15 GMT</pubDate>
            <atom:updated>2021-04-09T14:54:15.473Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! I’m back! This time, we will continue what we did before in <a href="https://fernaldifz.medium.com/embedded-system-project-9-mini-weather-station-1be67b00ffa3"><strong>project 9</strong></a>. We will try to make a <strong>database</strong> to receive sensor readings from BMP280. In other words, we will try to build an ESP32 client that makes an <strong>HTTP POST request</strong> to a <strong>PHP script</strong> to <strong>insert data</strong> (in this case sensor readings) into a <strong>MySQL database</strong>. For sure, we will also try to make a <strong>web page</strong> that displays the sensor readings, timestamps, and other information from the database. In other words, you may visualize your own data from anywhere in the world as long you can access your own server.</p><p>For this project, I will use this <a href="https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/">randomnerdtutorials</a> as references! The main differences are I used BMP280 instead of BME280 and I modified some things on the table that is used to display database content.</p><h4>Create MySQL Table</h4><p>First of all, we need to create a MySQL database. There are <strong>many options</strong> to <strong>create a MySQL database</strong>. In my case, I will use <a href="https://www.000webhost.com/">000webhost</a>. If you guys also interested in <strong>using 000webhost</strong> (don’t worry, it’s free!), here is a short explanation of how to do it:</p><ul><li>Create your free website from 000webhost</li><li>Create MySQL Database, here is a good <a href="https://www.000webhost.com/forum/t/how-to-create-a-mysql-database-on-000webhost/39142?__cf_chl_jschl_tk__=f3274e03d43d7d0e1b0ba91c56294b287cd5f3a2-1617854081-0-Ae81-_tVAC0M41s2Dac9ioJ6PsE1zshi5NuZirBIlVw56H7BWQp6xK2U5yKLjo6wQXQCflHUcwIZeK9IFOmgrKG8d8qZkgWn10B1c1RvXMDbousIx5YzYIJQeU01N0Z5HfLOeAwgJ3qOnMq8oaRLGEUVO5BxxkkXGOb02Kot6It15JaDe7GzWRwdJjlCu0x-lisGChFlceEdSo_rBh8nwQpCjkKqwH4QpqwIDYcwGShuwSMzlv6tJqok_rigRfyTPxarHe8Heqyq_q1XrnZNunuWiHUExbJOvszgvB9i0WcSpUX1e9SG5GfwsWUatBcK3M1pvm0f7Knki-BJ6SP-MtdO6ebqdZqMPuUAxV5KydRVghG6GiDOlPm4SeK3BKqfA0vNnmDlqVFHuRsAgPXv_RvFNSuK9QNk7IDK0avF5QNZqtkvq4Ye9e9zCR5ud323pNReFUmImbXINK4odguXimk">link</a> to explain it</li><li>Then, click Manage &gt; PhpMyAdmin</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*SujqGRcvlpQefgnRJwUyVA.png" /></figure><ul><li>Then, click SQL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQY6KbOfPU2Pfan5ZqT-hw.png" /></figure><ul><li>After that, you may copy the following code</li></ul><pre>CREATE TABLE SensorData (<br>    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,<br>    sensor VARCHAR(30) NOT NULL,<br>    location VARCHAR(30) NOT NULL,<br>    value1 VARCHAR(10),<br>    value2 VARCHAR(10),<br>    value3 VARCHAR(10),<br>    reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>)</pre><ul><li>Next, don’t forget to click Go</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frKNe2qjAwUGpFyqSXyhEQ.png" /></figure><h4>Create PHP Script HTTP POST</h4><p>Next, we will try to create a PHP script that is responsible for receiving incoming requests from the ESP32 and inserting the data into a MySQL database.</p><ul><li>Now, at the sidebar, open File Manager instead of Database Manager, then click Upload Files</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzJMJqoiDtrcHX3izgtoww.png" /></figure><ul><li>Then, open public_html folder</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjkpPd0CQtVPTSyQDQ_cEQ.png" /></figure><ul><li>Next, you may upload your PHP file that has the following snippet inside.</li></ul><pre>&lt;?php</pre><pre>/*<br>  Rui Santos<br>  Complete project details at <a href="https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/">https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/</a><br>  <br>  Permission is hereby granted, free of charge, to any person obtaining a copy<br>  of this software and associated documentation files.<br>  <br>  The above copyright notice and this permission notice shall be included in all<br>  copies or substantial portions of the Software.<br>*/</pre><pre>$servername = &quot;localhost&quot;;</pre><pre>// REPLACE with your Database name<br>$dbname = &quot;REPLACE_WITH_YOUR_DATABASE_NAME&quot;;<br>// REPLACE with Database user<br>$username = &quot;REPLACE_WITH_YOUR_USERNAME&quot;;<br>// REPLACE with Database user password<br>$password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;</pre><pre>// Keep this API Key value to be compatible with the ESP32 code provided in the project page. <br>// If you change this value, the ESP32 sketch needs to match<br>$api_key_value = &quot;tPmAT5Ab3j7F9&quot;;</pre><pre>$api_key= $sensor = $location = $value1 = $value2 = $value3 = &quot;&quot;;</pre><pre>if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) {<br>    $api_key = test_input($_POST[&quot;api_key&quot;]);<br>    if($api_key == $api_key_value) {<br>        $sensor = test_input($_POST[&quot;sensor&quot;]);<br>        $location = test_input($_POST[&quot;location&quot;]);<br>        $value1 = test_input($_POST[&quot;value1&quot;]);<br>        $value2 = test_input($_POST[&quot;value2&quot;]);<br>        $value3 = test_input($_POST[&quot;value3&quot;]);<br>        <br>        // Create connection<br>        $conn = new mysqli($servername, $username, $password, $dbname);<br>        // Check connection<br>        if ($conn-&gt;connect_error) {<br>            die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);<br>        } <br>        <br>        $sql = &quot;INSERT INTO SensorData (sensor, location, value1, value2, value3)<br>        VALUES (&#39;&quot; . $sensor . &quot;&#39;, &#39;&quot; . $location . &quot;&#39;, &#39;&quot; . $value1 . &quot;&#39;, &#39;&quot; . $value2 . &quot;&#39;, &#39;&quot; . $value3 . &quot;&#39;)&quot;;<br>        <br>        if ($conn-&gt;query($sql) === TRUE) {<br>            echo &quot;New record created successfully&quot;;<br>        } <br>        else {<br>            echo &quot;Error: &quot; . $sql . &quot;&lt;br&gt;&quot; . $conn-&gt;error;<br>        }<br>    <br>        $conn-&gt;close();<br>    }<br>    else {<br>        echo &quot;Wrong API Key provided.&quot;;<br>    }</pre><pre>}<br>else {<br>    echo &quot;No data posted with HTTP POST.&quot;;<br>}</pre><pre>function test_input($data) {<br>    $data = trim($data);<br>    $data = stripslashes($data);<br>    $data = htmlspecialchars($data);<br>    return $data;<br>}</pre><p>N.B. As usual, don’t forget to change the database name, username, and password before uploading. Example: If your database name is “MyDatabase”, you may make it</p><pre>$dbname = &quot;MyDatabase&quot;; </pre><ul><li>In my case, I made the PHP file with the name “POST_DATA”, and the website with the name “choleraic-authoriza” (generated automatically). So, if I open this <a href="https://choleraic-authoriza.000webhostapp.com/POST_DATA.php">link</a> will result:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5lyRivxLmY7Rbz_EFwZ_Q.png" /><figcaption><a href="https://choleraic-authoriza.000webhostapp.com/POST.php">https://choleraic-authoriza.000webhostapp.com/POST_DATA.php</a></figcaption></figure><h4>Create PHP Script to Display Database Content</h4><p>We are still not done with PHP Script! Next, we need to create another PHP Script in the /public_html directory to display all the database content on a web page. Personally, I named the file with the name “DATA”.</p><p>For the snippet, you may copy the following code.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;&lt;body&gt;<br>&lt;?php<br>/*<br>  Rui Santos<br>  Complete project details at <a href="https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/">https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/</a><br>  <br>  Permission is hereby granted, free of charge, to any person obtaining a copy<br>  of this software and associated documentation files.<br>  <br>  The above copyright notice and this permission notice shall be included in all<br>  copies or substantial portions of the Software.<br>*/</pre><pre>$servername = &quot;localhost&quot;;</pre><pre>// REPLACE with your Database name<br>$dbname = &quot;REPLACE_WITH_YOUR_DATABASE_NAME&quot;;<br>// REPLACE with Database user<br>$username = &quot;REPLACE_WITH_YOUR_USERNAME&quot;;<br>// REPLACE with Database user password<br>$password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;</pre><pre>// Create connection<br>$conn = new mysqli($servername, $username, $password, $dbname);<br>// Check connection<br>if ($conn-&gt;connect_error) {<br>    die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);<br>}</pre><pre>$sql = &quot;SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData ORDER BY id DESC&quot;;</pre><pre>echo &#39;&lt;table cellspacing=&quot;15&quot; cellpadding=&quot;5&quot;&gt;<br>      &lt;tr&gt; <br>        &lt;th&gt;ID&lt;/th&gt; <br>        &lt;th&gt;Sensor&lt;/th&gt; <br>        &lt;th&gt;Location&lt;/th&gt; <br>        &lt;th&gt;Temperature (°C)&lt;/th&gt; <br>        &lt;th&gt;Pressure (Pa)&lt;/th&gt;<br>        &lt;th&gt;Approx Altitude (m)&lt;/th&gt; <br>        &lt;th&gt;Timestamp&lt;/th&gt; <br>      &lt;/tr&gt;&#39;;<br> <br>if ($result = $conn-&gt;query($sql)) {<br>    while ($row = $result-&gt;fetch_assoc()) {<br>        $row_id = $row[&quot;id&quot;];<br>        $row_sensor = $row[&quot;sensor&quot;];<br>        $row_location = $row[&quot;location&quot;];<br>        $row_value1 = $row[&quot;value1&quot;];<br>        $row_value2 = $row[&quot;value2&quot;]; <br>        $row_value3 = $row[&quot;value3&quot;]; <br>        $row_reading_time = $row[&quot;reading_time&quot;];<br>        // Uncomment to set timezone to - 1 hour (you can change 1 to any number)<br>        //$row_reading_time = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;$row_reading_time - 1 hours&quot;));<br>      <br>        // Uncomment to set timezone to + 4 hours (you can change 4 to any number)<br>        //$row_reading_time = date(&quot;Y-m-d H:i:s&quot;, strtotime(&quot;$row_reading_time + 4 hours&quot;));<br>      <br>        echo &#39;&lt;tr&gt; <br>                &lt;td&gt;&#39; . $row_id . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_sensor . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_location . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_value1 . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_value2 . &#39;&lt;/td&gt;<br>                &lt;td&gt;&#39; . $row_value3 . &#39;&lt;/td&gt; <br>                &lt;td&gt;&#39; . $row_reading_time . &#39;&lt;/td&gt; <br>              &lt;/tr&gt;&#39;;<br>    }<br>    $result-&gt;free();<br>}</pre><pre>$conn-&gt;close();<br>?&gt; <br>&lt;/table&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>N.B. As usual, don’t forget to change the database name, username, and password before uploading. Example: If your database name is “MyDatabase”, you may make it (same as before)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taMGwmx_TYYuwgAiibNJAg.png" /></figure><p>After this, I can open this <a href="https://choleraic-authoriza.000webhostapp.com/DATA.php">link</a> with the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHfu5CaVIaI2ke4g49s69w.png" /><figcaption><a href="https://choleraic-authoriza.000webhostapp.com/DATA.php">https://choleraic-authoriza.000webhostapp.com/DATA.php</a></figcaption></figure><p>Yup! If you can see an empty table printed in your browser, it means that everything is ready. In the next section, we will try to learn how to insert BMP280 sensor readings data from ESP32 into the database.</p><h3>Preparing ESP32</h3><p>Now, we will assemble a simple circuit and upload the sketch provided to insert temperature, pressure, and approximate altitude into the database every 30 seconds.</p><h4>Components and Parts Required</h4><ul><li>ESP32 Development Board</li><li>BMP280 sensor</li><li>Jumper wires (I’m using male to male)</li><li>Breadboard</li></ul><h4>Schematics Diagram</h4><p>For this project, we will still use the same schematics diagram from the previous project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Bj0R19YWJmIU120csiJkFg.png" /><figcaption>My Schematics Diagram</figcaption></figure><p>As I explained before in the previous project, although in the schematics diagram I used BMP180, BMP280 can also work as long you pay attention to the pins! (I can’t found BMP280 sensor in fritzing, that’s why I used BMP180 instead of BMP280)</p><p>Some important notes:</p><ul><li>ESP32 3v3 connected to BMP280 VCC</li><li>ESP32 GND connected to BMP280 GND</li><li>GPIO 21 connected to BMP280 SCL</li><li>GPIO22 connected to BMP280 SDA</li></ul><h4>ESP32 Code</h4><p>Next, you may copy the following code</p><pre>/*<br>  This code references to: Rui Santos<br>  Complete project details at <a href="https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/">https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/</a><br>  <br>  Permission is hereby granted, free of charge, to any person obtaining a copy<br>  of this software and associated documentation files.<br>  <br>  The above copyright notice and this permission notice shall be included in all<br>  copies or substantial portions of the Software.</pre><pre>*/</pre><pre>#include &lt;WiFi.h&gt;<br>#include &lt;HTTPClient.h&gt;</pre><pre>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BMP280.h&gt;</pre><pre>// Replace with your network credentials<br>const char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;</pre><pre>// REPLACE with your Domain name and URL path or IP address with path<br>const char* serverName = &quot;DOMAIN_NAME&quot;;</pre><pre>// Keep this API Key value to be compatible with the PHP code provided in the project page. <br>// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key <br>String apiKeyValue = &quot;tPmAT5Ab3j7F9&quot;;</pre><pre>String sensorName = &quot;BMP280&quot;;<br>String sensorLocation = &quot;Office&quot;;</pre><pre>#define SEALEVELPRESSURE_HPA (1013.25)</pre><pre>Adafruit_BMP280 bmp; // I2C<br>//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI<br>//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);</pre><pre>void setup() {<br>  Serial.begin(115200);<br>  <br>  WiFi.begin(ssid, password);<br>  Serial.println(&quot;Connecting&quot;);<br>  while(WiFi.status() != WL_CONNECTED) { <br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  Serial.println(&quot;&quot;);<br>  Serial.print(&quot;Connected to WiFi network with IP Address: &quot;);<br>  Serial.println(WiFi.localIP());</pre><pre>// (you can also pass in a Wire library object like &amp;Wire2)<br>  bool status = bmp.begin(0x76);<br>  if (!status) {<br>    Serial.println(&quot;Could not find a valid BMP280 sensor, check wiring or change I2C address!&quot;);<br>    while (1);<br>  }<br>}</pre><pre>void loop() {<br>  //Check WiFi connection status<br>  if(WiFi.status()== WL_CONNECTED){<br>    HTTPClient http;<br>    <br>    // Your Domain name with URL path or IP address with path<br>    http.begin(serverName);<br>    <br>    // Specify content-type header<br>    http.addHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);<br>    <br>    // Prepare your HTTP POST request data<br>    String httpRequestData = &quot;api_key=&quot; + apiKeyValue + &quot;&amp;sensor=&quot; + sensorName<br>                          + &quot;&amp;location=&quot; + sensorLocation + &quot;&amp;value1=&quot; + String(bmp.readTemperature())<br>                          + &quot;&amp;value2=&quot; + String(bmp.readPressure()) + &quot;&amp;value3=&quot; + String((bmp.readAltitude(SEALEVELPRESSURE_HPA))) + &quot;&quot;;<br>    Serial.print(&quot;httpRequestData: &quot;);<br>    Serial.println(httpRequestData);<br>    <br>    // You can comment the httpRequestData variable above<br>    // then, use the httpRequestData variable below (for testing purposes without the BMP280 sensor)<br>    //String httpRequestData = &quot;api_key=tPmAT5Ab3j7F9&amp;sensor=BMP280&amp;location=Office&amp;value1=24.75&amp;value2=49.54&amp;value3=1005.14&quot;;</pre><pre>// Send HTTP POST request<br>    int httpResponseCode = http.POST(httpRequestData);<br>     <br>    // If you need an HTTP request with a content type: text/plain<br>    //http.addHeader(&quot;Content-Type&quot;, &quot;text/plain&quot;);<br>    //int httpResponseCode = http.POST(&quot;Hello, World!&quot;);<br>    <br>    // If you need an HTTP request with a content type: application/json, use the following:<br>    //http.addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    //int httpResponseCode = http.POST(&quot;{\&quot;value1\&quot;:\&quot;19\&quot;,\&quot;value2\&quot;:\&quot;67\&quot;,\&quot;value3\&quot;:\&quot;78\&quot;}&quot;);<br>        <br>    if (httpResponseCode&gt;0) {<br>      Serial.print(&quot;HTTP Response code: &quot;);<br>      Serial.println(httpResponseCode);<br>    }<br>    else {<br>      Serial.print(&quot;Error code: &quot;);<br>      Serial.println(httpResponseCode);<br>    }<br>    // Free resources<br>    http.end();<br>  }<br>  else {<br>    Serial.println(&quot;WiFi Disconnected&quot;);<br>  }<br>  //Send an HTTP POST request every 30 seconds (30.000 mili seconds)<br>  delay(30000);  <br>}</pre><p>As usual, make sure to change the SSID, password, and domain name before uploading!</p><pre>// Replace with your network credentials<br>const char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;</pre><pre>// REPLACE with your Domain name and URL path or IP address with path<br>const char* serverName = &quot;DOMAIN_NAME&quot;;</pre><h4>Result?</h4><p>So…. I tried it, and here are the results!</p><p>I found this in the serial monitor in Arduino IDE. Fortunately, HTTP Response code: 200!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMu8G-3O8TQV2AaTw61oIQ.png" /><figcaption>Serial Monitor in Arduino IDE</figcaption></figure><p>So, I tried to refresh the <a href="https://choleraic-authoriza.000webhostapp.com/DATA.php">web page</a> after 2–3 mins. VOILA!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOR_vWYHsBOm_-D2hMMfcQ.png" /><figcaption>My Web Page</figcaption></figure><p>Oh, wait! Probably some of you guys wondered about the ID. Where is the first ID? Why the ID starts from 2, not 1?!</p><p>No worries! I have a good explanation for it. Actually, I didn’t succeed on the first try. To be honest, I tried many times, but still failed! In the serial monitor in Arduino IDE, I got HTTP code 200, but on the web page, the data wasn’t updated. So, I tried to insert data into the database manually, and it succeeds. The data that I inserted manually has an ID with the value “1”. Later, I deleted the data, but that’s why when I succeed to send data with HTTP POST, the ID starts with 2, not 1.</p><p>For your information, my code didn’t work because I put the wrong server name in Arduino IDE, so make sure to pay attention! If apparently your web page also doesn’t work, I recommend debugging by inserting data manually to the database with SQL and do Serial.println the data to the serial monitor in Arduino IDE.</p><p>Additional information, in the Database Manager &gt; Manage &gt; PhpMyAdmin, you may find something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nntn4QfdoOxb01Mp31MXfg.png" /></figure><p>You may manage the data stored in your SensorData table. You can edit it, copy it, delete it, etc.</p><h4>BONUS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwkglLi_Bwj6oQMWikaiuw.png" /><figcaption>My Another Work</figcaption></figure><h4>Code Explanation</h4><p>I would like to summarize how the code works, which are:</p><ul><li>Import all libraries needed</li><li>Set variables that you might want to change, which are: apiKeyValue, sensorName, sensorLocation</li><li>The apiKeyValue is a random string, so feel free to modify it! It’s used for security reasons, so only anyone that knows your API key can publish data to your database</li><li>Initialize the serial communication to debug</li><li>Establish a Wi-Fi connection between ESP32 and the router</li><li>Initialize the BMP280 sensor to get sensor readings (temperature, pressure, and approximate altitude)</li></ul><p>Next, in the loop(), you make the HTTP POST request every 30 seconds (because we put delay(30000) in the end) with the latest BMP280 readings:</p><pre>// Your Domain name with URL path or IP address with path<br>http.begin(serverName);<br>    <br>// Specify content-type header<br>http.addHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);<br>       <br>// Prepare your HTTP POST request data<br>String httpRequestData = &quot;api_key=&quot; + apiKeyValue + &quot;&amp;sensor=&quot; + sensorName<br>                          + &quot;&amp;location=&quot; + sensorLocation + &quot;&amp;value1=&quot; + String(bmp.readTemperature())<br>                          + &quot;&amp;value2=&quot; + String(bmp.readPressure()) + &quot;&amp;value3=&quot; + String((bmp.readAltitude(SEALEVELPRESSURE_HPA))) + &quot;&quot;;</pre><pre>// Send HTTP POST request<br>int httpResponseCode = http.POST(httpRequestData);</pre><p>If you want, you may comment the httpRequestData variable above that concatenates all the BMP280 readings and use the httpRequestData variable below to test your code.</p><pre>// You can comment the httpRequestData variable above<br>// then, use the httpRequestData variable below (for testing purposes without the BMP280 sensor)<br>//String httpRequestData = &quot;api_key=tPmAT5Ab3j7F9&amp;sensor=BMP280&amp;location=Office&amp;value1=24.75&amp;value2=49.54&amp;value3=1005.14&quot;;</pre><h4>Conclusion</h4><p>It seems that our journey is done. To conclude, we can combine the mini weather station we made in the previous project with the database. We can publish sensor data into a database in our own server domain that we can access from anywhere in the world. In my case, I used 000webhost.</p><p>I hope that this project can inspire you guys to keep trying and learning new things, especially about Embedded System! Don’t forget to have fun and see you guys in the next project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=155214171c8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded System Project 9: Mini Weather Station]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-9-mini-weather-station-1be67b00ffa3?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be67b00ffa3</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[bmp280]]></category>
            <category><![CDATA[web-server]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 15:43:15 GMT</pubDate>
            <atom:updated>2021-04-01T15:44:59.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi! Before, we already made an ESP32 web server to turn on/off LEDs. Now, we will try to create a web server with the ESP32 to display readings from the BMP280 sensor module. As we know from previous projects, the BMP280 sensor can be used to measures <strong>temperature</strong>, <strong>pressure,</strong> and <strong>approximate altitude</strong>. In other words, we can easily build a <strong>mini weather station</strong> and <strong>monitor the measurements</strong> using the ESP32 web server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*ng5F4cuXogLz1pVqvaD78g.jpeg" /><figcaption>My Mini Weather Station</figcaption></figure><p>As usual, we will use Arduino IDE to compile and upload the code to the ESP32. For this story/project, I’m using this <a href="https://randomnerdtutorials.com/esp32-web-server-with-bme280-mini-weather-station/"><strong>randomnerdtutorials post</strong></a> as a reference.</p><h4>Parts and Components Required:</h4><ul><li>ESP32 Development Board</li><li>BMP280 sensor module</li><li>Breadboard</li><li>Jumper wires</li><li>Any device that as a browser on the local network</li></ul><h4>Additional Information</h4><p>Before we continue, make sure that you already installed Adafruit Unified Sensor from Library Manager in Arduino IDE. I already have mine installed because I need it for my previous project. To access the Library Manager, go to <strong>Sketch </strong>&gt; <strong>Include Library</strong> &gt; <strong>Manage Libraries.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6UXiplA_DNEIaV7rhTGZQ.png" /><figcaption>Library Manager in Arduino IDE</figcaption></figure><p>Oh, right! If you guys are still not familiar with external sensors especially <strong>BMP280</strong>, I recommend checking my <a href="https://fernaldifz.medium.com/embedded-system-project-4-esp32-external-sensor-f6f4974aab1b"><strong>previous project</strong></a> about <strong>BMP280</strong>! Also, if you guys want to know more about <strong>I2C</strong>, consider visiting my <a href="https://fernaldifz.medium.com/embedded-system-project-5-oled-display-with-esp32-eba09bf64fe1"><strong>previous project</strong></a> about <strong>OLED displays</strong>! There are some brief explanations about <strong>I2C</strong>.</p><h4>Schematic Diagram</h4><p>We will use the same schematic diagram with my project 4 which is about the external sensor (BMP280), which means, ESP32 3v3 connected to BMP280 VCC, ESP32 GND connected to BMP280 GND, GPIO 21 connected to BMP280 SCL, and GPIO22 connected to BMP280 SDA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*uiigq37kmXaE_VdvN8r8Yw.png" /><figcaption>Schematic diagram from <a href="https://www.circuitschools.com/interfacing-bmp280-with-esp-32-on-i2c-with-errors-and-solutions/">https://www.circuitschools.com/interfacing-bmp280-with-esp-32-on-i2c-with-errors-and-solutions</a>/</figcaption></figure><p>Although I will use BMP280, BMP180 also can work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*V8Z0jtznasFk1EPU0vXO_A.png" /><figcaption>Schematic Diagram Version 2</figcaption></figure><p>So I tried to make my own schematic diagram. Unfortunately, I couldn’t find the exact sensor I used which is BMP280 that has 6 pins (as there are only 4 pins in the schematic diagram). But there is no serious matter with it because in general, they are the same as I only use 4 from 6 pins which all of them are available in that sensor in the schematic diagram.</p><h4>Table in HTML</h4><p>Because we will try to display BMP280 sensor readings on a web page, it’s better to make the table in HTML to make it more comfortable to be seen. In short, these are the way to make the table in HTML:</p><ul><li>To create table, use &lt;table&gt; and &lt;/table&gt; tags</li><li>To create table row, use &lt;tr&gt; and &lt;/tr&gt; tags</li><li>To create the table heading, use &lt;th&gt; and &lt;/th&gt; tags</li><li>To create table cell, use &lt;tc&gt; and &lt;/tc&gt; tags</li></ul><p>To create a table for our readings with BMP280, we can use the following HTML code:</p><pre>&lt;table&gt;<br>  &lt;tr&gt;<br>    &lt;th&gt;MEASUREMENT&lt;/th&gt;<br>    &lt;th&gt;VALUE&lt;/th&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt; <br>    &lt;td&gt;Temp. Celsius&lt;/td&gt;<br>    &lt;td&gt;--- *C&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt; <br>    &lt;td&gt;Temp. Fahrenheit&lt;/td&gt;<br>    &lt;td&gt;--- *F&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;Pressure&lt;/td&gt;<br>    &lt;td&gt;--- hPa&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;Approx. Altitude&lt;/td&gt;<br>    &lt;td&gt;--- meters&lt;/td&gt;&lt;/tr&gt;<br>&lt;/table&gt;</pre><p>For now, this is how it looked like. But don’t worry! We will make it better!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*2V9H_jMuzyMsQuS59Vmzbg.png" /></figure><h4>Arduino IDE Code</h4><p>Now, you may use the following code to get the sensor readings, but as usual, don’t forget to change the SSID and password before uploading! This code references Rui Santos, but I modified it because I used the BMP280 sensor module instead of the BME280 sensor module. I also modified the web server style.</p><pre>/*********<br>  This code references Rui Santos<br>  Complete project details at <a href="https://randomnerdtutorials.com/">https://randomnerdtutorials.com</a>  <br>*********/</pre><pre>// Load Wi-Fi library<br>#include &lt;WiFi.h&gt;<br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_BMP280.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;</pre><pre>#define SEALEVELPRESSURE_HPA (1013.25)</pre><pre>Adafruit_BMP280 bmp; // I2C<br>//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI<br>//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);</pre><pre>// Replace with your network credentials<br>const char* ssid = &quot;FF&quot;;<br>const char* password = &quot;anrq8199&quot;;</pre><pre>// Set web server port number to 80<br>WiFiServer server(80);</pre><pre>// Variable to store the HTTP request<br>String header;</pre><pre>// Current time<br>unsigned long currentTime = millis();<br>// Previous time<br>unsigned long previousTime = 0; <br>// Define timeout time in milliseconds (example: 2000ms = 2s)<br>const long timeoutTime = 2000;</pre><pre>void setup() {<br>  Serial.begin(115200);<br>  bool status;</pre><pre>// default settings<br>  // (you can also pass in a Wire library object like &amp;Wire2)<br>  //status = bmp.begin();  <br>  if (!bmp.begin(0x76)) {<br>    Serial.println(&quot;Could not find a valid BMP280 sensor, check wiring!&quot;);<br>    while (1);<br>  }</pre><pre>// Connect to Wi-Fi network with SSID and password<br>  Serial.print(&quot;Connecting to &quot;);<br>  Serial.println(ssid);<br>  WiFi.begin(ssid, password);<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  // Print local IP address and start web server<br>  Serial.println(&quot;&quot;);<br>  Serial.println(&quot;WiFi connected.&quot;);<br>  Serial.println(&quot;IP address: &quot;);<br>  Serial.println(WiFi.localIP());<br>  server.begin();<br>}</pre><pre>void loop(){<br>  WiFiClient client = server.available();   // Listen for incoming clients</pre><pre>if (client) {                             // If a new client connects,<br>    currentTime = millis();<br>    previousTime = currentTime;<br>    Serial.println(&quot;New Client.&quot;);          // print a message out in the serial port<br>    String currentLine = &quot;&quot;;                // make a String to hold incoming data from the client<br>    while (client.connected() &amp;&amp; currentTime - previousTime &lt;= timeoutTime) {  // loop while the client&#39;s connected<br>      currentTime = millis();<br>      if (client.available()) {             // if there&#39;s bytes to read from the client,<br>        char c = client.read();             // read a byte, then<br>        Serial.write(c);                    // print it out the serial monitor<br>        header += c;<br>        if (c == &#39;\n&#39;) {                    // if the byte is a newline character<br>          // if the current line is blank, you got two newline characters in a row.<br>          // that&#39;s the end of the client HTTP request, so send a response:<br>          if (currentLine.length() == 0) {<br>            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)<br>            // and a content-type so the client knows what&#39;s coming, then a blank line:<br>            client.println(&quot;HTTP/1.1 200 OK&quot;);<br>            client.println(&quot;Content-type:text/html&quot;);<br>            client.println(&quot;Connection: close&quot;);<br>            client.println();<br>            <br>            // Display the HTML web page<br>            client.println(&quot;&lt;!DOCTYPE html&gt;&lt;html&gt;&quot;);<br>            client.println(&quot;&lt;head&gt;&lt;meta name=\&quot;viewport\&quot; content=\&quot;width=device-width, initial-scale=1\&quot;&gt;&quot;);<br>            client.println(&quot;&lt;link rel=\&quot;icon\&quot; href=\&quot;data:,\&quot;&gt;&quot;);<br>            // CSS to style the table <br>            client.println(&quot;&lt;style&gt;body { text-align: center; font-family: \&quot;courier\&quot;, Arial;}&quot;);<br>            client.println(&quot;table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }&quot;);<br>            client.println(&quot;th { padding: 12px; background-color: #00c767; color: white; }&quot;);<br>            client.println(&quot;tr { border: 1px solid #ddd; padding: 12px; }&quot;);<br>            client.println(&quot;tr:hover { background-color: #bcbcbc; }&quot;);<br>            client.println(&quot;td { border: none; padding: 12px; }&quot;);<br>            client.println(&quot;.sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }&quot;);<br>            client.println(&quot;table, td, th {border: 1px solid black;}&quot;);<br>            <br>            // Web Page Heading<br>            client.println(&quot;&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;ESP32 with BMP280&lt;/h1&gt;&quot;);<br>            client.println(&quot;&lt;table&gt;&lt;tr&gt;&lt;th&gt;MEASUREMENT&lt;/th&gt;&lt;th&gt;VALUE&lt;/th&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Temp. Celsius&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bmp.readTemperature());<br>            client.println(&quot; *C&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);  <br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Temp. Fahrenheit&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(1.8 * bmp.readTemperature() + 32);<br>            client.println(&quot; *F&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);       <br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Pressure&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bmp.readPressure() / 100.0F);<br>            client.println(&quot; hPa&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Approx. Altitude&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bmp.readAltitude(SEALEVELPRESSURE_HPA));<br>            client.println(&quot; m&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;);<br>            <br>            // The HTTP response ends with another blank line<br>            client.println();<br>            // Break out of the while loop<br>            break;<br>          } else { // if you got a newline, then clear currentLine<br>            currentLine = &quot;&quot;;<br>          }<br>        } else if (c != &#39;\r&#39;) {  // if you got anything else but a carriage return character,<br>          currentLine += c;      // add it to the end of the currentLine<br>        }<br>      }<br>    }<br>    // Clear the header variable<br>    header = &quot;&quot;;<br>    // Close the connection<br>    client.stop();<br>    Serial.println(&quot;Client disconnected.&quot;);<br>    Serial.println(&quot;&quot;);<br>  }<br>}</pre><p>N.B. For this code, I used the average sea level pressure which is 1013.25, because I was having a hard time finding my average sea level pressure in my location, probably because I don’t live in the big city.</p><h4>Result?</h4><p>This is how the web server looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rmm6jcb2blNLZHQwDODkDA.png" /></figure><p>Then, I tried to keep refreshing the web server (with Ctrl + R) while pressing the BMP280 sensor. Because the value of sensor readings is changing, it seems like I succeed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*EW6VEd0TZ7cFg-BFX4OtQg.gif" /><figcaption>My ESP32 Web Server to Show BMP280 Readings</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*BlWPDVmyljtW0R43TTlnWQ.gif" /><figcaption>Bonus GIF (Careful, might cause dizziness)</figcaption></figure><h4>Code Explanation?</h4><p>Alright! As usual, I would like to point out some important parts of the code! I will not explain some part of the code that had been explained before though, so make sure to check my previous project especially about the <a href="https://fernaldifz.medium.com/esp32-web-server-669000c385e2">ESP32 web server</a>!</p><p>In the setup(), we start a serial communication at a baud rate of 115200 for debugging purposes with the Serial.begin() function.</p><pre>Serial.begin(115200);</pre><p>In the loop(), the following code snippet sends the web page to display the BMP280 sensor readings in a table. In Arduino IDE, we use client.println() to send the web page to the client.</p><pre>// Display the HTML web page<br>            client.println(&quot;&lt;!DOCTYPE html&gt;&lt;html&gt;&quot;);<br>            client.println(&quot;&lt;head&gt;&lt;meta name=\&quot;viewport\&quot; content=\&quot;width=device-width, initial-scale=1\&quot;&gt;&quot;);<br>            client.println(&quot;&lt;link rel=\&quot;icon\&quot; href=\&quot;data:,\&quot;&gt;&quot;);<br>            // CSS to style the table <br>            client.println(&quot;&lt;style&gt;body { text-align: center; font-family: \&quot;courier\&quot;, Arial;}&quot;);<br>            client.println(&quot;table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }&quot;);<br>            client.println(&quot;th { padding: 12px; background-color: #00c767; color: white; }&quot;);<br>            client.println(&quot;tr { border: 1px solid #ddd; padding: 12px; }&quot;);<br>            client.println(&quot;tr:hover { background-color: #bcbcbc; }&quot;);<br>            client.println(&quot;td { border: none; padding: 12px; }&quot;);<br>            client.println(&quot;.sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }&quot;);<br>            client.println(&quot;table, td, th {border: 1px solid black;}&quot;);<br>            <br>            // Web Page Heading<br>            client.println(&quot;&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;ESP32 with BMP280&lt;/h1&gt;&quot;);<br>            client.println(&quot;&lt;table&gt;&lt;tr&gt;&lt;th&gt;MEASUREMENT&lt;/th&gt;&lt;th&gt;VALUE&lt;/th&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Temp. Celsius&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bmp.readTemperature());<br>            client.println(&quot; *C&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);  <br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Temp. Fahrenheit&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(1.8 * bmp.readTemperature() + 32);<br>            client.println(&quot; *F&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);       <br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Pressure&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bmp.readPressure() / 100.0F);<br>            client.println(&quot; hPa&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;tr&gt;&lt;td&gt;Approx. Altitude&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>            client.println(bmp.readAltitude(SEALEVELPRESSURE_HPA));<br>            client.println(&quot; m&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);<br>            client.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;);</pre><p>Keep in mind that to display the sensor readings on the table, we just need to send them between the corresponding &lt;td&gt; and &lt;/td&gt; tags. For example, to display the temperature in Celcius:</p><pre>client.println(&quot;&lt;tr&gt;&lt;td&gt;Temp. Celsius&lt;/td&gt;&lt;td&gt;&lt;span class=\&quot;sensor\&quot;&gt;&quot;);<br>client.println(bmp.readTemperature());<br>client.println(&quot; *C&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);</pre><h4>Conclusion</h4><p>In summary, we already learn about how to read temperature, pressure, and estimate altitude using the BMP280 sensor module. Then, we also learned how to build a web server that displays a table with sensor readings. Of course, this project can also be used to display data from other sensors easily.</p><p>I hope that this project can bring you guys inspiration and excitement to keep learning technology, especially about microprocessors. See you guys in the next project and don’t forget to have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be67b00ffa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ESP32 Web Server]]></title>
            <link>https://fernaldifz.medium.com/esp32-web-server-669000c385e2?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/669000c385e2</guid>
            <category><![CDATA[wifi]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 14:39:09 GMT</pubDate>
            <atom:updated>2021-03-31T12:10:20.619Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embedded System Project 8: ESP32 Web Server</h3><p>Hello! This time, in this story we will play with an <strong>ESP32 web server</strong>. We will try to create a standalone web server with an ESP32 that controls outputs of 2 LEDs using the <strong>Arduino IDE</strong> programming environment. This web server is <strong>mobile responsive</strong> and can be accessed with any device that as a browser on the local network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*u7pySWzaI67ULMHi7Ni0bQ.png" /></figure><p>As usual, before we continue, I would like to tell you guys that we will use this <a href="https://randomnerdtutorials.com/esp32-web-server-arduino-ide/">randomnerdtutorials</a> link as a reference.</p><h4>Components and Parts Required</h4><p>For this story, we will need:</p><ul><li>ESP32 Board</li><li>2x 5mm LED</li><li>2x 330 Ohm resistor</li><li>Jumper wires (I’m using male to male jumper wires)</li><li>Breadboard</li><li>Any device that as a browser on the local network</li></ul><h4>Schematic Diagram</h4><p>First, we have to build the circuit. The first LED connected to GPIO19 and the other one connected to GPIO21.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*JpgQG00W4XANClFLfkVBwQ.png" /><figcaption>My Circuit</figcaption></figure><h4>Code</h4><p>Next, we can start with the code. You may copy the following code to your Arduino IDE, but don’t upload it immediately! We need to change some things to make it work!</p><pre>/*********<br>  This code is referencing to: Rui Santos<br>  More details at <a href="https://randomnerdtutorials.com/">https://randomnerdtutorials.com</a>  <br>*********/</pre><pre>// Load Wi-Fi library<br>#include &lt;WiFi.h&gt;</pre><pre>// Replace with your network credentials<br>const char* ssid = &quot;FF&quot;;<br>const char* password = &quot;anrq8199&quot;;</pre><pre>// Set web server port number to 80<br>WiFiServer server(80);</pre><pre>// Variable to store the HTTP request<br>String header;</pre><pre>// Auxiliar variables to store the current output state<br>String output19State = &quot;off&quot;;<br>String output21State = &quot;off&quot;;</pre><pre>// Assign output variables to GPIO pins<br>const int output19 = 19;<br>const int output21 = 21;</pre><pre>// Current time<br>unsigned long currentTime = millis();<br>// Previous time<br>unsigned long previousTime = 0; <br>// Define timeout time in milliseconds (example: 2000ms = 2s)<br>const long timeoutTime = 2000;</pre><pre>void setup() {<br>  Serial.begin(115200);<br>  // Initialize the output variables as outputs<br>  pinMode(output19, OUTPUT);<br>  pinMode(output21, OUTPUT);<br>  // Set outputs to LOW<br>  digitalWrite(output19, LOW);<br>  digitalWrite(output21, LOW);</pre><pre>// Connect to Wi-Fi network with SSID and password<br>  Serial.print(&quot;Connecting to &quot;);<br>  Serial.println(ssid);<br>  WiFi.begin(ssid, password);<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  // Print local IP address and start web server<br>  Serial.println(&quot;&quot;);<br>  Serial.println(&quot;WiFi connected.&quot;);<br>  Serial.println(&quot;IP address: &quot;);<br>  Serial.println(WiFi.localIP());<br>  server.begin();<br>}</pre><pre>void loop(){<br>  WiFiClient client = server.available();   // Listen for incoming clients</pre><pre>if (client) {                             // If a new client connects,<br>    currentTime = millis();<br>    previousTime = currentTime;<br>    Serial.println(&quot;New Client.&quot;);          // print a message out in the serial port<br>    String currentLine = &quot;&quot;;                // make a String to hold incoming data from the client<br>    while (client.connected() &amp;&amp; currentTime - previousTime &lt;= timeoutTime) {  // loop while the client&#39;s connected<br>      currentTime = millis();<br>      if (client.available()) {             // if there&#39;s bytes to read from the client,<br>        char c = client.read();             // read a byte, then<br>        Serial.write(c);                    // print it out the serial monitor<br>        header += c;<br>        if (c == &#39;\n&#39;) {                    // if the byte is a newline character<br>          // if the current line is blank, you got two newline characters in a row.<br>          // that&#39;s the end of the client HTTP request, so send a response:<br>          if (currentLine.length() == 0) {<br>            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)<br>            // and a content-type so the client knows what&#39;s coming, then a blank line:<br>            client.println(&quot;HTTP/1.1 200 OK&quot;);<br>            client.println(&quot;Content-type:text/html&quot;);<br>            client.println(&quot;Connection: close&quot;);<br>            client.println();<br>            <br>            // turns the GPIOs on and off<br>            if (header.indexOf(&quot;GET /19/on&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 19on&quot;);<br>              output19State = &quot;on&quot;;<br>              digitalWrite(output19, HIGH);<br>            } else if (header.indexOf(&quot;GET /19/off&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 19off&quot;);<br>              output19State = &quot;off&quot;;<br>              digitalWrite(output19, LOW);<br>            } else if (header.indexOf(&quot;GET /21/on&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 21 on&quot;);<br>              output21State = &quot;on&quot;;<br>              digitalWrite(output21, HIGH);<br>            } else if (header.indexOf(&quot;GET /21/off&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 21 off&quot;);<br>              output21State = &quot;off&quot;;<br>              digitalWrite(output21, LOW);<br>            }<br>            <br>            // Display the HTML web page<br>            client.println(&quot;&lt;!DOCTYPE html&gt;&lt;html&gt;&quot;);<br>            client.println(&quot;&lt;head&gt;&lt;meta name=\&quot;viewport\&quot; content=\&quot;width=device-width, initial-scale=1\&quot;&gt;&quot;);<br>            client.println(&quot;&lt;link rel=\&quot;icon\&quot; href=\&quot;data:,\&quot;&gt;&quot;);<br>            // CSS to style the on/off buttons <br>            // Feel free to change the background-color and font-size attributes to fit your preferences<br>            client.println(&quot;&lt;style&gt;html { font-family: courier; display: inline-block; margin: 0px auto; text-align: center; color: white; background-color: black;}&quot;);<br>            client.println(&quot;.button { background-color: #45E6A3; border: none; color: black; padding: 16px 40px;&quot;);<br>            client.println(&quot;text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}&quot;);<br>            client.println(&quot;.button2 {background-color: #DEDEDE;}&lt;/style&gt;&lt;/head&gt;&quot;);<br>            <br>            // Web Page Heading<br>            client.println(&quot;&lt;body&gt;&lt;h1&gt;ESP32 Web Server&lt;/h1&gt;&quot;);<br>            <br>            // Display current state, and ON/OFF buttons for GPIO 19  <br>            client.println(&quot;&lt;p&gt;GPIO 19- State &quot; + output19State + &quot;&lt;/p&gt;&quot;);<br>            // If the output19State is off, it displays the ON button       <br>            if (output19State==&quot;off&quot;) {<br>              client.println(&quot;&lt;p&gt;&lt;a href=\&quot;/19/on\&quot;&gt;&lt;button class=\&quot;button\&quot;&gt;ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&quot;);<br>            } else {<br>              client.println(&quot;&lt;p&gt;&lt;a href=\&quot;/19/off\&quot;&gt;&lt;button class=\&quot;button button2\&quot;&gt;OFF&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&quot;);<br>            } <br>               <br>            // Display current state, and ON/OFF buttons for GPIO 21  <br>            client.println(&quot;&lt;p&gt;GPIO 21 - State &quot; + output21State + &quot;&lt;/p&gt;&quot;);<br>            // If the output21State is off, it displays the ON button       <br>            if (output21State==&quot;off&quot;) {<br>              client.println(&quot;&lt;p&gt;&lt;a href=\&quot;/21/on\&quot;&gt;&lt;button class=\&quot;button\&quot;&gt;ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&quot;);<br>            } else {<br>              client.println(&quot;&lt;p&gt;&lt;a href=\&quot;/21/off\&quot;&gt;&lt;button class=\&quot;button button2\&quot;&gt;OFF&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&quot;);<br>            }<br>            client.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;);<br>            <br>            // The HTTP response ends with another blank line<br>            client.println();<br>            // Break out of the while loop<br>            break;<br>          } else { // if you got a newline, then clear currentLine<br>            currentLine = &quot;&quot;;<br>          }<br>        } else if (c != &#39;\r&#39;) {  // if you got anything else but a carriage return character,<br>          currentLine += c;      // add it to the end of the currentLine<br>        }<br>      }<br>    }<br>    // Clear the header variable<br>    header = &quot;&quot;;<br>    // Close the connection<br>    client.stop();<br>    Serial.println(&quot;Client disconnected.&quot;);<br>    Serial.println(&quot;&quot;);<br>  }<br>}</pre><p>The part of the code we should modify are these:</p><pre>// Replace with your network credentials<br>const char* ssid     = &quot;REPLACE_WITH_YOUR_SSID&quot;;<br>const char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;</pre><p>To find your SSID, it’s pretty simple. In <strong>Windows</strong>, just click on the Wi-Fi icon located on the bottom right corner, and then click Properties on your network. For others like macOS, Android, and iOS, you may check this <a href="https://nordvpn.com/blog/what-is-ssid/">link</a>.</p><p>Next, we can upload the code. After that, when you see the dot, press the ESP32 button (reset) to connects with Wi-Fi and outputs the ESP32 IP address on the Serial Monitor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*FmQbRWj2YpsDkI5961Z-FA.png" /></figure><p>Then, open your browser, then copy your ESP32 IP address to the browser. In my case, it’s 192.168.43.248, and here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*yUlxTqaJ7xmqLkDVW_TMYA.png" /></figure><p>At the Serial Monitor in Arduino IDE, we can see what’s happening on the background. The ESP32 receives an HTTP request from a new client. In this case, the client is the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBKNU725SXkINSruaw26IA.png" /></figure><p>Also, you may see other information about the HTTP request.</p><h4>Testing the Web Server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*qGFE7M7NrMbQL8hxW8SPnQ.gif" /><figcaption>Turning on and off the LEDs</figcaption></figure><p>Fortunately, everything went well! When we press the ON button, it will turn on the corresponding LED with the GPIO that is written on the screen. Then, the state will change from off to on, and the ON button will change to OFF button.</p><h3>Code Explanation</h3><p>I would like to outline some parts of the code, especially the one that still new in our stories!</p><p>The following line is to include the WiFi library.</p><pre>#include &lt;WiFi.h&gt;</pre><p>This one set the web server to port 80.</p><pre>WiFiServer server(80);</pre><p>Next, this one creates a variable to store the header of the HTTP request</p><pre>String header;</pre><h4>setup() Section</h4><p>Next, we have the setup(). This one is to begin the Wi-Fi connection with WiFi.begin(ssid, password) function, wait for the successful connection and print the ESP IP address in the Serial Monitor.</p><pre>// Connect to Wi-Fi network with SSID and password<br>Serial.print(&quot;Connecting to &quot;);<br>Serial.println(ssid);<br>WiFi.begin(ssid, password);<br>while (WiFi.status() != WL_CONNECTED) {<br>  delay(500);<br>  Serial.print(&quot;.&quot;);<br>}<br>// Print local IP address and start web server<br>Serial.println(&quot;&quot;);<br>Serial.println(&quot;WiFi connected.&quot;);<br>Serial.println(&quot;IP address: &quot;);<br>Serial.println(WiFi.localIP());<br>server.begin();</pre><h4>loop() Section</h4><p>Then, we will have the loop() section. In short, we program what happens when a new client (in this case is browser) establishes a connection with the web server. Example: Control the outputs accordingly when the button is pressed on your web page.</p><p>We can make the ESP32always listening for incoming clients with the following line:</p><pre>WiFiClient client = server.available(); // Listen for incoming clients</pre><p>Keep in mind that you should only change this code if you know what you’re doing!</p><pre>void loop(){<br>  WiFiClient client = server.available();   // Listen for incoming clients</pre><pre>if (client) {                             // If a new client connects,<br>    currentTime = millis();<br>    previousTime = currentTime;<br>    Serial.println(&quot;New Client.&quot;);          // print a message out in the serial port<br>    String currentLine = &quot;&quot;;                // make a String to hold incoming data from the client<br>    while (client.connected() &amp;&amp; currentTime - previousTime &lt;= timeoutTime) {  // loop while the client&#39;s connected<br>      currentTime = millis();<br>      if (client.available()) {             // if there&#39;s bytes to read from the client,<br>        char c = client.read();             // read a byte, then<br>        Serial.write(c);                    // print it out the serial monitor<br>        header += c;<br>        if (c == &#39;\n&#39;) {                    // if the byte is a newline character<br>          // if the current line is blank, you got two newline characters in a row.<br>          // that&#39;s the end of the client HTTP request, so send a response:<br>          if (currentLine.length() == 0) {<br>            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)<br>            // and a content-type so the client knows what&#39;s coming, then a blank line:<br>            client.println(&quot;HTTP/1.1 200 OK&quot;);<br>            client.println(&quot;Content-type:text/html&quot;);<br>            client.println(&quot;Connection: close&quot;);<br>            client.println();<br>            <br>            // turns the GPIOs on and off<br>            if (header.indexOf(&quot;GET /19/on&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 19on&quot;);<br>              output19State = &quot;on&quot;;<br>              digitalWrite(output19, HIGH);<br>            } else if (header.indexOf(&quot;GET /19/off&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 19off&quot;);<br>              output19State = &quot;off&quot;;<br>              digitalWrite(output19, LOW);<br>            } else if (header.indexOf(&quot;GET /21/on&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 21 on&quot;);<br>              output21State = &quot;on&quot;;<br>              digitalWrite(output21, HIGH);<br>            } else if (header.indexOf(&quot;GET /21/off&quot;) &gt;= 0) {<br>              Serial.println(&quot;GPIO 21 off&quot;);<br>              output21State = &quot;off&quot;;<br>              digitalWrite(output21, LOW);<br>            }</pre><h4>HTML section</h4><p>Actually, this one is still in loop section, but I would like to differentiate it so it will be easier to be understood. I wouldn’t go into pretty detail for this one!</p><p>The following code is for styling the web page. Other than the GPIO that is used, I also modified this section from Rui Santos. But to be fair, my code is still pretty similar to it. But still, this is my own version and I’m pretty satisfied with it! TL;DR I made the dark mode of Rui Santos’s code with a different font type for the title. In short, what can we style from this code are the web page and the buttons appearances.</p><pre>// CSS to style the on/off buttons <br>            // Feel free to change the background-color and font-size attributes to fit your preferences<br>            client.println(&quot;&lt;style&gt;html { font-family: courier; display: inline-block; margin: 0px auto; text-align: center; color: white; background-color: black;}&quot;);<br>            client.println(&quot;.button { background-color: #45E6A3; border: none; color: black; padding: 16px 40px;&quot;);<br>            client.println(&quot;text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}&quot;);<br>            client.println(&quot;.button2 {background-color: #DEDEDE;}&lt;/style&gt;&lt;/head&gt;&quot;);</pre><p>To set the web page first heading, we use this line.</p><pre>// Web Page Heading<br>client.println(&quot;&lt;h1&gt;ESP32 Web Server&lt;/h1&gt;&quot;);</pre><p>Next, to display the buttons and corresponding state for GPIO 19, we use the following code.</p><pre>// Display current state, and ON/OFF buttons for GPIO 19  <br>            client.println(&quot;&lt;p&gt;GPIO 19- State &quot; + output19State + &quot;&lt;/p&gt;&quot;);<br>            // If the output19State is off, it displays the ON button       <br>            if (output19State==&quot;off&quot;) {<br>              client.println(&quot;&lt;p&gt;&lt;a href=\&quot;/19/on\&quot;&gt;&lt;button class=\&quot;button\&quot;&gt;ON&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&quot;);<br>            } else {<br>              client.println(&quot;&lt;p&gt;&lt;a href=\&quot;/19/off\&quot;&gt;&lt;button class=\&quot;button button2\&quot;&gt;OFF&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&quot;);<br>            }</pre><p>We use the same procedures for GPIO 21.</p><p>Last but not least, when the response ends, we clear the header variable, and stop the connection with the client (browser) with client.stop()</p><pre>// Clear the header variable<br>header = &quot;&quot;;<br>// Close the connection<br>client.stop();</pre><h4>Final Thought</h4><p>In conclusion, with the ESP32 web server, we can do many things like turning on/off LEDs by clicking the button on the web server. It seems that our story is already ended, I hope that my story can bring you guys more inspiration to learn more about technology, especially embedded systems. See you guys in the next story and don’t forget to keep learning! Have fun guys!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=669000c385e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ESP32 Bluetooth with Android]]></title>
            <link>https://fernaldifz.medium.com/esp32-bluetooth-with-android-6e4225ae7635?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e4225ae7635</guid>
            <category><![CDATA[bluetooth]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 14:24:42 GMT</pubDate>
            <atom:updated>2021-03-31T12:09:58.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embedded System Project 7: ESP32 Bluetooth with Android</h3><p>Alright! This time, just like the title of this story, we will do experimentation with ESP32 Bluetooth. More precisely, we will try to exchange data between ESP32 and an <strong>Android smartphone</strong>. We will try many things, like sending data from BMP280 sensor to Android smartphone, turning on/off led by using the message from Android smartphone, or greet the ESP32 with Android smartphone (although this one is actually pretty simple)</p><h4>Bluetooth?</h4><p>In short, Bluetooth is a wireless technology Personal Area Network (PAN) standard used for exchanging data between fixed and mobile devices over short distances. For your information, Bluetooth operates in the 2.4 GHz band.</p><h4>Let’s Start!</h4><p>For this story, I’m using this <a href="https://randomnerdtutorials.com/esp32-bluetooth-classic-arduino-ide/">randomnerdtutorials</a> link as a reference!</p><p>In this story, we will need:</p><ul><li>ESP32</li><li>Micro USB cable</li><li>Breadboard</li><li>Android smartphone</li><li>LED</li><li>330 Ohm resistor</li><li>BMP280 sensor</li></ul><p>We need a Bluetooth Terminal application installed on our Android smartphone. To make it easy, I recommend this <strong>Serial Bluetooth Terminal</strong> application that available in the Play Store</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jmqh6WckWlSVDXSyq7UskA.jpeg" /></figure><p>Before we continue, we have to assemble the circuit by following the next schematic diagram.</p><p>Connect an LED to GPIO17, BMP280 VCC to ESP32 3V3, BMP280 GND to ESP32 GND, BMP280 SCL to GPIO22, and BMP280 SDA to GPIO21.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*6qT8R7gZisRrmMUQEm-YGg.png" /><figcaption>Schematic Diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWVUbk4jNEV4a11maarMIg.jpeg" /><figcaption>My Simple Circuit</figcaption></figure><p>Next, we have to use this code to make use of ESP32 Bluetooth and Android’s Bluetooth:</p><pre>// Load libraries<br>#include &quot;BluetoothSerial.h&quot;<br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_BMP280.h&gt;</pre><pre>// Check if Bluetooth configs are enabled<br>#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)<br>#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it<br>#endif</pre><pre>// Bluetooth Serial object<br>BluetoothSerial SerialBT;</pre><pre>// GPIO where LED is connected to<br>const int ledPin =  17;</pre><pre>Adafruit_BMP280 bmp; // I2C<br>//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI<br>//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);</pre><pre>// Handle received and sent messages<br>String message = &quot;&quot;;<br>char incomingChar;<br>String temperatureString = &quot;&quot;;</pre><pre>// Timer: auxiliar variables<br>unsigned long previousMillis = 0;    // Stores last time temperature was published<br>const long interval = 10000;         // interval at which to publish sensor readings</pre><pre>void setup() {<br>  pinMode(ledPin, OUTPUT);<br>  Serial.begin(115200);<br>  // Bluetooth device name<br>  SerialBT.begin(&quot;ESP32&quot;);<br>  Serial.println(&quot;The device started, now you can pair it with bluetooth!&quot;);</pre><pre>if (!bmp.begin(0x76)) {<br>    Serial.println(F(&quot;Could not find a valid BMP280 sensor, check wiring!&quot;));<br>    while (1);<br>  }</pre><pre>/* Default settings from datasheet. */<br>  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */<br>                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */<br>                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */<br>                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */<br>                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */<br>}</pre><pre>void loop() {<br>  unsigned long currentMillis = millis();<br>  // Send temperature readings<br>  if (currentMillis - previousMillis &gt;= interval){<br>    previousMillis = currentMillis;</pre><pre>SerialBT.print(F(&quot;Temperature = &quot;));<br>    SerialBT.print(bmp.readTemperature());<br>    SerialBT.print(&quot; *C\n&quot;);</pre><pre>SerialBT.print(F(&quot;Pressure = &quot;));<br>    SerialBT.print(bmp.readPressure());<br>    SerialBT.print(&quot; Pa\n&quot;);</pre><pre>SerialBT.print(F(&quot;Approx altitude = &quot;));<br>    SerialBT.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */<br>    SerialBT.print(&quot; m\n&quot;);<br>  }<br>  // Read received messages<br>  if (SerialBT.available()){<br>    char incomingChar = SerialBT.read();<br>    if (incomingChar != &#39;\n&#39;){<br>      message += String(incomingChar);<br>    }<br>    else{<br>      message = &quot;&quot;;<br>    }<br>    Serial.write(incomingChar);  <br>  }<br>  // Check received message and control output accordingly<br>  if (message ==&quot;led_on&quot;){<br>    digitalWrite(ledPin, HIGH);<br>  }<br>  else if (message ==&quot;led_off&quot;){<br>    digitalWrite(ledPin, LOW);<br>  }<br>  else if (message ==&quot;hello&quot;){<br>    SerialBT.print(&quot;hello, Fernaldi!&quot;);  <br>  }<br>  delay(20);<br>}</pre><p>In short, here is the steps to use Serial Bluetooth Terminal:</p><ul><li>Turn on your smartphone’s Bluetooth. Then, open Serial Bluetooth Terminal application</li><li>Go to Devices</li><li>Click the settings icon, then select <strong>Pair new device</strong>. Pair with ESP32</li><li>Finally, go back to Terminal</li></ul><p>Also, I would like to point out some parts of the code, like:</p><pre>// Bluetooth Serial object<br>BluetoothSerial SerialBT;</pre><p>This code is to create an instance of BluetoothSerial called SerialBT:</p><pre>SerialBT.begin(&quot;ESP32&quot;); //Bluetooth device name</pre><p>Initialize the ESP32 as a Bluetooth device with the name of “ESP32”</p><pre>SerialBT.print(F(&quot;Temperature = &quot;));<br>    SerialBT.print(bmp.readTemperature());<br>    SerialBT.print(&quot; *C\n&quot;);</pre><pre>SerialBT.print(F(&quot;Pressure = &quot;));<br>    SerialBT.print(bmp.readPressure());<br>    SerialBT.print(&quot; Pa\n&quot;);</pre><pre>SerialBT.print(F(&quot;Approx altitude = &quot;));<br>    SerialBT.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */<br>    SerialBT.print(&quot; m\n&quot;);<br>  }</pre><p>I think this one actually pretty straightforward. So this is the code to send the temperature, pressure, and approximate altitude using sea-level pressure (1013.25 mbar) to the Android smartphone.</p><pre>// Read received messages<br>  if (SerialBT.available()){<br>    char incomingChar = SerialBT.read();<br>    if (incomingChar != &#39;\n&#39;){<br>      message += String(incomingChar);<br>    }<br>    else{<br>      message = &quot;&quot;;<br>    }<br>    Serial.write(incomingChar);  <br>  }</pre><p>This one is to read received messages, so that we know what is the purpose of the messages, like turning on/off LED or a greeting!</p><pre>// Check received message and control output accordingly<br>  if (message ==&quot;led_on&quot;){<br>    digitalWrite(ledPin, HIGH);<br>  }<br>  else if (message ==&quot;led_off&quot;){<br>    digitalWrite(ledPin, LOW);<br>  }<br>  else if (message =&quot;hi&quot;){<br>    SerialBT.print(&quot;hi, Fernaldi!&quot;);  <br>  }<br>  delay(20);</pre><p>This one is to check the received message and control output accordingly. If the message is “led_on”, turn on the LED. Else if the message is “led_off”, turn off the LED. Else if the message is “hi”, send greeting “hi, Fernaldi!”.</p><h4>Now, It’s Time to Have Fun!</h4><p>After connecting the Android with ESP32, we can get temperature, pressure, and approximate altitude from ESP32!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*IDA4VmJPzukZDvFbYltlig.gif" /><figcaption>Temperature, Pressure, and Approximate Altitude</figcaption></figure><p>Next, we can send a greeting (“hello”) to ESP32. ESP32 will send the message “hello, Fernaldi” as the result!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*fXIgjiEBXd1esIXjPQPjnA.gif" /><figcaption>Greet the ESP32</figcaption></figure><p>The “hello” message from Android Smartphone can be seen in the serial monitor in Arduino IDE. Just make sure that you use the correct baud (in my case it’s 115200 baud) so that we can get the accurate message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*PrV5qsCqtI1OWSHOsLOvQg.png" /></figure><p>We can also turn on LED with sending “led_on” message and turn off LED with sending “led_off” message!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*m_GeVw6GNeX3zpa4h2s1NA.gif" /><figcaption>Turn On and Off the LED</figcaption></figure><p>In conclusion, by using ESP32 Bluetooth, we can do many things with the help of an Android smartphone, like send the BMP280 sensor reading to an Android smartphone, or turn on/off an LED with a message from an Android smartphone. Moreover, we also can do simple chatting with Serial Bluetooth Terminal application (Android smartphone) with the serial monitor in Arduino IDE (PC) and make ESP32 respond to some specific message like “hello”.</p><p>It seems that our story has come to the end. I hope that this story can be informative to you guys. Remember to stay curious because there are still many things in ESP32 that we can explore! See you guys in the next story! Good luck and don’t forget to have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e4225ae7635" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded System Project 6: ESP32 I2C Communication]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-6-esp32-i2c-communication-41d4bec3ab?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d4bec3ab</guid>
            <category><![CDATA[bmp280]]></category>
            <category><![CDATA[oled]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 14:51:08 GMT</pubDate>
            <atom:updated>2021-03-05T16:13:53.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Yay! This time, we will go further in experimenting with ESP32! More precisely, this time we will combine project 4 which is about ESP32 external sensor with project 5 which is about OLED display with ESP32! What does that mean? It means we will try to get sensor readings from BMP280 sensor (via I2C) and displays the results on an I2C OLED display!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIL8-sC50FdRYj0k3OB7IA.jpeg" /><figcaption>My Simple Circuit</figcaption></figure><h3>Let’s Begin!</h3><p>Oh wait, before we go further, I would like to tell you guys that for this project I am using this <a href="https://randomnerdtutorials.com/esp32-i2c-communication-arduino-ide/">randomnerdtutorials </a>link as reference! Although, I will use BMP280 instead of BME280!</p><p>In this project, we will use:</p><ul><li>ESP32 Board</li><li>BMP280 sensor</li><li>0.96 inch OLED display</li><li>8 male to male jumper wires</li><li>Micro USB cable</li><li>Breadboard</li></ul><p>Keep in mind that, every I2C device has its own address, so it’s possible to have multiple I2C devices on the same bus. This time, because we will experimenting with BMP280 sensor with OLED display, although it’s in same bus, it’s different address.</p><p>To set it up, we have to:</p><ul><li>Connect both peripherals to the ESP32 <strong>GPIO 22 (SCL)</strong> and <strong>GPIO 21 (SDA)</strong></li><li>In the code, we should refer to each peripheral by its address</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9BJcEn7w7h4SKaFIFbRtA.png" /></figure><p>Unfortunately, I can’t find BMP280 with 6 pins with fritzing, so in my schematic diagram its pin are 4 instead of 6, but actually there is no major problem since all of 4 pins are available in BMP280 with 6 pins!</p><p>My schematic diagram is pretty similar with schematic diagram in this <a href="https://randomnerdtutorials.com/esp32-i2c-communication-arduino-ide/">randomnerdtutorials</a>, but here it’s BMP280 instead of BME280 and also some differences in wiring.</p><p>For the code, I’m using this <a href="https://randomnerdtutorials.com/guide-for-oled-display-with-arduino/">randomnerdtutorials</a> as reference!</p><pre>/*********<br>  Another Version of Rui Santos<br>*********/<br>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_GFX.h&gt;<br>#include &lt;Adafruit_SSD1306.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BMP280.h&gt;<br>#define SCREEN_WIDTH 128 // OLED display width, in pixels<br>#define SCREEN_HEIGHT 64 // OLED display height, in pixels<br>// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)<br>Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, -1);<br>Adafruit_BMP280 bmp; // I2C<br>void setup() {<br>  Serial.begin(115200);<br>  bmp.begin(0x76); // Initialize I2C address of BMP280<br>  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {<br>    Serial.println(F(&quot;SSD1306 allocation failed&quot;));<br>    for(;;);<br>  }<br>  delay(2000);<br>  display.clearDisplay();<br>  display.setTextColor(WHITE);<br>}<br>void loop() {<br>  delay(3000);<br>  <br>  //read temperature and pressure<br>  float t = bmp.readTemperature();<br>  float p = bmp.readPressure();<br>  if (isnan(p) || isnan(t)){<br>    Serial.println(&quot;Failed to read from bmp sensor!&quot;);<br>  }<br>  <br>  // clear display<br>  display.clearDisplay();<br>  <br>  // display temperature<br>  display.setTextSize(1);<br>  display.setCursor(0,0);<br>  display.print(&quot;Temperature: &quot;);<br>  display.setTextSize(2);<br>  display.setCursor(0,10);<br>  display.print(t);<br>  display.print(&quot; &quot;);<br>  display.setTextSize(1);<br>  display.cp437(true);<br>  display.write(167);<br>  display.setTextSize(2);<br>  display.print(&quot;C&quot;);<br>  <br>  // display pressure<br>  display.setTextSize(1);<br>  display.setCursor(0, 35);<br>  display.print(&quot;Pressure: &quot;);<br>  display.setTextSize(2);<br>  display.setCursor(0, 45);<br>  display.print(p/1000);<br>  display.print(&quot; kPa&quot;); <br>  <br>  display.display(); <br>}</pre><h4>The Result?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*Tlqw5LKRgNydjseRV-hNbA.gif" /><figcaption>My Experimentation</figcaption></figure><p>Fortunately, it seems that my BMP280 and OLED can work well! Since the temperature that can be seen on OLED changed from 30.76 °C to 32.50 °C if I touch the BMP280 with my bare hand.</p><h4>OLED is Displaying 0 °C and 0 kPa?</h4><p>Probably some of you guys will experience this problem that happened before. First of all, you should try to troubleshooting 1 by 1, which means try to troubleshooting the BMP280 alone, then the OLED alone, the jumper wires alone, then the ESP32 alone!</p><p>In my case, apparently the problem is because BMP280 I2C address can’t be found! Thankfully, it can be solved by fixing the wiring, because apparently I followed wrong reference in wiring because that reference is for <strong>BME280</strong>, not <strong>BMP280</strong>. Actually, I realized before that it’s BME280 instead of BMP280 but I thought that there is no difference in wiring (which is actually different).</p><h4>Yay! We did it!</h4><p>In conclusion, because the BMP280 and the OLED have different addresses, we can use the same <strong>GPIO 22 (SCL)</strong> and <strong>GPIO 21 (SDA)</strong> without any problem (same bus, different addresses). With this, we can get sensor readings from BMP280 sensor (via I2C) and displays the results on an I2C OLED display just like we did before!</p><p>That’s all about this ESP32 I2C Communication story. At the end, I hope this blog can help you guys that reading this to give more inspiration and insight. Have fun and see you in the next story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d4bec3ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded System Project 5 : OLED Display With ESP32]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-5-oled-display-with-esp32-eba09bf64fe1?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba09bf64fe1</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[oled]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 13:27:12 GMT</pubDate>
            <atom:updated>2021-03-31T12:09:06.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embedded System Project 5: OLED Display With ESP32</h3><h4>Wait What?! My ESP32 says “Hello, World!”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RonhaPUjGmv3Mf3jYSe-Q.jpeg" /></figure><p>This time we are going to play with external display with <strong>OLED</strong>. With this, we don’t have to depends on PC to do some reading, so that we can be more flexible!</p><p>First, let me explain about external display. Actually, there are many external displays that we can use, but this time I want to make it simple so I will only explain in short about 2 external display, which is LCD and OLED.</p><p>The LCD that I meant before is 16×2 I2C Liquid Crystal Display (although size shouldn’t be really matters), while the OLED that I meant is 0.96 inch Organic Light Emitting Diode Display. In short, their <strong>notable differences</strong> are LCD is heavier, having more components, and cheaper if compared to OLED. For your information, LCD costs around IDR 20k while OLED costs around IDR 50k (luckily I bought mine for IDR 44k). Unfortunately, LCD can’t output the display as sharp as OLED, but I believe that the output is still readable which means it is fine.</p><h4>I2C? What’s That?</h4><p>I hope that it’s not too late to explain about I2C. <strong>I2C (Inter Integrated Circuit)</strong> is <strong>synchronous, multi-master, multi-slave communication protocol</strong> to ease the communication between the components. In this case, I2C will ease the communication between our PC with LCD/OLED. What does it mean? To make it more understandable, I will take the example of using LCD as external display. 16x2 LCD has 16 pins, so to make it runs, actually we have to use all of its pins. But, with I2C we can make it works by only using 4 pins instead of 16 pins.</p><p>As usual, we will use <a href="https://randomnerdtutorials.com/esp32-ssd1306-oled-display-arduino-ide/">https://randomnerdtutorials.com/esp32-ssd1306-oled-display-arduino-ide/</a> as reference, but of course we will make our own version!</p><h4>Let’s Start!</h4><p>For this project, we will need:</p><ul><li>ESP32 Board</li><li>0.96 inch OLED display</li><li>USB cable to connects ESP32 with PC</li><li>Jumper wires (I am using 4 male to male jumper wires)</li><li>Breadboard</li></ul><p>As we know, OLED display uses I2C communication protocol, so wiring is pretty simple. You may look at my schematic diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*KRrpWGnMrXtL0V0Qd2692g.png" /><figcaption>Source : <a href="https://randomnerdtutorials.com/esp32-ssd1306-oled-display-arduino-ide/">https://randomnerdtutorials.com/esp32-ssd1306-oled-display-arduino-ide/</a></figcaption></figure><p>Friendly reminder that in this example, we will use I2C communication protocol instead of SPI communication protocol. For your information, the most suitable pins for <strong>I2C communication</strong> in the ESP32 are <strong>GPIO 22 (SCL)</strong> and <strong>GPIO 21 (SDA)</strong>.</p><h3>Installing Library — ESP32</h3><p>We need to install 2 library, which is Adafruit_SSD1306 library and Adafruit_GFX library. You may follow these steps below to install the library.</p><ul><li>In your Arduino IDE, Sketch &gt; Include Library &gt; Manage Libraries</li><li>Type “<strong>Adafruit SSD1306</strong>” in the search box and then install the SSD1306 library from Adafruit</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3d3f0xk2CTJR2_S_6c1McA.png" /></figure><ul><li>After you are done, type “<strong>Adafruit GFX</strong>” in the search box and install the library</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKS3uN16SYkl_c05R552TA.png" /></figure><ul><li>Next, type “<strong>Adafruit BusIO</strong>” in the search box and install the library</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nza_55YyB9wjVA0yVx-Ycg.png" /></figure><ul><li>After installing the libraries, restart the Arduino IDE</li></ul><p>Finally, we are done with libraries, which means we can do the real fun! In your Arduino IDE, go to File &gt; Examples &gt; Adafruit SSD1306 and then select the example for the display you’re using. In my case, I pick “ssd1306_128x64_i2c”.</p><p>After it, the following <a href="https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/OLED/oled_adafruit_demo.ino"><strong>code</strong></a> should load. It’s pretty long code so I decided to make it in link instead of directly raw code in this medium article! In short, this code is an example of monochrome OLED based on SSD1306 drivers, made by Adafruit.</p><p>Before we continue, you should check your OLED. If your OLED doesn’t have a RESET pin, you should set the OLED_RESET variable to -1 as shown below:</p><pre>#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q20CbCHtki9Qqu-Sd5MgxA.png" /></figure><p>Next, you should change the OLED address if necessary in the following line. You can check what is your OLED address with this <a href="https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/LCD_I2C/I2C_Scanner.ino"><strong>code</strong></a>. In our case, the address is 0x3C.</p><pre>#define SCREEN_ADDRESS 0x3C</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sxoXhMCApvy1sIY5UwRKA.png" /></figure><h4>Result?</h4><p>Fortunately, it seems that it can works really well!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*bMQco0wMxZbUB8Aj5DPMQQ.gif" /></figure><h3>Now It’s Time To Make Our Version!</h3><p>Let’s start with the simple one, which of course “Hello, world!”. But this time, I add more text which is “Good bye!” below “Hello, world!”.</p><pre>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_GFX.h&gt;<br>#include &lt;Adafruit_SSD1306.h&gt;</pre><pre>#define SCREEN_WIDTH 128 // OLED display width, in pixels<br>#define SCREEN_HEIGHT 64 // OLED display height, in pixels<br>#define SCREEN_ADDRESS 0x3C // Address 0x3D for 128x64</pre><pre>// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)<br>Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, -1);</pre><pre>void setup() {<br>  Serial.begin(115200);</pre><pre>if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {<br>    Serial.println(F(&quot;SSD1306 allocation failed&quot;));<br>    for(;;);<br>  }<br>  delay(2000);<br>  display.clearDisplay();               // Clear display buffer<br>  display.setTextSize(1.5);             // Set text size<br>  display.setTextColor(WHITE);          // Set text color<br>  display.setCursor(5, 5);              // Define position<br>  display.println(&quot;Hello, world!&quot;);     // Display static text<br>  display.setCursor(5, 18);      <br>  display.println(&quot;Good bye!&quot;);  <br>  display.drawRect(0, 0, 90, 30, WHITE);// Draw rectangle<br>  display.display();                    // Display the text and shape on the screen<br>}</pre><pre>void loop() {<br>  <br>}</pre><p>In short, after initializing the display, it’s better to add a two second delay, so that the OLED has enough time to initialize before writing text, then clear the display buffer with the <strong>clearDisplay()</strong> method. Next, we need to set the text size with <strong>setTextSize(size)</strong> method, the text color with <strong>setTextColor(color)</strong> method. Then, we can define position with<strong> setCursor(x, y)</strong> method. After that, draw the rectangle with <strong>drawRect(x, y, width, height, color)</strong> method. In this case, the (x, y) coordinates indicate the top left corner of the rectangle. Finally, we can send the text to the display using <strong>println()</strong> method, then call the <strong>display()</strong> method to actually display the text and shape on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dr5ZQrkcwMvQ5F6HvJ99Qw.jpeg" /><figcaption>My experiment</figcaption></figure><p>Wait what?! How can we have :</p><pre>display.setTextColor(WHITE);</pre><p>While as we can see in the demo, the color are yellow and blue?</p><p>No worries! Actually, that happened because actually my OLED is Yellow-Blue I2C OLED. In normal cases, the color would be white instead of yellow and blue!</p><p>To conclude, OLED display can be used to write text, draw shape, and even display bitmap images with Arduino IDE software and ESP32. I’d like to notify you that the OLED display doesn’t require backlight, which results in a pretty nice contrast in dark environments. Moreover, its pixels will only consume energy when they are on, so the OLED display consumes less power when compared with other displays.</p><p>That’s all for this story about external OLED display. I hope that this story can give you guys who is reading this more inspiration to keep exploring your idea and knowledge. There are still many ESP32 features that can be explored, stay curious and see you in the next story! Good bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba09bf64fe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded System Project 4 : ESP32 External Sensor]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-4-esp32-external-sensor-f6f4974aab1b?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f4974aab1b</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[bmp280]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 17:12:41 GMT</pubDate>
            <atom:updated>2021-03-31T12:08:13.354Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embedded System Project 4: ESP32 External Sensor</h3><p>Alright! Again, we will play with sensor, but this time, not internal sensor from ESP32 itself but <strong>external sensor</strong> instead! I feel like this project will bring much insights to me because if I can make us of many external sensors well, I think it will bring me to many possibilities which make me pretty excited! Isn’t that pretty interesting?</p><p>First, I would like to explain about my sensor that will be used in this project. Although I bought it from online shop in the name of <strong>BME280</strong>, when I checked the pin, its pins are not VCC, GND, SDI, SCK, CSB, SDO which should be it if my sensor is BME-280 (based on <a href="https://randomnerdtutorials.com/esp32-bme280-arduino-ide-pressure-temperature-humidity/">reference</a> that my lecture gave). Also, it isn’t <strong>BMP180</strong> as mine has 6 pins instead of 4 pins. So, I tried to discuss it with my System Embedded Assistant, which lead me to conclusion that my sensor is <strong>BMP280</strong>, as its pins are VCC, GND, SCL, SDA, CSB and SDO.</p><p>So, in this project I would like to make use of <strong>BMP280</strong> sensor to read temperature, pressure and estimate altitude using <strong>Arduino IDE</strong> software. This sensor connects directly to a microcontroller via <strong>I2C or SPI</strong>.</p><h4>What are we waiting for? Let’s get started!</h4><p>For this project, I am using this <a href="https://www.circuitschools.com/interfacing-bmp280-with-esp-32-on-i2c-with-errors-and-solutions/">circuitschools.com</a> as reference! Of course, we will make it with our own version!</p><p>First, we need these components :</p><ul><li>ESP32 Development Board</li><li>BMP280 sensor</li><li>Some jumper wires (I’m using male to male)</li><li>Micro USB cable</li><li>Breadboard</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2znRKC-eoQ4nrdhivPAfw.png" /><figcaption>Schematic Diagram</figcaption></figure><p>So I tried to make my own schematic diagram. Unfortunately, I couldn’t find the exact sensor I used which is BMP280 that has 6 pins (as there are only 4 pins in schematic diagram). But actually there is no serious matter with it, because in general they are actually same as I only use 4 from 6 pins which all of them are available in that sensor in schematic diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*BaFU6ZOCC1MxTZYu7Q8dzQ.png" /><figcaption>Schematic diagram from <a href="https://www.circuitschools.com/interfacing-bmp280-with-esp-32-on-i2c-with-errors-and-solutions/">https://www.circuitschools.com/interfacing-bmp280-with-esp-32-on-i2c-with-errors-and-solutions/</a></figcaption></figure><p>Next, let’s start with the code that we may get from File &gt; Examples &gt; BMP 280 library. If you don’t find it in your Arduino IDE, you need to download and install, Adafruit BMP280 library, which can be achieved by</p><ul><li>Sketch &gt; Include Library &gt; Manage Libraries…</li><li>Search for “Adafruit BMP280 Library”</li><li>Click install</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kyn005JzhCE5oXXgYaqrOQ.png" /></figure><ul><li>If you haven’t install Adafruit Unified Sensor Library, install it by pressing “Install all”!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ezp6MK_PzWC3vb3cHrcAsw.png" /></figure><p>Finally, we have the code that we can access from File &gt; Examples &gt; Adafruit BMP280 Library &gt; bmp280test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57zU0QBnKBkV887XH-goXA.png" /></figure><p>But we are not done yet! Next, we need to look for the I2C address of BMP280 so that we can add it to the code to make it works! We have to change <strong>if (!bmp.begin())</strong> to <strong>if (!bmp.begin(&lt;I2C address&gt;))</strong>. To get the I2C address, I am using this <a href="https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/LCD_I2C/I2C_Scanner.ino"><strong>code</strong></a> from randomnerdtutorials.</p><pre>/*********<br>  Rui Santos<br>  Complete project details at <a href="https://randomnerdtutorials.com/">https://randomnerdtutorials.com</a>  <br>*********/</pre><pre>#include &lt;Wire.h&gt;<br> <br>void setup() {<br>  Wire.begin();<br>  Serial.begin(115200);<br>  Serial.println(&quot;\nI2C Scanner&quot;);<br>}<br> <br>void loop() {<br>  byte error, address;<br>  int nDevices;<br>  Serial.println(&quot;Scanning...&quot;);<br>  nDevices = 0;<br>  for(address = 1; address &lt; 127; address++ ) {<br>    Wire.beginTransmission(address);<br>    error = Wire.endTransmission();<br>    if (error == 0) {<br>      Serial.print(&quot;I2C device found at address 0x&quot;);<br>      if (address&lt;16) {<br>        Serial.print(&quot;0&quot;);<br>      }<br>      Serial.println(address,HEX);<br>      nDevices++;<br>    }<br>    else if (error==4) {<br>      Serial.print(&quot;Unknow error at address 0x&quot;);<br>      if (address&lt;16) {<br>        Serial.print(&quot;0&quot;);<br>      }<br>      Serial.println(address,HEX);<br>    }    <br>  }<br>  if (nDevices == 0) {<br>    Serial.println(&quot;No I2C devices found\n&quot;);<br>  }<br>  else {<br>    Serial.println(&quot;done\n&quot;);<br>  }<br>  delay(5000);          <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*3lpx0V39XtLZ5uWMdBk3WQ.png" /><figcaption>Result</figcaption></figure><p>With this, we know that I2C device found at address 0x76. Finally, we can finish our code. As I get 0x76 as the result, our last code would be seen like this :</p><pre>/***************************************************************************<br>  This is a library for the BMP280 humidity, temperature &amp; pressure sensor</pre><pre>Designed specifically to work with the Adafruit BMP280 Breakout<br>  ----&gt; <a href="http://www.adafruit.com/products/2651">http://www.adafruit.com/products/2651</a></pre><pre>These sensors use I2C or SPI to communicate, 2 or 4 pins are required<br>  to interface.</pre><pre>Adafruit invests time and resources providing this open source code,<br>  please support Adafruit andopen-source hardware by purchasing products<br>  from Adafruit!</pre><pre>Written by Limor Fried &amp; Kevin Townsend for Adafruit Industries.<br>  BSD license, all text above must be included in any redistribution<br> ***************************************************************************/</pre><pre>#include &lt;Wire.h&gt;<br>#include &lt;SPI.h&gt;<br>#include &lt;Adafruit_BMP280.h&gt;</pre><pre>#define BMP_SCK  (13)<br>#define BMP_MISO (12)<br>#define BMP_MOSI (11)<br>#define BMP_CS   (10)</pre><pre>Adafruit_BMP280 bmp; // I2C<br>//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI<br>//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);</pre><pre>void setup() {<br>  Serial.begin(9600);<br>  Serial.println(F(&quot;BMP280 test&quot;));</pre><pre>if (!bmp.begin(0x76)) {<br>    Serial.println(F(&quot;Could not find a valid BMP280 sensor, check wiring!&quot;));<br>    while (1);<br>  }</pre><pre>/* Default settings from datasheet. */<br>  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */<br>                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */<br>                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */<br>                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */<br>                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */<br>}</pre><pre>void loop() {<br>    Serial.print(F(&quot;Temperature = &quot;));<br>    Serial.print(bmp.readTemperature());<br>    Serial.println(&quot; *C&quot;);</pre><pre>Serial.print(F(&quot;Pressure = &quot;));<br>    Serial.print(bmp.readPressure());<br>    Serial.println(&quot; Pa&quot;);</pre><pre>Serial.print(F(&quot;Approx altitude = &quot;));<br>    Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */<br>    Serial.println(&quot; m&quot;);</pre><pre>Serial.println();<br>    delay(2000);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXEagWm263Z6PYj1yuIRyw.jpeg" /><figcaption>My ESP32 connected with BMP280</figcaption></figure><p>Finally, we can start the the experiment!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP8pZBttnhv5dxvR1WbfBA.png" /><figcaption>Result</figcaption></figure><p>It seems that my BMP280 is working, because its temperature increase as I am touching it with my hand. (26.78 C to 28.23 C).</p><p>So, after that I try to do another testing, but this time I make it in gif! Seems like this time my body temperature is not really hot so the difference not really big this time (only from around 27.07 C to 27.31 C)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*GfPXY7WIc6CI1jiOvS2DNw.gif" /><figcaption>Result in live version</figcaption></figure><p>For your information, if you find the error “Could not find a valid BMP280 sensor, check wiring!”, that means you forgot to add the I2C address of BMP280 to the code. Mine is 0x76 so I made the <strong>if (!bmp.begin())</strong> to <strong>if (!bmp.begin(0x76))</strong>. This is important!</p><p>In conclusion, we can use BMP280 as external sensor to read temperature, pressure and estimate altitude using <strong>Arduino IDE</strong> software. I2C address of BMP280 is required to make BMP280 works as intended. We can see the result from serial monitor in Arduino IDE.</p><p>I think, that will end my story about BMP280, the external sensor which is used to read temperature, pressure, and estimate altitude. I hope that this experience can give you guys inspiration, knowledge, and insight! There are still many opportunities and chances from ESP32 that can be explored. Make sure to keep curious and see you in the next story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f4974aab1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded System Project 3 : ESP32 Internal Sensor]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-3-esp32-internal-sensor-468dbb7864d3?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/468dbb7864d3</guid>
            <category><![CDATA[sensors]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 04:45:35 GMT</pubDate>
            <atom:updated>2021-03-31T12:07:22.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embedded System Project 3: ESP32 Internal Sensor</h3><p>This time, I would like to share about my experience with ESP32 sensor which is internal sensor! (not external sensor). Right now, I am pretty curious to try 3 built-in sensor in ESP32, which is touch sensor, hall effect sensor, and temperature sensor (or maybe just 2 built-in sensor because I heard from my lecture that not all ESP32 has built-in temperature sensor, personally I haven’t try it myself so I can’t say for sure).</p><p>What are we waiting for?! Now let’s check it out!</p><h4>Touch Sensor</h4><p>I am intrigued to try using ESP32 touch pins with Arduino IDE. For your information, the ESP32 touch pins can sense variations in anything as long it holds an electric charge. Before we start, this is the list of component and device I used:</p><ul><li>ESP32 Development Board</li><li>5mm LEDs (2)</li><li>330 Ohm resistors (2)</li><li>Male to male jumper wires (4)</li><li>Breadboard</li><li>Micro USB cable</li></ul><p>Now I am done with all component and device that I need to prepare, it’s time to start working in making the electric circuit. You guys may want to see my electric circuit by looking at my schematic diagram below!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*Jh67Z3KGb2_le9ErKL8_PA.png" /><figcaption>Touch Sensor Schematic Diagram</figcaption></figure><p>As you can see, I am using 2 LEDs. Similar with my project before, I want that my circuit will blink if I touch my touch sensor, while nothing will happen if I don’t touch my touch sensor, so of course at least 2 LEDs is needed.</p><p>I am done with the circuit, now how about the code? No worries! This is my code that I use for this touch sensor project. Please be careful with which pin you can use as capacitive touch GPIO, personally I use pin number 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*sxjuQl_G3JG2pxDej6fTPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*GDwhElgfDOLU47AwM4X2cg.png" /></figure><p>I would say the key of this code is touchValue and threshold. In short, if my touchValue from touchRead(touchPin) is less than the threshold that I put, my LEDs will blink, while if touchValue is more than threshold, turn LED off. While doing this project, you may see the value of touchValue at serial monitor in Arduino IDE which can be opened with 2 alternatives :</p><ul><li>Tools &gt; Serial Monitor (Ctrl + Shift + M), or</li><li>Tools &gt; Serial Plotter (Ctrl + Shift + L)</li></ul><p>And now here how it’s done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eIUPTK7g-OkdUTHsQla2A.jpeg" /><figcaption>My Pretty Simple Circuit For Touch Sensor Experiment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*F6zMXrXpJ32r7pC3bSkwoQ.gif" /><figcaption>First Touch Sensor Demo, Touching The Jumper Wires to Make The LEDs Blink</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*wooxPqX846LSoYRhmB1-og.gif" /><figcaption>Second Touch Sensor Demo, Releasing The Jumper Wire to Turn Off LEDs</figcaption></figure><p>It seems like if I touch the male to male jumper wire that is used as touch sensor, the value read by sensor drops (as can be seen from the gif above). With this, I can make use of it and threshold value to make something works! (Example : do LEDs blink)</p><p>For those wondering what serial plotter looked like (as I am using serial monitor above as you guys can see at my gif), here it is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*A-x1X4sCng15DIJ0QRUJig.png" /><figcaption>Example of Serial Plotter View</figcaption></figure><p>To get the result as same as mine, make sure you use the right baud at the serial monitor/serial plotter! For example, because at the code I used 115200 baud, I also have to put the value of baud setting at serial monitor/serial plotter equal to 115200 baud.</p><p>Although, sometimes the value can decrease or increase by itself while we literally don’t do anything to it. But, actually that’s pretty normal because that is the reality, there are many external factors that can influence the touch sensor, so don’t worry if that thing happen to you!</p><p>I am pretty glad that everything is working as I am expected! With this, I am done with my simple touch sensor project!</p><h4>But, How About Hall Effect Sensor?</h4><p>What if I used hall effect sensor with magnet instead of touch sensor to turn on the LED? Is it possible? I am kind of curious so I decide to try it!</p><p>For this project, I am still using same components and devices as previous project (touch sensor), but instead of 2 LEDs and 2 resistors, I will use 1 LED and 1 resistor instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*LOL-hW8vr50IYEiENaaJWw.png" /><figcaption>Simpler Schematic Diagram From Above</figcaption></figure><p>At this project, I want to utilize magnet to turn on the LED. This can works because ESP32 has built-in hall effect sensor that detects changes in the magnetic field in its surrounding. The greater the magnetic field, the greater the sensor’s output voltage which can be seen from serial monitor/serial plotter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*soBT1-3tEqJmnrVWFjVsMA.png" /></figure><p>To be fair, this code can be said pretty simple and similar with the code above (touch sensor project). In short, the key points are firstThreshold, secondThreshold, and val that store the value of hallRead(). If val is more than firstThreshold or less than secondThreshold, ESP32 will turn on LED, else it will turn off LED. Just keep in mind that instead of using <strong>Serial.begin(115200)</strong>, this time I’m using <strong>Serial.begin(9600)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAtwRD_0fQJXZxUQ7mUUYQ.jpeg" /><figcaption>My Pretty Simple Circuit For Hall Effect Sensor Experiment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*p1uHR4Jhgxye3nC4T5-2cA.gif" /><figcaption>Putting Magnet to Turn On LED</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*sbVWLLJpoboOt5wj4DuZTA.gif" /><figcaption>Changing The Side of Magnet</figcaption></figure><p>For your information, magnet can increase or decrease the value of hallRead(), depends on the magnet pole that is facing the sensor. What can be said for sure is the closer the magnet to the sensor, the greater the absolute values are (although mine feels like not really make a great difference, probably because my magnet is too weak, might be because it’s an old magnet already)</p><p>It seems like my second experiment in this project also goes well, now we only have 1 more experiment!</p><h4>Temperature Sensor</h4><p>Although this sensor is named temperature sensor, but actually this sensor isn’t usable to monitor external temperature. This sensor purpose is to monitor its internal temperature which is its core temperature.</p><p>This time, I do this experiment pretty simple. I just want to check my ESP32 internal temperature, so what I need only ESP32 (and of course its USB cable and PC to connect). I believe for this time schematic diagram is not needed, you guys might want to see my taken picture below instead!</p><p>BTW, here is the code which to be honest I just take from <a href="https://circuits4you.com/2019/01/01/esp32-internal-temperature-sensor-example">circuits4you.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*HLn4gGsQNsUEQn_3TQrzKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*xNqABeNVKSmRmWuz79dKuQ.png" /></figure><p>Because what I am going to do is pretty simple, to be fair it can’t be helped. More or less it will pretty similar with the code above, so I will just credit circuits4you.com directly (Of course, I will also credit randomnerdtutorials.com for the references for touch sensor and hall effect sensor above , although I didn’t copy but still used it as reference)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-gVGk3oxXZ6fq1jLDFXAA.jpeg" /><figcaption>My Experiment For Temperature Sensor</figcaption></figure><p>With this project, it seems that my ESP32 has built-in temperature sensor! As we can see that the internal temperature of my ESP32 is 53.33 Celsius.</p><h4>Conclusion?</h4><p>To conclude this third project, the main point that I would like to highlights are :</p><ul><li>I can make blink LEDs by touching the male to male jumper wires by making use of built-in touch sensor, and turn off all LEDs by not touching it. This can be happened because if we touch the touch-sensitive pin, the value read by the sensor drops (can be seen from serial monitor/serial plotter), so we can make use threshold value to make something happen.</li><li>I can turn on LED by putting magnet near the built-in hall effect sensor and turn off LED by moving magnet away from the built-in hall effect sensor. This can be happened because magnet can increase or decrease the value of hallRead(), depends on the magnet pole that is facing the sensor. What can be said for sure is the closer the magnet to the sensor, the greater the absolute values are, so we also can make use of threshold value to make something happen. (Example : detect proximity, calculate positioning, count the number of revolutions of a wheel, detect a door closing, etc.)</li><li>My ESP32 has temperature sensor which can show us what is the internal temperature of my ESP32 (not external temperature). This temperature can be seen from serial monitor in Arduino IDE.</li></ul><p>I think that’s all for this story about internal sensor. I hope that this can bring you guys more insight and benefit that can be pretty useful. See you guys in the next story!</p><h3>References :</h3><ul><li><a href="https://randomnerdtutorials.com/esp32-touch-pins-arduino-ide/">https://randomnerdtutorials.com/esp32-touch-pins-arduino-ide/</a></li><li><a href="https://randomnerdtutorials.com/esp32-hall-effect-sensor/">https://randomnerdtutorials.com/esp32-hall-effect-sensor/</a></li><li><a href="https://circuits4you.com/2019/01/01/esp32-internal-temperature-sensor-example/">https://circuits4you.com/2019/01/01/esp32-internal-temperature-sensor-example/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=468dbb7864d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded System Project 2 : I/O With ESP32]]></title>
            <link>https://fernaldifz.medium.com/embedded-system-project-2-i-o-with-esp32-a64dabb488ea?source=rss-908796d811ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a64dabb488ea</guid>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Fernaldi Fauzie]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 13:30:11 GMT</pubDate>
            <atom:updated>2021-03-31T12:06:34.515Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embedded System Project 2: I/O With ESP32</h3><p>Our journey with ESP32 is still only first page of many pages! This time, I would like to share about my second project with ESP32, which is about I/O with ESP32. At this point, I would like to do 2 experimentation, first one is digital I/O with ESP32 and second one is analog I/O with ESP32. Check it out!</p><h4>Digital Inputs and Digital Outputs</h4><p>Before I start, I need to prepare :</p><ul><li>Microcontroller ESP32 Development Board</li><li>USB Type A Male to Micro USB</li><li>Breadboard</li><li>5 mm LED (2)</li><li>330 Ohm resistor (2)</li><li>Pushbutton</li><li>10k Ohm resistor</li><li>Jumper wires (I’m using 6 male to male jumper wires)</li></ul><p>For some reason, when I made schematic diagram in <a href="http://circuito.io/">circuito.io</a>, I can’t modify the ESP32 type, resistor type, which ESP32 pin used, the location of components (all of it automatically), which mean this schematic diagram is not 100% same with what I made, but in general this schematic diagram can bring you to understand more about what I made.</p><p>So, there are some notable difference like :</p><ul><li>I used 330 Ohm resistor instead of 100 Ohm resistor in Schematic Diagram</li><li>ESP32 pin that I used for input and output.</li></ul><p>So, this is the result of schematic diagram with <a href="http://circuito.io/">circuito.io</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*6sVaJs2X5iS4IPzK3rOL5w.png" /><figcaption>Schematic Diagram</figcaption></figure><p>After I made this schematic diagram, I still don’t feel really satisfied with what I have done. So I tried to look and find another alternative to make schematic diagram, and then that’s when I found <a href="http://fritzing.org/">fritzing</a>. Finally I can make a better schematic diagram and here it is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhZiyXZ2eXTtkCji-bztiQ.jpeg" /><figcaption>Also Schematic Diagram but better</figcaption></figure><p>Of course, different setup with mine can also work, as long you be careful with what you do. <a href="https://randomnerdtutorials.com/esp32-pinout-reference-gpios/">Here is good ESP32 pinout reference from randomnerdtutorials.com</a> if you need it.</p><p>As I am done with schematic diagram, let’s move to the code. You may look at my code and demo below. I am using pushbutton to do blink with 2 LED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*6NSLhEwEaGrb-0RgKGodww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Zdhi8hBwCfy6uDZMl2gULA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*Nl_pDNuECz9OhAZuSCX5nw.gif" /><figcaption>My Demo for Digital I/O</figcaption></figure><p>This demo is basically LED blink with pushbutton. If I press the pushbutton, first LED will turn on, while second LED will turn off, vice versa. I put 1000 ms (1 second) so that I don’t confused when looking at the blink. If I don’t press the pushbutton, all led will be turned off.</p><p>In conclusion, with pushbutton, you can do more things as you can use if, else if, and else in the code to put more condition. In my case, if I push the pushbutton, my 2 LED will do blink which is if first LED turned off, the other one will be turned off, vice versa. There are only 2 cases, the LED turned on or turned off because I am using digital signal as digital signal uses discrete values for representing the information. While if I don’t push the pushbutton, nothing will happened.</p><h4>We Are Done With Digital Inputs and Digital Outputs, But How About Analog Output Instead of Digital Output?</h4><p>So I kind of curious, what if I used analog output instead of digital output? Do I can use it like before with pushbutton? So now I am modifying my code as I am still using same circuit as before that can be seen at schematic diagram upward. This time, I want to generate PWM signals with the ESP32 using Arduino IDE.</p><p>Oh right, before you guys going here, make sure to pay attention to some things like :</p><ul><li>PWM channel in ESP32 that can be used. There are 16 channels in ESP32 which is from 0 to 15.</li><li>PWM signal frequency for LED. In my case, I am using 5000 Hz.</li><li>Signal’s duty cycle resolution, we have resolutions from 1 to 16 bits. In my case, I am using 8-bit resolution, which means I can control the LED brightness using value from 0 to 255, although at the code below I am using value from 15 to 255 because I modified it.</li><li>GPIO or GPIOs that the signal will appear upon. I am using ledcAttachPin(GPIO, channel) function for this.</li><li>LED brightness that can be controlled with PWM. I am using ledcWrite(channel, dutycycle).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*VoPm4AFh8TipmflkobT4Mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*349gYjvCkNVzlcE02W3wzQ.png" /></figure><p>In this code, I am still using pushbutton to put more condition with my experiment. This time :</p><ul><li>When the pushbutton pressed, the LED will not blink, but instead it will increase LED brightness, starting from dutyCycle equal to 15, keep increasing until it equal to 255. Then. it will decrease LED brightness, starting from dutyCycle equal to 255, keep decreasing until it equal to 15. Because its code at void loop, it will keep looping.</li><li>When the pushbutton released, it will turn off all LED.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*cNIEJLxYOnpNfDpaxARd9A.gif" /><figcaption>Pressing the pushbutton</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*G3k9Yc1S6excWP4T20Njqw.gif" /><figcaption>Releasing the pushbutton</figcaption></figure><p>To conclude, analog signal uses continuous values for representing the information. In my case, with analog signal I can adjust the brightness of LED more freely compared while I am using digital signal, because digital uses discrete values for representing the information. In my case, with digital signal I can only turn on or turn off the LED, can’t do more specific like analog signal.</p><p>It seems that my story about I/O is finally come to the end. I hope that this story can bring you guys more knowledge and of course, insight that can help you guys to more interested in ESP32 as our journey with ESP32 is still pretty long! See you in my next story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a64dabb488ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>