Header Ads

Header ADS

Web Server with NodeMCU WebSocket

Uploading sensor data to web servers is one of the core ideas for Internet of Things (IoT). Such data are often small-sized and are continuously updated over time. And while HTTP performs satisfactorily for simple applications, like how I showed in my NodeMCU web server tutorial, there is a need for a much better method when speed and data-size are critical factors. I’ve already shown how to use MQTT as a faster and lightweight alternative to HTTP. In this tutorial, I will demonstrate how to use NodeMCU WebSocket.

Introduction to WebSocket

WebSocket, like HTTP, is a communications protocol over TCP. The key differences between WebSocket and HTTP is that the former operates full-duplex, bi-directional and at single TCP connection.

Full-duplex means two objects communicating with each other can send and receive messages simultaneously, like when you’re talking over the telephone. In contrast, half-duplex is non-simultaneous messaging, like when you’re using a walkie-talkie. A full-duplex system is faster than a half-duplex system.
 WebSocket vs. HTTP via DevCentral

As a consequence of being full-duplex, WebSocket is also bidirectional. The client always initiates the communication in HTTP. The client or the server can initiate the communication in WebSocket.

Finally, WebSocket is established in a single TCP connection. The request-response pattern needs to be repeated for every HTTP request by the client.

 NodeMCU WebSocket Library

A WebSocket library for NodeMCU using the Arduino IDE can be downloaded in this repository.

Extract the library to the Arduino libraries folder and then restart the IDE (if it was open when you were downloading the library).

The library has plenty of examples (File -> Examples ->WebSockets). I will create my own code here that is similar to the one on the NodeMCU web server tutorial via HTTP:

Upload the code to your NodeMCU and, if successful, open Arduino's serial monitor to see something like this:
Then go to your preferred web browser and type in the address of the NodeMCU (shown in the screenshot above) on the address bar. You should see something like this:

 To see what this code does, wire a LED to D7 (which is GPIO #13) on your NodeMCU. Check here for example with code.

Then click the buttons on the web page. The LED should respond to the button press:

No comments

Powered by Blogger.