Controlling a relay from a Raspberry Pi Zero using Restful API and Node.js

In this section, we will show you how to control a relay module connected to an Arduino UNO board, a relay for sending commands from a web browser. Let's do it.

JSON structure

JavaScript Object Notation  (JSON) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

First, we need to know how to apply the JSON format that we use to describe this structure, as follows:

{"data": "Pin D6 set to 1", "id": "1", "name": "Arduino", "connected": true}

This is the format that we need to follow and make responsive:

  • Data: Defines the number of the command and then describes the definition of the command
  • Name: Follows the name of the device
  • Connected: Confirms if the device is connected or not

All the data that is between the { } defines our JSON format.

Commands with the aREST API

Using the aREST command like this, we can define our Arduino and the devices, and then control them from a web browser. The following are examples of the commands from the aREST API:

  • IP_Address_of the device/mode/6/o: This configures the digital pin 6 like an output pin
  • IP_Address_of the device /digital/6/1: Configures output 6 and makes the function like a digitalwrite. For example: http://192.168.1.100/digital/6/1; we define the IP address of the device and the number of the pin that will be activated.

Installing Node.js on your Raspberry Pi Zero

Node.js is a tool that will allow us to create servers running in the device, using code in JavaScript. The most important thing is that we will apply this framework to build a web server using this code.

Using Node.js means that we configure a web server that will open a port and the devices can be connected to the web server.

With the following command, you will install Node.js in your Raspberry Pi Zero:

sudo apt-get install nodejs

NPM is the default package manager for the JavaScript runtime environment with Node.js. To configure and install the aREST module, type the following line in your terminal:

sudo npm install arest

The Express philosophy is to provide small, robust tooling for HTTP servers, making it a great solution for single-page applications, websites, hybrids, or public HTTP APIs.

We can also need to configure the express module with the following command:

sudo npm install express
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.101.63