Node JS and Raspberry pi – Setup

raspberry-back4app-android3x

The Internet of Things is coming closer to our daily lives each day more. With the advent of affordable, connected and small electronics, such as Raspberry Pi or other microcontrollers, we have the feeling that we can remotely control the entire world around us.

However, there is a difference between playing once or twice with electronics and building a reliable application to be actually installed in your home or even sold as a product. One of the features an IoT application must have is a solid Internet backend, in order to handle a high volume of requests, ensure scalability or work even under realistic connectivity.

Four years have come by since Facebook open-sourced Parse. In 2019 Parse developer community released a new version of the framework that provides GraphQL API to fetch data. This new feature will help you even more constructing your IoT application. 

Here comes Back4App and our Parse Server Platform. In addition to providing a robust backend service, we offer easy implementation of other tools, such as Parse Live Query and Push Notifications, with a minimum amount of lines of code!

This tutorial series will teach you how to connect a Raspberry Pi with Parse Server and interact with it by using a real-time Android App. The first part covers the basic setup of a Raspberry Pi, including all the hardware and software needed for it to work properly. We finish by showing the basic code to interact with the outside world using your small computer.

Raspberry Pi works nicely for our IoT purposes since we may run on it anything that runs on Linux and it connects easily to wireless networks, either via integrated WiFi or via USB WiFi modules. It also comes in different versions, ranging from very compact ones to larger and more powerful ones.

Our next tutorial will cover how to connect Raspberry Pi to Parse Server, perform Queries and Live Queries to retrieve objects, and trigger the GPIO pins depending on the attributes of the object. Reciprocally, we will also create objects on Parse Server depending on the status of a GPIO pin. It is already posted here.

The last tutorial will cover how to interact with Parse Server with an Android App, using the same Queries and Live Queries performed on the device side. We will use the App to create the objects that activate the Raspberry pins and display the status of a pin in real-time for the user.

We will also provide our codes for the device and app sides to give you a fast start to develop your own application, which can be range from a remotely activated coffeemaker to a security camera or a door lock for your house!

Prerequisites

Please note we have developed this tutorial based on Raspberry Pi 2B. Some hardware specifications, such as types of connectors, currents and voltages may be different for other models. Models such as Zero may even require you to solder the GPIO pins. However, the software sections are the same for all models.

To complete this tutorial, you need a Raspberry Pi and the following items:

The very minimum:

  • A USB power supply for the Raspberry.

A conventional 5V smartphone charger may be enough. It is not recommended to plug a USB cable into another laptop because of current ratings. If you have further questions on the overall current consumption, please check the information provided in the link below:

https://www.raspberrypi.org/help/faqs/#power

  • An SD card (2B uses a microSD) for installing the OS.

The conventional Raspbian requires 4.5 GB of internal space, but it is possible to install the lighter Raspbian Lite, which requires 1.5 GB and an Ethernet connection during the installation.

  • A USB keyboard.
  • A monitor and a cable (and possibly adapters) to connect it to your Pi

Also strongly recommended:

  • A USB mouse if you do not feel comfortable using an OS only from the command line.
  • An Ethernet connection and a cable, especially if you are planning to install Raspbian Lite.
  • A WiFi USB adapter if you do not want your IoT application to be wired and your board does not come with WiFi.
  • A USB hub, in case your Raspberry does not have enough ports.

Section 1: Downloading and Installing the OS

On your computer, download NOOBS or Raspbian and follow the instructions to copy it to a formatted SD card. They can be downloaded from the following link:

https://www.raspberrypi.org/documentation/installation/noobs.md

Follow the installation instructions. NOOBS provides images for many different OS, but they can only be installed with a network connection. Raspberry 2B requires a wired connection, since it does not come with integrated WiFi, and setting the adapter can only be done AFTER the OS is installed!

It may take some time until the OS installation finishes. After it is done, use pi as login and raspberry as a password (in lowercase letters). We recommend you to change this default configuration later since it is a default for all Raspberry Pi, thus easily hackable.

Configuring the Keyboard

The default keyboard layout is English (UK). After the installation is done, you may type in command line “sudo raspi-config”. Choose the “internationalization” menu, then the “keyboard setup” menu, and search for your model.

Alternatively, edit directly the file “/etc/default/keyboard”. For example, for a Portuguese (BR) ABNT2 keyboard, write in the file:

XKBMODEL="abnt2"  
XKBLAYOUT="br" 
XKBVARIANT="" 
XKBOPTIONS="lv3:alt_switch,compose:rctrl"

Configuring WiFi

You may configure your WiFi connection using the command

sudo iwlist wlan0 scan

and editing the corresponding configuration file

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

