Basics of Design CC Blog Research & Design Hub

Backend Web Development for MCU Clients

Part 1: Handling HTTP Requests in PHP

Sometimes edge devices must interact with servers that understand only HTTP and HTTPS, even though MQTT protocol is often preferred for sending IoT data to a server. Thus, proficiency with servers, HTTP, and backend technologies is a valuable skill for the embedded systems professional. In this new article series, I will cover backend web development for embedded clients such as microcontrollers and edge processors for IoT applications.

  • How can I handle HTTP requests for MCU clients?
  • What are the basics of backend web development for MCU clients?
  • How can I set up a Raspberry Pi server?
  • Raspberry Pi

In this three-part article series, I discuss backend web development for embedded clients, such as microcontrollers (MCUs) and other edge processors for Internet-of-Things (IoT) applications. I describe how to set up a web server with a database to develop backend applications for receiving sensor data from remote devices via Hyper Text Transport Protocol (HTTP) requests. The received data are parsed, processed, and stored in a database using the PHP scripting language.

Sensor data are sent from the MCU client as a string of Comma Separated Values (CSVs). The JavaScript Object Notation (JSON) data-interchange format can be used as well. The receiving PHP script running on the server processes the data and stores them in a database. Another PHP script is used to query the database and extract data matching a certain criterion, such as a given period of time. The script prepares the available results as a JSON or Extensible Markup Language (XML) file, and sends it back to the HTTP client that made the request–for instance, a web browser that requested the data to visualize them graphically in a web page.

Although there are cases in which Message Queuing Telemetry Transport (MQTT) protocol would be a better option to send IoT data to a web server, sometimes edge devices need to interact with servers that understand only HTTP and secure HTTP (HTTPS). However, web clients such as web browsers generally access server data using HTTP/HTTPS almost exclusively. With that in mind, knowing about servers, HTTP and backend technologies can be helpful for an embedded developer, for prototyping web applications that store and retrieve IoT data from a web server using databases, and for other applications.

To be able to follow the topics discussed in this article series, you will need to have some experience with the Arduino platform. It is also desirable to have some experience setting up server software (Apache, PHP, MariaDB, PhpMyAdmin) on a single-board computer (SBC), such as the Raspberry Pi board, or any conventional personal computer. I will not be covering in great depth how to do the latter, but I will describe the main steps in reasonable detail. Nevertheless, it’s a simple procedure and there are also countless tutorials on the Web covering the topic. It is also possible to just use a typical shared web hosting service to avoid setting up your own server.

The code referenced throughout this article is available on the Circuit Cellar Article Materials and Resources webpage.

FULL-STACK WEB DEVELOPMENT

Let’s begin by explaining “full stack web development,” to establish a clear conceptual base for all that will be discussed in this article. “Full stack” refers to the development of both the “frontend” (client side) and “backend” (server side) portions of a web application [1]. Full-stack web developers can design and implement complete web applications or websites, because they have the knowledge to work on both the frontend and the backend. They also know how to use databases and perform all necessary debugging tasks typical of web applications and websites.

Figure 1 illustrates the concept of full-stack web development and how it is divided into its two components: the frontend and the backend. Let’s explain in more detail what is the frontend or the client side of the application, and what is the backend, known also as the server side of the application.

FIGURE 1
Full-stack web development.
FIGURE 1
Full-stack web development.

The frontend is the visible part of the web application or website, and is typically in charge of user interaction. It is built using frontend languages, such as Hyper Text Markup Language (HTML), Cascading Style Sheets (CSS), and the JavaScript scripting language. HTML and CSS are not strictly programming languages; rather, they are markup and stylesheet languages, respectively. Additionally, there are some frontend frameworks and libraries, such as: AngularJS, ReactJS, VueJS, Bootstrap, jQuery and SASS, among others. Data exchange formats such as JSON and XML, along with query languages such as GraphQL are used by web clients to request data from servers.

The backend is the non-visible, server-side part of the web application or website, and it defines how the website works for the most part. It is also responsible for managing the database, and interacts with it on behalf of web clients. To this end, it provides Application Programming Interfaces (APIs) to the client side. Backends are typically built using languages such as PHP, Ruby, C++, Java, Python, JavaScript/NodeJS, and others. Some frameworks, including Express, Django, Rails, Laravel, and Spring, also are available. Databases are also part of almost any backend. Popular database technologies used are Oracle, MongoDB and MySQL/MariaDB, among others.

