Node.js Raspberry Pi GPIO - LED e botão


Usando entrada e saída

No capítulo anterior aprendemos como usar um Raspberry Pi e seu GPIO para fazer um LED piscar.

Para isso usamos um pino GPIO como "Saída".

Neste capítulo, usaremos outro pino GPIO como "Input".

Em vez de piscar por 5 segundos, queremos que o LED acenda quando você apertar um botão conectado à placa de ensaio.


O que nós precisamos?

Neste capítulo vamos criar um exemplo simples onde controlamos uma luz LED com um botão de pressão.

Para isso você precisa:

Clique nos links na lista acima para obter descrições dos diferentes componentes.

Nota: O resistor que você precisa pode ser diferente do que usamos dependendo do tipo de LED que você usa. A maioria dos LEDs pequenos precisa apenas de um pequeno resistor, em torno de 200-500 ohms. Geralmente não é crítico o valor exato que você usa, mas quanto menor o valor do resistor, mais brilhante o LED brilhará.

Neste capítulo, construiremos o circuito que construímos no capítulo anterior, para que você reconheça algumas das partes da lista acima.


Construindo o Circuito

Agora é hora de construir o circuito em nossa Breadboard. Usaremos o circuito que criamos no capítulo anterior como ponto de partida.

Se você é novo em eletrônica, recomendamos que desligue a energia do Raspberry Pi. E use um tapete antiestático ou uma cinta de aterramento para evitar danificá-lo.

Desligue o Raspberry Pi corretamente com o comando:

pi@w3demopi:~ $ sudo shutdown -h now

Depois que os LEDs pararem de piscar no Raspberry Pi, retire o plugue de alimentação do Raspberry Pi (ou gire o filtro de linha ao qual está conectado).

Basta puxar o plugue sem desligar corretamente pode causar corrupção do cartão de memória.

Raspberry Pi 3 com Breadboard.  Circuito de LED e botão

Observe a ilustração acima do circuito.

  1. Starting with the circuit we created in the last chapter:
    On the Raspberry Pi, connect the female leg of a jumper wire to a 5V power pin. In our example we used Physical Pin 2 (5V, row 1, right column)
  2. On the Breadboard, connect the male leg of the jumper wire connected to the 5V power, to the Power Bus on the right side. That entire column of your breadboard is connected, so it doesn't matter which row. In our example we attached it to row 1
  3. On the Breadboard, connect the push button so that it fits across the Trench. In our example it connects to rows 13 and 15, columns E and F
  4. On the Breadboard, connect one leg of the 1k ohm resistor to the Ground Bus column on the right side, and the other leg to the right side Tie-Point row where it connects to one of the right side legs of the push button. In our example we attached one side to Tie-Point row 13, column J, and the other side to the closest Ground Bus hole
  5. On the Breadboard, connect a male-to-male jumper wire from the right Power Bus, to the right Tie-Point row that connects to the other leg of the push button. In our example we attached one side to Tie-Point row 15, column J, and the other side to the closest Power Bus hole
  6. On the Raspberry Pi, connect the female leg of a jumper wire to a GPIO pin. In our example we used Physical Pin 11 (GPIO 17, row 6, left column)
  7. On the Breadboard, connect the male leg of the jumper wire to left Tie-Point row the Push Button leg that is directly across the Ground connection leg.  In our example we attached it to row 13, column A

Your circuit should now be complete, and your connections should look pretty similar to the illustration above.

Now it is time to boot up the Raspberry Pi, and write the Node.js script to interact with it.



Raspberry Pi and Node.js LED and Button Script

Go to the "nodetest" directory, and create a new file called "buttonled.js":

pi@w3demopi:~ $ nano buttonled.js

The file is now open and can be edited with the built in Nano Editor.

Write, or paste the following:

buttonled.js

var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
var LED = new Gpio(4, 'out'); //use GPIO pin 4 as output
var pushButton = new Gpio(17, 'in', 'both'); //use GPIO pin 17 as input, and 'both' button presses, and releases should be handled

pushButton.watch(function (err, value) { //Watch for hardware interrupts on pushButton GPIO, specify callback function
  if (err) { //if an error
    console.error('There was an error', err); //output error message to console
  return;
  }
  LED.writeSync(value); //turn LED on or off depending on the button state (0 or 1)
});

function unexportOnClose() { //function to run when exiting program
  LED.writeSync(0); // Turn LED off
  LED.unexport(); // Unexport LED GPIO to free resources
  pushButton.unexport(); // Unexport Button GPIO to free resources
};

process.on('SIGINT', unexportOnClose); //function to run when user closes using ctrl+c

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

Run the code:

pi@w3demopi:~ $ node buttonled.js

Now the LED should turn on when you press the button, and turn off when you release it.

End the program with Ctrl+c.