Node.js y Raspberry Pi


Raspberry Pi es una computadora pequeña y multiusos.

Con Node.js puedes hacer cosas increíbles con tu Raspberry Pi.


¿Qué es la Raspberry Pi?

La Raspberry Pi es una computadora del tamaño de una tarjeta de crédito pequeña, asequible y sorprendentemente capaz.

Está desarrollado por la Fundación Raspberry Pi y podría ser la tecnología más versátil jamás creada.

El objetivo del creador Eben Upton era crear un dispositivo de bajo costo que mejorara las habilidades de programación y la comprensión del hardware.

Debido al pequeño tamaño y al precio del dispositivo, se ha convertido en el centro de una amplia gama de proyectos por parte de entusiastas de la electrónica, fabricantes y manitas.


Raspberry Pi y Node.js

El Raspberry Pi tiene una fila de pines GPIO (entrada/salida de propósito general), y estos se pueden usar para interactuar de maneras asombrosas con el mundo real. Este tutorial se centrará en cómo usarlos con Node.js.


¿Qué necesito?

Para este tutorial necesitas una Raspberry Pi. En nuestros ejemplos, usamos una Raspberry Pi 3, pero este tutorial debería funcionar para la mayoría de las versiones.

Hardware necesario:

  • computadora frambuesa pi
  • Tarjeta de memoria MicroSD (Recomendamos una clase 10 con 16 GB o superior)
  • Adaptador de tarjeta de memoria MicroSD a SD (generalmente incluido con la tarjeta MicroSD)
  • Fuente de alimentación micro USB para alimentar la Raspberry Pi (se recomiendan 2,5 A o más)
  • Conexión de cable WiFi/Ethernet para Raspberry Pi (no es necesario para Raspberry Pi 3 ya que tiene WiFi incorporado)
  • Una computadora que funcione con Internet y un lector de tarjetas de memoria SD (utilizado para obtener el sistema operativo (Sistema operativo) para Raspberry Pi en la tarjeta de memoria). En nuestro tutorial, usamos una computadora con Windows para esto, pero puede usar una computadora Mac o Linux si lo prefiere.
  • Monitor HDMI, teclado USB (los necesitamos solo temporalmente para el primer arranque de la Raspberry Pi)

En capítulos posteriores de este tutorial, utilizaremos sensores o dispositivos especiales que conectaremos a la Raspberry Pi. Los especificaremos como requisitos especiales en los capítulos correspondientes.

Si ya tiene una Raspberry Pi configurada con Raspbian, Internet y SSH habilitado, puede saltar al paso "Instalar Node.js en Raspberry Pi".


Escribir la imagen del sistema operativo Raspbian en la tarjeta MicroSD

Antes de que podamos comenzar a usar nuestra Raspberry Pi para cualquier cosa, necesitamos instalar un sistema operativo.

Raspbian es un sistema operativo gratuito basado en Debian Linux y está optimizado para Raspberry Pi.

Descargue la última imagen de Raspbian desde https://www.raspberrypi.org/downloads/raspbian/ a su computadora.

Usamos la versión "LITE" en nuestro tutorial, ya que estamos configurando el Raspberry Pi como un servidor sin cabeza (nos conectaremos a él a través de SSH, sin tener un teclado/pantalla conectado). Puede usar la versión que desee, pero este tutorial está escrito con la versión "LITE" como enfoque.

Inserte la tarjeta de memoria MicroSD en su computadora (a través del adaptador SD si es necesario). Abra el Explorador de archivos para verificar que esté operativo.

Etcher es un programa para flashear imágenes en tarjetas de memoria. Descargue e instale Etcher desde: https://etcher.io/

Iniciar grabador:

Iniciar grabador

Click "Select image" button and find the Raspbian zip file that you downloaded.

Click the "Select drive" button and specify the memory card as the target location.

Click the "Flash!" button to write the image to the memory card.

After Etcher is finished writing the image to the memory card, remove it from your computer.


Set up Your Raspberry Pi

To get the Raspberry Pi ready to boot we need to:

  1. Insert the MicroSD memory card into the Raspberry Pi
  2. Connect the USB keyboard
  3. Connect the HDMI cable
  4. Connect the USB Wi-Fi adapter (or Ethernet cable). Skip this step if you are using a Raspberry Pi 3
  5. Connect the micro USB power supply
  6. The Raspberry Pi should now be booting up

