Login

Control the GPIO pins by hosting a REST API on NodeMCU’s local server

Objectives

  • Set up a local web server using NodeMCU
  • Host a REST API on the local web server to control GPIO pins

Things

  1. NodeMCU (quantity: 1 no)
  2. Micro USB cable A to B (quantity: 1 no)
  3. REST client app
  4. Arduino IDE on the computer

Let’s begin!

GPIO stands for General Purpose Input Output. All digital pins on the NodeMCU are GPIO pins. A REST API is an web interface which follows a set of rules called REST rules. You can interact with a REST API on a server by making HTTP calls.

There are generally four types of calls which are made to a REST API – GET (retrieve data), POST (post data), PUT (update existing data), DELETE (delete existing data).

Any device which interacts with a REST API is called a REST client. We will be using a mobile app as a REST Client. There are a number of apps available. We will be using the one called Advanced Rest API client.

Final Code

We will first need to upload the code to the NodeMCU so that the HTTP server is running and the REST API is active. Then we can test the server using the REST client app.

You will need to install ArduinoJson library version 5.13.1. Go to Sketch -> Include Library -> Manage libraries. Search for ArduinoJson, select version 5.13.1 and click Install.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Uploading the code

Step 1: Enter the final code in the Arduino IDE window.

  • When you click on New to open a new blank code in the Arduino IDE, you will get a new window with two functions: void setup() and void loop()
  • You can either type commands as shown in the final code under void setup() and void loop() functions or
  • Delete the contents of this window. Then copy and paste the final code in the Arduino IDE window.

Step 2: Compile/ verify the code by clicking on the verify button.

  • Make sure the board is connected to your computer
  • Check if the correct board and port is selected.

Step 3: Upload the code by clicking on the upload button, which is right next to the verify button.

  • The Arduino IDE provides a progress bar when it’s uploading.
  • After it is done, you will see “Done uploading” on the bottom left of your IDE.
  • If you encounter any errors, you need to go back to the code and fix the errors.

There you go!

The HTTP server with the REST API is now active and running. We can now test it with the REST client app

We would love to see what you build out of these learnings!

Click here to submit your projects, share it with the world and stand a chance to be rewarded.

top

Knowledge and Content by Li2 Technologies | © 2021 NASSCOM Foundation | All rights reserved

X