Script

Overview

In the context of Johnny-Five, a popular JavaScript robotics and IoT platform, scripts are JavaScript files that are used to control hardware components. These scripts communicate with a microcontroller that runs the Firmata firmware. The execution of these scripts is facilitated by Node.js, which allows them to follow an event-driven structure. This structure is essential for handling asynchronous events and interactions with hardware components effectively.

Execution and Output

When a script is executed, it interacts with the connected hardware, and the output can be observed in the console. For instance, consider the following example of running an altered hello.js script:

Listing 2.10. Running the altered hello.js script

1457808024073 Device(s) /dev/cu.usbmodem1421
1457808024079 Connected /dev/cu.usbmodem1421
1457808027867 Repl Initialized
>> I have changed state 1 times
I have changed state 2 times
I have changed state 3 times
I have changed state 4 times
I have changed state 5 times
I have changed state 6 times
I have changed state 7 times
I have changed state 8 times
I have changed state 9 times
I have changed state 10 times
I shall stop blinking now

In this example, the script is designed to control an LED, making it blink a certain number of times before stopping. The output logs the connection to the device and the initialization of the REPL (Read-Eval-Print Loop), followed by a series of state changes indicating the number of times the LED has blinked. After reaching a predefined number of blinks, the script stops the LED from blinking.

This example demonstrates the flexibility of scripts in Johnny-Five, where callbacks can be used to perform various actions, such as changing the blink frequency or tracking the total number of blinks over time. This event-driven approach allows developers to create complex interactions and behaviors for their hardware projects.