There are also some popular technology stacks used for backend development. They include MEAN (MongoDB, Express, AngularJS, and Node.js), MERN (MongoDB, Express, ReactJS, and Node.js), Django (Django, Python, and MySQL), Ruby on Rails (Ruby, PHP, and MySQL) and LAMP (Linux, Apache, MySQL, and PHP).

In this article series we will use LAMP, because it is arguably the most popular and is commonly found. For instance, most of the shared hosting servers offer LAMP installed by default, so you don’t need to install anything else to begin developing web applications.

BACKEND WORKFLOW

Let’s describe a typical backend workflow for a simple IoT web application. Figure 2 is a conceptual diagram of this type of workflow. For the purpose of this article, the web client will be primarily any edge device. For the concrete application example we will discuss here, the web client will be an MCU that gathers sensor data and sends them periodically to the web/application server. The server receives these data and stores them in a database. Data are sent by the client (the MCU) via periodic HTTP POST request to the server. To retrieve data from the database, any client (for example a web browser or the MCU, itself) can send HTTP GET requests to the server as well. Both types of requests (POST and GET) are part of the REpresentational State Transfer (REST) architectural style, on top of which most Internet websites are built.

FIGURE 2
Backend workflow for an IoT web application.
FIGURE 2
Backend workflow for an IoT web application.

The data are transferred from the client to the server using data interchange formats such as CSV, JSON or XML. In general, CVS and JSON are the most efficient in terms of memory space, because they use less metadata for data representation. However, to retrieve data from the application server, JSON and XML are typically used, especially by more conventional web clients, such as web browsers. For MCU clients requesting data from the application server, JSON is more efficient in comparison with XML, in terms of memory. CSV can also be used, which is even more efficient; but at the same time, it has its drawbacks–being less clearly defined, not hierarchical and not easily scalable in comparison to JSON and XML. Nevertheless, CSV can be convenient for small datasets.

WEB AND APPLICATION SERVER

To build your first HTTP IoT web application, there are two easy options for setting up an application server. The first one is to use an SBC, such as the Raspberry Pi board, as a server, and to install on it the LAMP stack. Other SBCs can be used as well, for instance, boards such as the Orange Pi, Le Potato, Asus Tinker Board, Odroid N2+, Banana Pi, Radxa RockPro64, Nano Pi R4S, and others. Moreover, any regular Linux computer or laptop can also be used. A computer with the Windows operating system can be used after installing WAMP (Windows, Apache, MySQL and PHP) or Laragon [2].

The second option is to use a regular shared hosting server. Most cheap web hosting options (around $10 a month) come with the LAMP stack installed by default. The user doesn’t have to install anything else to be able to write web applications using PHP and MySQL/MariaDB databases.

In this article, we will use the first option, and I will describe the main procedure to set up a Raspberry Pi server. I will not go into great detail, but the procedure is fairly easy for someone that has reasonable experience using a Raspberry Pi and the Linux terminal.

RASPBERRY PI SERVER

Setting up a Raspberry Pi web server is relatively easy. The procedure described next assumes you have already installed the Raspberry Pi OS on your board. The same steps will work equally well with other Debian-based operating systems, such as Armbian and Ubuntu. Listing 1 shows the commands to run on the Linux terminal to install the LAMP stack [3].

LISTING 1
Raspberry Pi web server installation.

