Program to read from push button

Write the following code in Cloud9 and save it as pushButton.js. Run the program, keep the button pressing and releasing. You should see Button is pressed printed when you press the button and Button is released when the button is released. The program will exit after a minute automatically.

var b = require('bonescript'),var loopTime = 1000;
var exitTime = 60000;
var button = 'P8_16';
b.pinMode(button, b.INPUT);
var loopTimer = setInterval(check,loopTime);
var exitTimer = setTimeout(exitProgram,exitTime);

function check()
{
  b.digitalRead(button, checkButton);
}

function checkButton(pinObj)
{
  if(pinObj.value == b.HIGH)
  {
    console.log("Button is pressed");
  }
  else
  {
    console.log("Button is released");
  }
}

function exitProgram()
{
   clearInterval(loopTimer);
   console.log("Program exiting");
} 

Explanation

We first declared that we are going to use the P8_16 pin as the input. That means we will only read from it and not write on it. We set the timer exitTimer to call the function exitProgram() after a minute. Then we set the timer to call the function check() after every second. Inside the function check(), we are calling digitalRead(). In the first parameter, we are specifying that reading is to be done on the 16th pin on the P8 extension header. In the second parameter, we are specifying to call function checkButton() when reading is done. When reading is done, checkButton() will be called with a parameter of type object. We named it pinObj. Inside the checkButton() function, we are checking if the property value of object pinObj is HIGH or not and print accordingly. If the button is pressed when this checking is going on, BeagleBone senses 3.3V at P8_16 and pinObj.value matches to HIGH and our program prints Button is pressed. If something goes bad, the pinObj.err property is set with error information. You can print it for debugging. If there is no error, it is set to undefined.

There is a need to add a pull-down resistor at pole 1 for a reliable output. We are not including it to avoid complexity. Instead of printing, we can glow the LED like we did in previous chapter. In that case, the LED will glow when we press the button and will turn off when the button is released. We are going to write a program to achieve this soon.

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

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