Program to control LED by push button

Write the following code in it and save it as pushButton2.js. Run the program, keep button pressing and releasing. You should see the LED glowing when the button is pressed. When the button is released, the LED should be turned off.

var b = require('bonescript'),
var inputPin = 'P8_16';
var outputPin = 'P8_10';

b.pinMode(inputPin, b.INPUT);
b.pinMode(outputPin, b.OUTPUT);
b.attachInterrupt(inputPin, true, b.CHANGE, interruptCallback);
var exitTimer = setTimeout(exitProgram, 60000);

function interruptCallback(pinObj)
{
  if(pinObj.value==b.HIGH)
  {
    b.digitalWrite(outputPin, b.HIGH);
  }
  else
  {
    b.digitalWrite(outputPin, b.LOW);
  }
}

function exitProgram()
{
  b.digitalWrite(outputPin, b.LOW);
  b.detachInterrupt(inputPin);
  console.log('Interrupt detached'),
}

Explanation

We are using GPIO pin P8_16 as input from the push button and P8_10 as output to the LED. Then we attached interrupt on GPIO input pin P8_16 for the event CHANGE in current. The CHANGE mode means we will be called upon RISE or FALL in current. That means the interrupt will be generated when the button is pressed as well as when the button is released. We specified that the name of interrupt handler function is interruptCallback(). This callback function will be called automatically when the interrupt is generated related to pin P8_16. Then we made sure that the program ends after a minute with the exitProgram() function.

InterruptCallback() is called with a special object as parameter we named pinObj here. Object pinObj has a property value which is HIGH when the button is pressed. It becomes LOW when the button is released. If it is HIGH, we turn on the LED. If it is LOW, we turn off the LED. After a minute, exitTimer gets triggered and the function exitProgram() gets called. Inside it, we turn off the LED and detach the interrupt on input pin P8_16. Now, we are no longer notified if the button is pressed or released.

If you are not getting the desired output, you can insert console.log() before turning the LED on and off. You can also check if the number of interrupts count for gpiolib in /proc/interrupts file is increasing per button press. You can replace the LED ON/OFF code with buzzer speaker beeps or trigger/kill some processes for a more realistic scenario.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.21.47