Node.js Raspberry Pi GPIO - LED 및 푸시 버튼


입력과 출력 모두 사용하기

이전 장에서 우리는 Raspberry Pi와 GPIO를 사용하여 LED를 깜박이게 하는 방법을 배웠습니다.

이를 위해 GPIO 핀을 "출력"으로 사용했습니다.

이 장에서는 다른 GPIO 핀을 "입력"으로 사용합니다.

5초 동안 깜박이는 대신 브레드보드에 연결된 버튼을 누를 때 LED가 켜지길 원합니다.


우리는 무엇이 필요한가?

이 장에서는 푸시 버튼으로 LED 조명을 제어하는 ​​간단한 예를 만들 것입니다.

이를 위해서는 다음이 필요합니다.

다양한 구성 요소에 대한 설명을 보려면 위 목록의 링크를 클릭하십시오.

참고: 필요한 저항기는 사용하는 LED 유형에 따라 사용하는 것과 다를 수 있습니다. 대부분의 소형 LED에는 약 200-500옴의 작은 저항만 있으면 됩니다. 일반적으로 어떤 정확한 값을 사용하는지는 중요하지 않지만 저항 값이 작을수록 LED가 더 밝게 빛납니다.

이 장에서는 지난 장에서 만든 회로를 기반으로 하므로 위 목록의 일부 부품을 인식할 수 있습니다.


회로 구축

이제 브레드보드에 회로를 만들 차례입니다. 우리는 마지막 장에서 만든 회로를 시작점으로 사용할 것입니다.

전자 제품을 처음 접하는 경우 Raspberry Pi의 전원을 끄는 것이 좋습니다. 정전기 방지 매트나 접지 스트랩을 사용하여 손상되지 않도록 하십시오.

다음 명령을 사용하여 Raspberry Pi를 올바르게 종료합니다.

pi@w3demopi:~ $ sudo shutdown -h now

Raspberry Pi에서 LED가 깜박임을 멈추면 Raspberry Pi에서 전원 플러그를 뽑습니다(또는 연결된 전원 스트립을 켭니다).

제대로 종료하지 않고 플러그를 뽑기만 하면 메모리 카드가 손상될 수 있습니다.

브레드보드가 있는 라즈베리 파이 3.  LED 및 버튼 회로

위의 회로도를 보십시오.

  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.