How to Send Data to a Web Page from Arduino — Serial Port

JINGXI GUO
2 min readFeb 13, 2021

--

Sending Arduino DHT22 Temperature and Humidity Data to a Web Server.

I have a habit of collecting data. Since I was young, I have had more than 10 sports bracelets, which can record my heart rate, sleep time, walking steps. Besides, the air purifier at home also reports the air quality to me regularly. Knowing all the data around me is satisfied.

After learning about Arduino, using Arduino to grabbing sensor data in the past six months became the happiest thing in my daily life. However, all this data only can be read in the serial reading software, which is not convenient to read and collect.

One way to solve it is by sending this data to a web server, and the data can display on the web page.

Serial communication to a web server

Three things are needed, Arduino with a sensor, a web server, and a WebSocket for the serial communication.

Arduino with DHT 22

I use an Arduino Nano 33 Iot and a DHT22 here. DHT22 is a temperature-humidity sensor, can detect air relative humidity and Fahrenheit.

All data from DHT22 would be sent in JSON format. A JSON library is needed, to encode the original data into a JSON format. Full Arduino Code is here!

Server

There are three things that are needed to constrain a web page, HTML(the structure of the web page), Javascript(the behavior of the component), and CSS(the appearance of the web page).

To read the data from the serial port,

  1. a running Serial WebSocket on the computer listing to the serial data is needed. (The browser is not allowed to read serial data directly for security reasons).
  2. a serial library also needed to insert into the HTML.
  3. Initial some data placeholder for the data in the HTML.

4. Go to javascript, add some event listener for each placeholder. When the server receives data, the number in <span> will change corresponding.

The full version of javascript is here.

When all thing is set, open the serial WebSocket and run the server locally, select the corresponding port of the Arduino. The data is displayed on the web page.

I just remove my hand from the sensor.

--

--