Blinking On-board LEDs
The simplest bonescript we can create right now is to blink one of the four user LEDs. The user LEDs are those four blue LEDs just above the miniUSB port:
On Cloud9 IDE (192.168.7.2:3000), open a new file (click the + tab) and then paste the following script:
var b = require('bonescript'); var state = b.LOW; b.pinMode("USR0", b.OUTPUT); setInterval(toggle, 1000); function toggle() { if(state == b.LOW) state = b.HIGH; else state = b.LOW; b.digitalWrite("USR0", state); }
Click on the “run” button and you should see the right most LED blink every second.
This might confuse some Arduino users here (you said the transition is easy!). There is no setup() and loop() functions on bonescript. As always, the code starts at the very first line.
The line:
var b = require('bonescript');
is very important as it loads the bonescript library. The rest of the lines are then executed. Variables on javascript d[the_ad id=”3059″]on’t require specific data type declaration like int, char, etc. The data type is automatically determined once you assign some object to the variable. Here, the require() Node.JS function returns the bonescript module.
Once we loaded the bonescript module, we are ready to use its functions, constants, etc. We then created a variable named state with a value b.LOW. LOW is one of those bonescript constants.
If you want part of the code to loop continuously, you need to create some function (toggle() in this example) and wrap it around the javascript setInterval() function. Here, the setInterval() function loops every second.
The toggle() function checks the state of the state variable and complements (inverses) it. That state variable is then use to define the status of USR0 via the digitalWrite() function.
Blinking an External LED
We can also use an external LED and change the name of the pin on the program above. For example, if we will attach an LED to GPIO_60 or pin P9_12 (as shown on the diagram), the script becomes:
var b = require('bonescript'); var state = b.LOW; b.pinMode("P9_12", b.OUTPUT); setInterval(toggle, 1000); function toggle() { if(state == b.LOW) state = b.HIGH; else state = b.LOW; b.digitalWrite("P9_12", state); }
Save the file and click the “run” button again. The LED on P9_12 should now be blinking.