When the Raspberry Pi is finished booting up, log in using username: pi and password: raspberry


Set Up Network on the Raspberry Pi

If you will use a Ethernet cable to connect your Raspberry Pi to the internet, you can skip this step.

For this section we will assume you have a Raspberry Pi 3, with built in WiFi.

Start by scanning for wireless networks:

pi@raspberrypi:~ $ sudo iwlist wlan0 scan

This will list all of the available WiFi networks. (It also confirms that your WiFi is working)

Now we need to open the wpa-supplicant file, to add the network you want to connect to:

pi@raspberrypi:~ $ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

This will open the file in the Nano editor. Add the following to the bottom of the file (change wifiName and wifiPassword with the actual network name and password):

network={
  ssid="wifiName"
  psk="wifiPassword"
}

Press "Ctrl+x" to save the code. Confirm with "y", and confirm the name with "Enter".

And reboot the Raspberry Pi:

pi@raspberrypi:~ $ sudo reboot

After reboot, log in again, and confirm that the WiFi is connected and working:

pi@raspberrypi:~ $ ifconfig wlan0

If the WiFi is working propery, the information displayed should include an IP address, similar to this:

inet addr:192.168.1.50

Write down that IP address, as we will use it to connect to the Raspberry Pi via SSH.



Enable SSH, Change Hostname and Password

Now your Raspberry Pi is connected to the internet, it is time to enable SSH.

SSH allows you up use the Raspberry Pi without having a monitor and keyboard connected to it.

(You will need a SSH client for this on your non-Raspberry Pi computer. We use PuTTY for windows)

Open the Raspberry Pi Software Configuration Tool:

pi@raspberrypi:~ $ sudo raspi-config

You should see a menu like this:

raspi-config Main Screen

Select option 5 Interfacing Options:

raspi-config Main Screen

Select option P2 SSH, to activate SSH:

raspi-config Main Screen

Confirm with YES, to activate SSH:

raspi-config Main Screen

SSH is now enabled, and you should be in the main menu again.

Select 1 Change User Password, and follow the instructions to change the password. Choose a secure password, but something you will remember:

raspi-config Main Screen

After you have finished changing the password, you should be back in the main menu.

Select 2 Hostname, and follow the instructions to change the hostname:

raspi-config Main Screen

After you have finished changing the hostname, you should be back in the main menu.

Now we will close the menu and save the changes:

raspi-config Main Screen

When selecting Finish, you will get the option to reboot. Select Yes to reboot the Raspberry Pi.

raspi-config Main Screen

You can now unplug the monitor and keyboard from the Raspberry Pi, and we can log in using out SSH client.

Open PuTTY, type in the IP address for your Raspberry Pi, and click Open:

raspi-config Main Screen

Log in using the username pi and the new password you specified.

You should now see a command line like this: (we used w3demopi as our hostname)

pi@w3demopi:~ $

You are now able to run your Raspberry Pi in "Headless-mode", meaning you do not need a monitor or keyboard. And if you have a WiFi connection, you do not need a ethernet cable either, just the power cable!


Install Node.js on Raspberry Pi

With the Raspberry Pi properly set up, login in via SSH, and update your Raspberry Pi system packages to their latest versions.

Update your system package list:

pi@w3demopi:~ $ sudo apt-get update

Upgrade all your installed packages to their latest version:

pi@w3demopi:~ $ sudo apt-get dist-upgrade

Doing this regularly will keep your Raspberry Pi installation up to date.

To download and install newest version of Node.js, use the following command:

pi@w3demopi:~ $ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -

Now install it by running:

pi@w3demopi:~ $ sudo apt-get install -y nodejs

Check that the installation was successful, and the version number of Node.js with:

pi@w3demopi:~ $ node -v

Get Started with Raspberry Pi and Node.js

Now you have a Raspberry Pi with Node.js installed!

If you want to learn more about Node.js, follow our tutorial: https://www.w3schools.com/nodejs/

In the next chapter we will get to know the GPIO and how to use it with Node.js.