JavaScript Arduino Electronics, Complete Introduction — Part 2: Blinking an LED

In this series of posts, (after a brief introduction in Part 1) you will learn how to build a circuit with an LED light and the Arduino UNO and switch it on and off from JavaScript inside the Node.js environment (this post). Next, we will look at electronic sensors and how to measure temperature and light (go to Part 3).

You can buy an extended printed version of all these posts on Amazon for only $4.95 / £4.95:
Introduction to JavaScript Electronics on Amazon.com
Introduction to JavaScript Electronics on Amazon.co.uk

Otherwise, you can download a free PDF on www.webondevices.com

If you liked this brief introduction, have a look at my JavaScript Electronics book in which you will learn how to build a Smart Talking Plant:
JavaScript Electronics on Amazon.com
JavaScript Electronics on Amazon.co.uk

Building a circuit on the Arduino UNO

The boards previously discussed are both useful and affordable, but the Arduino UNO is still the number one, most popular board to start developing with. One of the reasons might be that its pin layout is clean and spacious, making it beginner friendly. The extra features mentioned previously, like wireless connection, are all possible with UNO projects, though these will require the addition of external modules or shields.

The most important component of the Arduino UNO is the ATmega328 microcontroller chip. This chip manages the input and output pins (GPIO) of the UNO that are exposed via the header pins along the top and bottom edge of the board.

In short, input pins (ANALOG IN) are designed to measure electricity from sensors like light, sound or temperature.

Power and input pins

Digital pins (DIGITAL) on the other hand can switch electricity on and off for lights, motors, and other electronic components. These pins can also be used as digital sensors which means they can detect if there is or there isn’t incoming electricity. You can use these to work with binary (two-state) sensors like a button.

Digital pins

Both sets of pins can be accessed and controlled from the application code you write and upload onto the board.

The header pins also allow connection to a constant 5V and a 3.3V (5 and 3.3 volts) power source. These will simply let you use the UNO like a battery to power your components. On regular batteries you will find two poles: positive (+) and negative (-). The 5V and 3.3V pins on the Arduino are the positive poles, GND (ground) pins are the negative ones.

Arduino UNO

Next to the header pins is the large USB type-B connector which can be used to communicate with a PC and to upload code. The barrel plug on the bottom left is where you can connect a 9V battery or any other DC power source between 6–20V (the recommended is 7-12V), this can be any mains adapter with the correct size of plug and amount of voltage. This time the Arduino won’t be powered from an external power source, instead, it will be connected via USB to a computer which will, in turn, power the device.

The digital pins on the Arduino board are also power sources, just like the 5V pins. The main difference is that these digital output pins can be switched on and off by the microcontroller chip and the application we upload and run on it.

To demonstrate the behaviour of the output pins let’s build a simple circuit and control it from JavaScript. The “Hello World” of hardware development is blinking an LED, so that’s what we are going to start with. For this project, you will need an Arduino UNO, a regular LED light, a resistor between 150–1kΩ, a breadboard, and a few jumper wires.

Components for the LED blink example project

Resistors can be identified from the coloured stripes on their body. There are many resistor calculators and cheat sheets to help you with that.

The simplest possible circuit we could think of would be an LED lit by a battery. This circuit connects the positive pole of the battery with the positive leg of the LED (long leg) and the negative pole with the negative leg (short leg). Once they are connected, electricity and electrons start flowing through the LED which will inevitably cause it to light up.

Rebuilding this simple circuit on the Arduino will essentially mean replacing the positive pole of the battery with the 5V pin on the Arduino and the negative pole with GND.

The LED powered up from the Arduino

For our LED blink example we will use an output pin as these are the power source pins that we will be able to access from our application code and switch on and off. In this example, I randomly picked output pin number 6.

The LED circuit connected to an output pin

You probably noticed the addition of a small resistor to the circuit and wonder why we need this. Well, there’s one problem: LED lights don’t limit the electric current in the circuit so without a resistor, they would let too much current across. With no resistor in our circuit, we would overdrive and damage our LED in a short amount of time. It would probably only work for a couple of minutes before burning out irreversibly.

Fixed rate resistors

To prevent this from happening, we can limit the flow of electric current through the LED by adding a resistor. Using Ohm’s law (Resistance equals voltage divided by current or R = V / I) we can calculate the exact resistor needed in a certain setup.

In our circuit, the Arduino provides 5 volts but not all of that will fall to the resistor: the LED also has a 2-volt voltage drop which is the ideal supplied voltage for it to work. We also know that the ideal current for our LED is 20mA or 0.02 in Amperes (the datasheet of the LED will give you all this information). Now we need to choose a resistor which will drop that voltage at 20mA. The right value is given by Ohm’s law:

R = V / I

R = (5V - 2V) / 0.02A

R = 150Ω

This means that we need a resistor around 150Ω. You don’t want a resistor that’s less than 150Ω but using a larger one, for example, 220Ω, 500Ω or 1000Ω, would simply resist the flow more which would make our LED dimmer but would extend its lifetime in return.

This circuit is now complete and by switching the 6th output pin on from our program code the LED would light up.

