Учебник по Node.js

ГЛАВНАЯ СТРАНИЦА Node.js Введение в Node.js Node.js Начало работы Модули Node.js HTTP-модуль Node.js Файловая система Node.js URL-модуль Node.js Node.js NPM События Node.js Загрузить файлы Node.js Электронная почта Node.js

Node.js MySQL

Начать работу с MySQL MySQL Создать базу данных MySQL Создать таблицу MySQL вставить в MySQL выбрать из MySQL Где Порядок MySQL MySQL Удалить Таблица удаления MySQL Обновление MySQL Лимит MySQL MySQL присоединиться

Node.js MongoDB

Начать работу с MongoDB MongoDB Создать базу данных MongoDB Создать коллекцию Вставка MongoDB MongoDB Найти Запрос MongoDB Сортировка MongoDB MongoDB Удалить Коллекция MongoDB Drop Обновление MongoDB Лимит MongoDB Присоединиться к MongoDB

Малиновый Пи

Начать работу с RasPi Введение в RasPi GPIO Мигающий светодиод RasPi Светодиод RasPi и кнопка Проточные светодиоды RasPi Веб-сокет RasPi Веб-сокет со светодиодной подсветкой RasPi RGB Компоненты RasPi

Справочник по Node.js

Встроенные модули

Node.js Raspberry Pi GPIO — светодиод и кнопка


Использование ввода и вывода

В предыдущей главе мы узнали, как использовать Raspberry Pi и его GPIO, чтобы заставить светодиод мигать.

Для этого мы использовали вывод GPIO в качестве «Выхода».

В этой главе мы будем использовать другой вывод GPIO в качестве «входа».

Вместо того, чтобы мигать в течение 5 секунд, мы хотим, чтобы светодиод загорался, когда вы нажимаете кнопку, подключенную к макетной плате.


Что нам нужно?

В этой главе мы создадим простой пример, в котором мы будем управлять светодиодом с помощью кнопки.

Для этого вам нужно:

Щелкните ссылки в списке выше, чтобы просмотреть описания различных компонентов.

Примечание . Резистор, который вам нужен, может отличаться от того, который мы используем, в зависимости от типа используемого вами светодиода. Большинству маленьких светодиодов нужен только небольшой резистор, около 200-500 Ом. Как правило, не критично, какой именно номинал вы используете, но чем меньше номинал резистора, тем ярче будет светить светодиод.

В этой главе мы будем основываться на схеме, построенной в предыдущей главе, так что вы узнаете некоторые части в приведенном выше списке.


Создание схемы

Теперь пришло время построить схему на нашей макетной плате. Мы будем использовать схему, созданную в предыдущей главе , в качестве отправной точки.

Если вы новичок в электронике, мы рекомендуем вам отключить питание Raspberry Pi. И используйте антистатический коврик или заземляющий браслет, чтобы не повредить его.

Правильно выключите Raspberry Pi с помощью команды:

pi@w3demopi:~ $ sudo shutdown -h now

После того, как светодиоды перестанут мигать на Raspberry Pi, вытащите вилку питания из Raspberry Pi (или поверните удлинитель, к которому он подключен).

Простое выдергивание вилки из розетки без надлежащего выключения может привести к повреждению карты памяти.

Raspberry Pi 3 с макетной платой.  Схема светодиодов и кнопок

Посмотрите на приведенную выше иллюстрацию схемы.

  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.