Blink

Blinking an LED is a fundamental task in hardware programming, often used as an introductory exercise for learning how to control electronic components with code. This task involves turning an LED on and off at regular intervals, creating a blinking effect. In the context of Arduino and JavaScript, this can be achieved using various methods and libraries, such as Johnny-Five.

Blinking an LED with Arduino

To blink an LED on an Arduino, you need to write a sketch that alternates a digital pin between HIGH and LOW states. This alternation causes the LED connected to that pin to turn on and off. The process involves setting up the pin as an output and using a loop to toggle the pin state at desired intervals.

Blinking an LED with Johnny-Five

Johnny-Five is a JavaScript library that simplifies the process of interacting with hardware components like LEDs. In Johnny-Five, you can make an LED blink using the blink method on an LED object. This method takes a period in milliseconds as an argument, which defines the interval at which the LED will blink.

Example: Basic LED Blinking

Below is an example of how to make an LED blink using Johnny-Five:

Listing 2.8. LED blinking with Johnny-Five

board.on('ready', () => {
  const led = new five.Led(13);
  led.blink(500);
});

In this example, the LED connected to pin 13 will blink every 500 milliseconds. The ready event is fired once the board is ready, and the function passed to it is executed once.

Stopping the Blink

To stop the LED from blinking, you can use a callback function with the blink method. This callback is invoked every time the LED changes state (on or off). You can use this feature to implement logic that stops the blinking after a certain number of blinks.

Listing 2.9. Using LED callbacks in hello.js

const five = require('johnny-five');
const board = new five.Board();

board.on('ready', () => {
  const led = new five.Led(13);
  var blinkCount = 0;                                 
  const blinkMax = 10;                                

  led.blink(500, () => {                              
    blinkCount++;
    console.log(`I have changed state ${blinkCount} times`);
    if (blinkCount >= blinkMax) {
      console.log('I shall stop blinking now');
      led.stop();                                     
    }
  });
});

In this example, the LED will blink 10 times before stopping. The blinkCount variable keeps track of how many times the LED has blinked, and once it reaches blinkMax, the stop method is called to cease the blinking. This demonstrates how JavaScript's callback functions can be used to interact with hardware in a more dynamic way.