Hardware Reference
In-Depth Information
Discussion
In BoneScript, the attachInterrupt() command is used to trigger a function upon
status change of a GPIO port. The last argument ( printStatus ) is the name of the func-
tion to call when the value changes. If you had other work for your Bone to do, you could
list those commands after the attachInterrupt() command, and they would execute
while BoneScript is waiting for activity on the GPIO port. In this simple example, there is
nothing else to do, but the program won't exit, due to the attached event handler. That's
why you have to press ^C (Ctrl-C).
Example 2-2 shows a more traditional way of reading a GPIO port. Here, the
digitalRead() command returns the value of the port synchronously. The code reads
the switch only once, so to see a difference in the output, run it once with the button pushed
and run it a second time without pressing the button.
Example 2-2. Reading a pushbutton by returning a value (pushbutton2.js)
#!/usr/bin/env node
var b = require ( 'bonescript' );
var button = 'P9_42' ;
var state ;
// State of pushbutton
b . pinMode ( button , b . INPUT , 7 , 'pulldown' );
state = b . digitalRead ( button );
console . log ( 'button state = ' + state );
This traditional, synchronous style is useful for small programs, in which you don't need to
be concerned about many different possible events. Asynchronous code helps free up the
processor and operating system to handle other events as they occur. It is also possible to
use digitalRead() asynchronously by providing a callback function, such as in
Example 2-3 .
Example 2-3. Reading a pushbutton once using a callback function
(pushbutton_digitalRead.js)
#!/usr/bin/env node
var b = require ( 'bonescript' );
var button = 'P9_42' ;
b . pinMode ( button , b . INPUT , 7 , 'pulldown' );
b . digitalRead ( button , printStatus );
Search WWH ::




Custom Search