Prototyping breadboards

Breadboards make it easy and quick to build circuit prototypes. They are designed to connect regular male to male jumper wires or the legs of simple components like LEDs, resistors, diodes or capacitors.

LED circuit connections highlighted inside the breadboard

Breadboards essentially help to connect these components together.

When you stick the leg of an LED anywhere in the breadboard, components added to the same row of pins will be connected to the LED.

Here is a larger breadboard with all its pin connections highlighted:

Getting started with Node.js

The LED is now ready to be switched on and off from the JavaScript application. To do this we will need to run JavaScript on the server computer in order to have access to the USB port that we will connect the Arduino to. The first step in this journey is to install the Node.js environment onto our computer.

Installing Node.js is a quick and easy process, and can be done with the official pre-built installers. You can download these from https://nodejs.org/download/.

Once installed, the new node command is available from the Terminal on MacOS or the Command Prompt on Windows. For a Hello World demonstration create a new file called helloworld.js and add this single line of JavaScript to it:

console.log("Hello World");

Entering node helloworld.js to your command line tool (from the same folder that contains the helloworld.js file) will run the JavaScript file and output “Hello World” to the command line.

Node.js “Hello World” in terminal

This might not seem much progress so far, but with Node.js set up we are ready to start building our hardware projects using JavaScript. From this environment, we now have access to the USB port, sensors and many other components of our computer.

For this app, we will be using the Johnny-Five JavaScript library designed for Node.js. This library was created to make hardware prototyping easy for web developers.

Running JavaScript code straight on development boards is only possible with a handful of models and, unfortunately, the Arduino is not one of them. Arduinos require you to write code in the Arduino language, and this can’t be changed currently.

Johnny-Five, and many other Node libraries work around this limitation by requiring a fixed codebase installed onto the Arduino. This codebase essentially exposes an API to communicate with and control the Arduino from external devices. This codebase is called Firmata.

To make the LED blink, we first need to upload the Firmata codebase onto the Arduino UNO. To upload any code onto the board we need to download and install the official Arduino IDE from the Arduino website. The Arduino IDE is just the name of the application you use to write and upload Arduino code onto the board.

Once the IDE is installed, plug your Arduino into the USB port and the green power LED, labeled ON, should light up. Open up the IDE application you just installed and make sure under Tools/Board Arduino/Genuino UNO is selected. You will also need to select the USB port the Arduino is connected to under Tools/Serial Port. The port will only show up in the list if the board is actually connected. If you have problems getting the environment ready please refer to the official installation guide or the troubleshooting page.

The Arduino IDE

At this stage, we won’t be writing anything in the Arduino language. We only opened the IDE to upload the standard Firmata library. Select File/Examples/Firmata/StandardFirmata to open the sketch then hit upload (the green arrow pointing to the right), this will upload the Firmata library to your UNO.

If everything was successful you will see the “Done uploading” message in the green status bar. If you get an error, make sure the Arduino is connected, has power, and that the correct board and port are selected in the Tool menu.

Blinking an LED

The wiring is now complete and the Arduino has the Firmata library loaded. The UNO is ready to take commands from Node.js. Since we are going to be creating an app for Node.js, it’s a good practice to initialise an application in a new folder.

To do that, create a new folder and run npm init from the command line. This will run you through a series of questions about your app but you can just hit enter a couple of times to work with the defaults.

As we will be using the Johnny-Five library to blink our LED, let’s now install it:

npm install johnny-five --save

Notice how a new node_modules folder has been created in your app folder containing your installed libraries. Let’s also create a new file for our Node.js application and name it blink.js. The first thing we need to do in this file is load all the libraries into variables required by our application. In our case it’s only Johnny-Five:

const five = require("johnny-fi");

Next, we initialise a new Board instance that will provide us with all the tools to interact with the Arduino:

const arduino = new five.Board();

When working with jQuery we use the $(document).on("ready", callback) pattern to wait for the document to finish loading before we do anything else. The Arduino and the USB connection also need some time to start up, so we will need to implement a similar event listener before we can send our commands:

arduino.on("ready", function(){
// The board is ready
// We can now blink the LED
});

To blink the LED, let’s initialise a new LED instance inside the callback of the event listener:

// Create an LED on pin number 6
const led = new five.Led(6);

Then below this, we can simply call blink() on the instance:

// Blink the LED every half second
led.blink(500);

And that’s all there is to it!

Here’s the complete blink sketch:

const five = require("johnny-five");const arduino = new five.Board();arduino.on("ready", function(){
const led = new five.Led(10);
led.blink(500);
});

Now that the LED is set up we can try other methods too: led.pulse() will fade the LED in and out instead of just switching with no transition. Conveniently, fade in and out methods are also available:

// fade LED in
led.fadeIn();
// wait 3 seconds then fade out
this.wait(3000, () => {
led.fadeOut();
});

Part 3

In part 3, we will look at a few basic electronic sensors and learn how to measure temperature and light!

Senior Front-end Web Developer, Creative Technologist with over 12 years experience. Loves pushing the limits of HTML and CSS.