according to the instructions on the following link:

https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md

However, if you plan to install a desktop environment, you may connect to wireless networks by clicking on the network symbol on the initialization bar (as you usually do in Windows/Ubuntu).

Optional: Installing a Desktop Environment

If you installed Raspbian Lite (which does not come with a desktop environment) you may follow the link below to install your preferred Graphic Interface.

https://www.raspberrypi.org/forums/viewtopic.php?t=133691

After installing the desktop, your mouse pointer may drag clumsily. If this happens, try opening the file

/boot/cmdline.txt

and adding to the end of the file

usbhid.mousepoll=0

According to the link below:

https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=94075

If you want a text editor, we used geany. Since it is light, it may come in handy for use with the Pi. All you need to do is to type “sudo apt-get install geany”.

You have now finished setting up Raspberry Pi! Now you may use it as you would use any other Linux computer. Continue with our tutorial to learn how to access its pins and use it as an IoT device!

Section 2: Using Raspberry Pi GPIO pins with Python

Raspberry Pi comes with Python installed. To test a sample of our IoT applications, you may blink an LED with this simple ledblink.py script. It is the “Hello World” of electronics!

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)

while 1:
   GPIO.output(11,1)
   print "pin 11 HIGH"
   time.sleep(1)
   GPIO.output(11,0)
   print "pin 11 LOW"
   time.sleep(1)

Make sure you have connected the right GPIO/ground pins on the circuit. Here, the first argument of GPIO.output is the physical number of the pin. Some libraries, such as those that are used on our following tutorials on IoT, use specific numbering only for GPIO pins.

Python is a very versatile language, however, if we plan to build our IoT applications with a higher degree of reliability, we must start with a stable backend services provider. Back4App provides easy interaction with Parse Server running as a backend. To connect our Raspberry with Parse Server, it is best to use a platform such as Javascript, which has a supported API from Parse Server. Fortunately, there is also a version of Node.JS packages to interact with the GPIO pins.

Therefore, from now on, we will develop our embedded code with NodeJS. We begin with a tutorial for installing NodeJS and some required packages.

Section 3: Using Raspberry Pi GPIO pins with NodeJS

Make sure you have an Internet connection. We start by updating our software repository and then upgrade packages already installed. Issue the following commands:

sudo apt update
sudo apt full-upgrade

Install NodeJS and NPM by issuing in the command line:

sudo npm -g l n
sudo n latest

After having the latest versions of Node and NPM, install three fundamental packages for our applications: onoff, parse and pm2.

sudo npm install onoff
sudo npm install parse
sudo npm install -g pm2

Note that pm2 must be installed as global, whereas the others can be local.

Now that we have onoff installed, we may write the same Hello World we did in Python with NodeJS. Let us call it ledblink.js.

var Gpio = require('onoff').Gpio;
var led = new Gpio(4, 'out');
var ledValue = 0;

function blink(){
   ledValue = ledValue ^ 1 // ^ is XOR operator
   led.write(ledValue, function (err) {
      console.log("Gpio pin 4 is " + ledValue);
      if (err) {
         throw (err);
      }
   });
}

setInterval(blink, 1000); // execute blink each 1000 ms

We can run this process by typing node ledblink.js on the command line. However, for a real IoT application, we need to run it automatically when the device is powered and without a keyboard and monitor attached. We use pm2.

Issue the following sequence of commands in the command line:

pm2 start ledblink.js
pm2 list
pm2 save
pm2 startup

These commands start running the desired application under pm2, check which applications are managed by pm2, save the list of processes on pm2 and configure to run the processes on boot automatically. Remember that pm2 startup requires you to copy/paste the command shown in the terminal.

Reboot your Pi. Note that the processes under pm2 will run even before the login is done! This is exactly what we need for our IoT applications.

At this point, we still have not covered how to connect your Raspberry Pi to Parse Server. Please read our following IoT tutorials to continue your development!

Continue your project

In the following weeks, we will come up with tutorials to complete this series. As mentioned earlier in this article, our next tutorial will cover how to connect Raspberry Pi to Parse Server, whereas the last will cover how to interact with Parse Server with an Android App. 

Link for the second part: https://medium.com/@back4apps/connecting-raspberry-pi-to-parse-server-with-nodejs-59cefa25c84a

Note that Parse provides SDKs for a broad set of platforms. Even if you plan to use a platform different from those mentioned here, you may still build your App over Parse with the functionalities developed by Back4App.

How to connect a Raspberry Pi with Parse Server?

– Downloading and Installing the OS
– Installing a Desktop Environment
– Using Raspberry Pi GPIO pins with Python


Leave a reply

Your email address will not be published.