1 # Setting Up a LAMP Web Server On A Raspberry Pi
2 
3 ## Step 1: Update Your Operating System
4     sudo apt update
5     sudo apt upgrade
6 
7 ## Step 2: Install and Test Apache Server
8     sudo apt install apache2
9 
10 ### Find your Raspberry Pi IP address:
11     Hostname -I
12 
13 ### Open the IP address on your web browser. For example: http://192.168.0.100   Check that the “Apache2 Debian Default Page” is shown. 
14 
15 ## Step 3: Install and Test PHP
16     sudo apt install php libapache2-mod-php
17 
18 ### Test your first PHP script. Go to the Apache web folder:
19     cd /var/www/html
20 
21 ### Create a new PHP file:
22     sudo nano test.php
23 
24 ### Copy this code into it:
25     <?php phpinfo(); ?>
26 
27 ### Open the script on your web browser. For instance: http://192.168.0.100/test.php   Check that the default PHP Info “PHP Version x.x.x” is shown.
28 
29 ## Step 4: Install and Test MariaDB
30     sudo apt install mariadb-server php-mysql
31 
32 ### Restart Apache:
33     sudo service apache2 restart
34 
35 ### Check that MariaDB is installed properly. Start MariaDB:
36     sudo mariadb
37 
38 ### List all available databases:
39     show databases;
40 
41 ### Exit MariaDB:
42     exit
LISTING 2
MCU web client Arduino source code.
1 #include <ESP8266WiFi.h>
2 #define PUB_INTERVAL  5000  // Data publication interval (msec) 
3 
4 char* ssid     = “MyWiFi”;
5 char* password = “MyCatKnowsAssembly”;
6 
7 WiFiClient client;
8 char server_addr[] = “192.168.0.15”; // Server IP addres
9 char php_script_uri[] = “/backend/receive_csv.php”; // URI for the PHP script that will receive and process the data
10 String csv_data; // CSV data string to send to the server
11 
12 void setup() { 
13   Serial.begin(115200); // Open the Arduino serial terminal
14   while (!Serial);
15 
16   // Connect to WiFi
17   Serial.print(“Connecting to: “);
18   Serial.println(ssid);
19   WiFi.begin(ssid, password);
20   while (WiFi.status() != WL_CONNECTED) {
21       delay(500);
22       Serial.print(“.”);
23   }
24   Serial.println(“WiFi connected. IP address:”);
25   Serial.println(WiFi.localIP());
26 }
27 
28 void loop() {
29   static long prev_millis; // Stores time of the last publication
30   // Generate random values to simulate sensor readings
31   float gas_resistance = random(0, 100);
32   float pressure = random(0, 100);  
33   float temperature = random(0, 100);  
34   float rel_humimidy = random(0, 100);  
35 
36   // Compute elapsed time since last publication
37   long elapsed_time = millis() - prev_millis;
38   // Send data to server if publication period has been reached
39   if (elapsed_time >= PUB_INTERVAL) {
40     // Create and send sensor data as CSV string
41     csv_data = String(gas_resistance) + “,” + String(pressure) + “,” + String(temperature) + “,” + String(rel_humidity);
42     Serial.print(“CSV string to send: “);
43     Serial.println(csv_data);
44     Send_Http_Request(); // Send data in an HTTP request
45     prev_millis = millis();  // Take current time to compute next interval
46   }
47   // Print response from server 
48   while (client.available()) { 
49     char c = client.read();
50     Serial.print(c);
51   }
52 }
53 
54 // Function that sends data to server
55 void Send_Http_Request () {
56     if (client.connect(server_addr, 80)) {  // Create a connection with the server 
57       Serial.println(“Connected to server!”); // Print to serial monitor
58       // Send HTTP POST request to server
59       client.print(“POST “);
60       client.print(php_script_uri); // Receiving PHP script URI
61       client.println(“ HTTP/1.1”);
62       client.print(“Host: “);
63       client.println(server_addr); // Include server address
64       client.println(“User-Agent: Arduino/1.0”);
65       client.println(“Connection: close”);
66       client.println(“Content-Type: text/csv; charset=UTF-8”);
67       client.print(“Content-Length: “);
68       client.println(csv_data.length());
69       client.println();
70       client.print(csv_data); // CSV data inside the request body
71     } else {
72       Serial.println(“Connection to server failed.”);  
73     }
74 }
1 #include <ESP8266WiFi.h>
2 #define PUB_INTERVAL  5000  // Data publication interval (msec) 
3 
4 char* ssid     = “MyWiFi”;
5 char* password = “MyCatKnowsAssembly”;
6 
7 WiFiClient client;
8 char server_addr[] = “192.168.0.15”; // Server IP addres
9 char php_script_uri[] = “/backend/receive_csv.php”; // URI for the PHP script that will receive and process the data
10 String csv_data; // CSV data string to send to the server
11 
12 void setup() { 
13   Serial.begin(115200); // Open the Arduino serial terminal
14   while (!Serial);
15 
16   // Connect to WiFi
17   Serial.print(“Connecting to: “);
18   Serial.println(ssid);
19   WiFi.begin(ssid, password);
20   while (WiFi.status() != WL_CONNECTED) {
21       delay(500);
22       Serial.print(“.”);
23   }
24   Serial.println(“WiFi connected. IP address:”);
25   Serial.println(WiFi.localIP());
26 }
27 
28 void loop() {
29   static long prev_millis; // Stores time of the last publication
30   // Generate random values to simulate sensor readings
31   float gas_resistance = random(0, 100);
32   float pressure = random(0, 100);  
33   float temperature = random(0, 100);  
34   float rel_humimidy = random(0, 100);  
35 
36   // Compute elapsed time since last publication
37   long elapsed_time = millis() - prev_millis;
38   // Send data to server if publication period has been reached
39   if (elapsed_time >= PUB_INTERVAL) {
40     // Create and send sensor data as CSV string
41     csv_data = String(gas_resistance) + “,” + String(pressure) + “,” + String(temperature) + “,” + String(rel_humidity);
42     Serial.print(“CSV string to send: “);
43     Serial.println(csv_data);
44     Send_Http_Request(); // Send data in an HTTP request
45     prev_millis = millis();  // Take current time to compute next interval
46   }
47   // Print response from server 
48   while (client.available()) { 
49     char c = client.read();
50     Serial.print(c);
51   }
52 }
53 
54 // Function that sends data to server
55 void Send_Http_Request () {
56     if (client.connect(server_addr, 80)) {  // Create a connection with the server 
57       Serial.println(“Connected to server!”); // Print to serial monitor
58       // Send HTTP POST request to server
59       client.print(“POST “);
60       client.print(php_script_uri); // Receiving PHP script URI
61       client.println(“ HTTP/1.1”);
62       client.print(“Host: “);
63       client.println(server_addr); // Include server address
64       client.println(“User-Agent: Arduino/1.0”);
65       client.println(“Connection: close”);
66       client.println(“Content-Type: text/csv; charset=UTF-8”);
67       client.print(“Content-Length: “);
68       client.println(csv_data.length());
69       client.println();
70       client.print(csv_data); // CSV data inside the request body
71     } else {
72       Serial.println(“Connection to server failed.”);  
73     }
74 }

LISTING 3
Listing for the "receive_csv.php" PHP script.

1 <?php 
2     $csv = file_get_contents(‘php://input’); // Get the body (CSV string) from the incoming request
3 
4     echo “Received CSV string: “; // Send back received data to client just for debugging         
5     echo $csv . “\n”;
6 
7     $data_array = str_getcsv($csv); // Convert CSV to array
8 
9     if($data_array != null) {
10         $unix_t =   time(); // Read unix time (GMT) from server
11 
12         // Extract received remote values from array
13         $gas_res = $data_array[0]; 
14         $pressure = $data_array[1];
15         $temperature = $data_array[2];
16         $rel_hum = $data_array[3];
17 
18         // Build SQL query string for the database
19         $query = “INSERT INTO data_logger(unix_t, gas_res, pressure, temperature, rel_hum) VALUES” .
20           “(‘$unix_t’, ‘$gas_res’, ‘$pressure’, ‘$temperature’, ‘$rel_hum’)”;
21 
22         echo “SQL query: $query\n”; // Send back query string to client just for debugging
23     }   
24 ?>

As a first step, it is a good idea to update the operating system by running the commands from lines 4-5. Next, install the Apache web server software by running the command in line 8. After the installation finishes, you will be ready to test Apache. Make sure your Raspberry Pi is connected to your local LAN via Ethernet or Wi-Fi, and get the IP address assigned to it by running the command in line 11. Open that IP address on a web browser and check that the default “Apache2 Debian Default Page” loads on the web browser page. It should look like the screenshot in Figure 3.

Next, run the command in line 16 to install PHP and the Apache plug-in that interprets PHP files. After the installation, you can test it with a simple PHP script. Go to the server’s root folder (line 19), create a “test.php” file (line 22), and write in the PHP code from line 25. Line 22 uses the “nano” terminal-based text editor to edit the aforementioned PHP file, but you can use any other terminal-based or Graphical User Interface (GUI) text editor. Next, open the PHP script on a web browser (see line 27). If PHP is set up correctly, you should see a webpage similar to the one shown in Figure 4.

FIGURE 3
Default Apache web server page.
FIGURE 3
Default Apache web server page.
FIGURE 4
PHP version info web page.
FIGURE 4
PHP version info web page.

As one of the last steps, install the MariaDB database by running line 30. For practical purposes, MySQL and MariaDB are the same database. MariaDB is an improved, open-source fork, backward-compatible version of MySQL. MariaDB supports the same features present in MySQL and adds various others, as well as many security and execution improvements. That’s why “mysql” and “mariadb” names are used interchangeably in much available documentation, as well as related code and Linux command examples.

After installing MariaDB, restart the Apache web server (line 33) and test your database installation. Start MariaDB on a terminal window by running the command in line 36. For the reasons explained above, if you type “sudo mysql” instead, you will get the same result. Once you have the MariaDB command-line client running, run the command in line 39 to get a listing of all currently available databases. Any fresh MariaDB installation comes with some pre-installed databases for internal use. These will be shown after running the show databases; command. Don’t forget to type the semicolon in line 39. That line is an SQL query, and all SQL queries for MariaDB must be terminated with a semicolon. If you don’t get any errors after performing these steps, it means the database is installed correctly. Exit the command-line client by typing “exit” to return to the Linux system prompt.

MCU-BASED WEB CLIENT

To test the web application we will be building in this article series, we will use an MCU-based HTTP client to send sensor data to our server. This MCU client needs network access to exchange data with the server, so it must have Ethernet or Wi-Fi connectivity. There are various options that fulfill this requirement. A couple of those are the Espresiff Systems ESP8266 and ESP32 MCUs, which are considered the cheapest and most popular options for this type of do-it-yourself projects. Both include an integrated TCP/IP protocol stack, and a Wi-Fi transceiver to connect them to a Wireless Local Area Network (WLAN).

Figure 5 shows the NodeMCU ESP8266-based data logger prototype, and Figure 6 is its circuit schematic. As shown, the data logger uses the Bosh Sensortec BME688 Environmental Sensor, which can detect Volatile Organic Compounds (VOCs), Volatile Sulfur Compounds (VSCs) and other gases, such as carbon monoxide and hydrogen. Additionally, it can measure atmospheric pressure, temperature, and relative humidity [4].

FIGURE 5
ESP8266-based MCU client prototype.
FIGURE 5
ESP8266-based MCU client prototype.
FIGURE 6
Data logger circuit schematic.
FIGURE 6
Data logger circuit schematic.

Because ESP8266 boards aren’t supported by the Arduino IDE by default, a support package must be installed first, to be able to compile code for this MCU. The support package includes all necessary libraries to connect the MCU to the Internet, using Wi-Fi and the HTTP protocol. Installing this support package is easy. You just have to open the Arduino Preferences window and add the support package URL into the “Additional Board Manager URLs” field. For a tutorial on how to do this, see the Circuit Cellar Article Materials and Resources webpage [5].

Listing 2 shows the code for the data logger to upload sensor data to the web server. Lines 17-25 inside the setup() function connect the ESP8266 to the Wi-Fi network with the ID and password specified in lines 4-5. In lines 31-34 inside the loop() function, we randomly generate four values to simulate sensor readings. Even if the sensor is connected already, it is usually preferable to do the first tests using randomly generated data. This allows us to test just the HTTP communications, without worrying about errors from other system components, such as sensors modules.

The data logger sends periodically its sensor readings to the web server. This is accomplished with the non-blocking delay implemented in lines 37-46. Line 37 computes the elapsed time since the last data sent. Line 39 compares this elapsed time with the publication interval defined in line 2, which is 5,000ms (5 seconds). This is the interval at which we want to send data to the server.

If the elapsed time is greater-than or equal to the publication interval (line 39), a CSV string is created by concatenating all sensor readings with commas (line 41). The resulting string will look like this: “49.00,93.00,9.00,41.00”. Next, with lines 42-43, the string is printed to the Arduino serial terminal for debugging purposes. Line 44 calls the Send_Http_Request() function that’s in charge of sending the CSV data to the web server by issuing an HTTP POST request.

Line 45 takes the current system time in milliseconds to restart the time count for the next publication interval. Lines 48-51 will print the incoming server response after attending the HTTP POST request.

Lines 55-74 show the Send_Http_Request() function definition. After creating a connection to the server (line 56), lines 59-68 send the HTTP POST request header. Line 69 separates the header from the body, and line 70 sends the CSV data as the body of the HTTP request. The described structure follows the HTTP protocol specification. The Circuit Cellar Article Materials and Resources webpage includes a link to an explanation of HTTP protocol basics, in case you are not familiar with it [6].

Note that line 60 inserts in the header the Uniform Resource Identifier (URI) of the PHP script on the server that will receive and process the data. The php_script_uri variable is defined in line 9. The URI string “/backend/receive_csv.php” specifies that the request is directed to a “receive_csv.php” script inside a “backend” folder in the server’s root directory. Line 63 inserts the web server’s IP address defined in line 8.

OUR FIRST PHP SCRIPT

So, to attend to the HTTP POST requests sent by the MCU client, we need a PHP script that will run on the server every time those requests arrive. Remember from the MCU client’s Arduino code that the URI for this PHP script is included in the HTTP header. So, now we need to create a “receive_csv.php” script and put it inside a “backend” folder in the server’s root directory. Listing 3 shows the PHP code for the aforementioned script.

PHP code must be surrounded by an opening tag, as shown in line 1 (<?php), and a closing tag as shown in line 24 (?>). For the most part, PHP is similar to C and C++ languages. However, all variable names in PHP must begin with the “$” character. In line 2 of Listing 3, the file_get_contents PHP function reads from the server system the incoming HTTP request’s body, which, if you remember, contains the CSV string with the sensor readings. In the same line, this CSV string is stored in the $csv variable.

Lines 4-5 send back debugging data to the client using the echo “function” (technically, a “language construct”) that is analogous to the printf C language function. Suppose the received CSV string was, for example, “49.0,52.0,23.0,30.0”; lines 4-5 will send back to the client the string, “Received CSV string: 49.0,52.0,23.0,30.0\n”. The last two characters (\n) are the “new line” character that makes the cursor jump to the next line in the screen. The ‘.’ character in line 5 is the PHP string concatenation operator. See as well that in line 22 we have another echo. All strings from these echo construct callings will be included in the HTTP response’s body that the server will send back to the client.

Line 7 uses the str_getcsv PHP function to parse the CSV string and store the result to the $data_array array. The cells in the resulting array will contain the individual sensor values that were separated by commas in the received CSV string. Line 9 checks that the conversion operation was successful and the resulting array is not null. If so, in lines 13-16 the array is indexed to read all sensor values into local variables. But previously, in line 10, we read the “Unix time” from the server system and stored it into the $unix_t variable.

In case you are wondering, Unix time is a way of representing a timestamp as the number of seconds since January 1, 1970 at 00:00:00 UTC. Unix time timestamps are represented as integers, which makes them easier to parse using programming languages [7]. Here we are using the obtained server Unix time as a timestamp for the sensor readings batch that just arrived.

Next, in lines 19-20 we build the SQL query string that will insert the received values into the database. I will explain MariaDB databases and SQL queries in more detail in Part 2 of this article series. For now, let’s just accept as a fact that these two lines build the required SQL query to insert the data into the database, by concatenating two strings (see the ‘.’ at the end of line 19), including the values stored in variables (line 20).

Line 22 echoes the resulting string contained in the $query variable to the client. The string will look like this:

INSERT INTO data_logger(unix_t, gas_res, pressure, temperature, rel_hum) VALUES(49.0,52.0,23.0,30.0)

The names inside the first parentheses are column names in the “data_logger” database table. The values inside the second parentheses are the corresponding values to be inserted in each column. For now, we are just showing how to create the SQL query, but we are not using it yet. We will do that in Part 2 of this article series.

RUNNING THE FIRST TEST

Let’s describe now the procedure to run a first test with all that we have ready. First, create a “backend” folder inside your web server’s root directory. On a typical Raspberry Pi server installation, the server root directory will usually be: “/var/www/html.” The same applies to other Debian-based distributions, such as Armbian and Ubuntu. Download all source code files from the Circuit Cellar Article Materials and Resources webpage. Then, copy the “receive_csv.php” script to the “backend” folder and make sure the file has the right access permissions. For setting the permissions open a terminal window on the “backend” folder, and run the command: chmod 644 receive_csv.php

Next, connect the ESP82266 board to your PC, and upload the “esp8266_http_post_client.ino” Arduino sketch. Before flashing your board, don’t forget to change lines 4-5 with your Wi-Fi credentials and line 8 with the IP address assigned to your server. After flashing the board, it will reset itself and try to connect to your Wi-Fi network. Open the Arduino IDE’s serial monitor to see debug information. Once the board is connected to your Wi-Fi, it will automatically start to send data periodically to the web server. A response from the server, similar to what is shown in Figure 7, will be printed on the serial monitor.

FIGURE 7
Arduino serial monitor displaying response from the web server.
FIGURE 7
Arduino serial monitor displaying response from the web server.
CONCLUSION

I hope I succeeded in showing you how relatively easy it is to receive data from an MCU client on a web server, and process the data using PHP. To understand the workflow, it greatly helps to be familiar with the client/server model and the HTTP protocol. If some concepts are still new and confusing to you, take the time to read the included resources, test the example, and carefully analyze the provided code. Don’t worry if you still have some lingering doubts; just make sure you understand the general workflow, and give yourself some extra time to understand the details.

In Part 2 of this article series, I will explain how to create a database and store the received data in it, using a slightly modified version of the PHP script described here. I will also explain how to extract data from the database and send it back to a web client using a second PHP script. We will also explore the pros and cons of using different data exchange formats, such as CSV, JSON, and XML. 

REFERENCES
[1] What is full stack development?: https://www.geeksforgeeks.org/what-is-full-stack-development/
[2] Laragon Documentation: https://laragon.org/docs/
[3] Set Up a LAMP Web Server on a Raspberry Pi in 2023: https://raspberrytips.com/web-server-setup-on-raspberry-pi/
[4] Gas Sensor BME688: https://www.bosch-sensortec.com/products/environmental-sensors/gas-sensors/bme688/
[5] Installing ESP8266 Board in Arduino IDE: https://randomnerdtutorials.com/how-to-install-esp8266-board-arduino-ide/
[6] What is HTTP? Protocol Overview for Beginners: https://www.freecodecamp.org/news/what-is-http/
[7] What is Unix time?: https://kb.narrative.io/what-is-unix-time

— ADVERTISMENT—

Advertise Here

SOURCES
ESP8266 NodeMCU CP2102 ESP-12E Development Board: https://www.amazon.com/HiLetgo-Internet-Development-Wireless-Micropython/dp/B010O1G1ES
Adafruit BME688 – Temperature, Humidity, Pressure and Gas Sensor – STEMMA QT: https://www.adafruit.com/product/5046

RESOURCES
Arduino | www.arduino.cc
Espressif Systems | www.espressif.com
Raspberry Pi | www.raspberrypi.org

Code and Supporting Files

PUBLISHED IN CIRCUIT CELLAR MAGAZINE • OCTOBER 2023 #399 – Get a PDF of the issue

Keep up-to-date with our FREE Weekly Newsletter!

Don't miss out on upcoming issues of Circuit Cellar.


Note: We’ve made the Dec 2022 issue of Circuit Cellar available as a free sample issue. In it, you’ll find a rich variety of the kinds of articles and information that exemplify a typical issue of the current magazine.

Would you like to write for Circuit Cellar? We are always accepting articles/posts from the technical community. Get in touch with us and let's discuss your ideas.

Sponsor this Article
| + posts

Raul Alvarez Torrico has a B.E. in electronics engineering and is the founder of TecBolivia, a company offering services in physical computing and educational robotics in Bolivia. In his spare time, he likes to experiment with wireless sensor networks, robotics and artificial intelligence. He also publishes articles and video tutorials about embedded systems and programming in his native language (Spanish), at his company’s web site www.TecBolivia.com. You may contact him at raul@tecbolivia.com

Supporting Companies

Upcoming Events


Copyright © KCK Media Corp.
All Rights Reserved

Copyright © 2024 KCK Media Corp.

Backend Web Development for MCU Clients

by Raul Alvarez Torrico time to read: 19 min