JavaScript Arduino Electronics, Complete Introduction — Part 3: Working with sensors

Mate Marschalko
10 min readDec 7, 2018

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 (go to Part 2). Next, we will look at electronic sensors and how to measure temperature and light (this post).

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

Sensing the world

In this post, we will extend our knowledge by exploring the input pins on the Arduino UNO. We already know that these pins can measure the change in voltage so we will use simple analog sensors that affect the voltage running across them depending on certain changes in the environment.

Components for the sensor projects

For this project, you will need an Arduino UNO, an LM35 or TMP36 temperature sensor, an LDR (light dependent resistor), a breadboard, two 1kΩ resistors, and a few male-to-male jumper wires.

Measuring temperature

For measuring temperature I picked the very common LM35 sensor. This low-cost sensor is rated to operate between -55 and 150°C, with a +/- 0.5°C accuracy. The way this analog sensor works is really simple and in fact, most analog sensors work in a similar way. First, they are powered from a constant power source on two of their pins (+ and -), then, on a third pin, they output a lower voltage value that is proportional to the sensor reading.

Our temperature sensor will be powered from the Arduino UNO’s 5V pin and will output voltage values between 0 and 2 volts changing with the temperature. The LM35’s scale factor is 0.01V/°C which means that a 1 Celsius degree change in air temperature will result in a 0.01-volt change measured on the output pin.

LM35 temperature sensor

Conveniently, the Arduino’s analog input pins are designed to measure and convert voltage into data we can use. In actual numbers, the full range of 0 to 5 volts that can be measured by the analog pins of the Arduino UNO will be mapped to a 0–1024 scale in our program code

Let’s say your sensor returns only 1.5 volts from the supplied 5 volts to the analog input pin you connected it to. The reading in your application will be 307 on the 0–1024 scale because (1.5 / 5) * 1024 is 307.2.

You have the option to retrieve this raw number in your application, but the Johnny-Five library maps the 0–1024 measurement scale to the sensor’s -55 to 150°C range and calculates the resulting temperature from this information for us.

Let’s go back to our temperature sensor and wire it up. Before you start wiring, always make sure you have unplugged your Arduino from the USB or any other power source. Otherwise, you could accidentally stick a wire into the wrong header pin and damage your board or the sensor.

From the three legs of the sensor, the one on the left is the positive, and the one on the right is the negative pole (the flat side of the sensor is the front). We will feed the power in from the 5V (positive) and GND (negative) pins of the Arduino UNO as you can see on this diagram:

Temperature sensor powered up

The make the connections you might want to use a breadboard at this point! The sensor is now powered up and the only pin left to be connected is the output pin in the middle. This will need to be connected to one of the five analog pins on the UNO. These are the ones lined up along the bottom right edge of the board, marked A0 to A5. Let’s connect it to pin A0:

Temperature sensor connected to an analog input pin

Now that the wiring is finished, let’s write the JavaScript code that will read the sensor. Firstly, create a new project (npm init) and name the main file temp.js, starting it off the same way as the LED blink sketch:

const five = require("johnny-five");
const arduino = new five.Board();
arduino.on("ready", function() {
// The Arduino is ready
});

Next, we need to create a new Thermometer sensor instance with a few settings. They include the name of the sensor, and the pin number it’s connected to.

const tempSensor = new five.Thermometer({
controller: "LM35",
pin: "A0"
});

If you have a TMP36 sensor that can still be used the same way. Simply change the controller setting to TMP36 and the wiring remains the same.

After initialising the temperature sensor we can start using the “on data” event listener to catch sensor readings as they arrive from the USB port. The Johnny-Five library leverages the asynchronous capabilities of Node.js which means that sensor readings immediately appear in the “on data” event listener’s callback function. Let’s write this event listener:

tempSensor.on("data", function(){
console.log(this.celsius + "°C");
console.log(this.fahrenheit + "°F");
});

Again, we need to wait for the board to be initialised so both of these blocks will need to go inside the arduino.on("ready", callback) code block.

In the final version of the code, both the Celsius and the Fahrenheit sensor readings are rounded up to one decimal places to make the numbers easier to read.

const five = require("johnny-five");
const arduino = new five.Board();
let celsius = 0;
let fahrenheit = 0;
arduino.on("ready", function(){
const tempSensor = new five.Thermometer({
controller: "LM35",
pin: "A0"
});
tempSensor.on("data", function(){
celsius = this.celsius.toFixed(1);
fahrenheit = this.fahrenheit.toFixed(1);
console.log(celsius + "°C");
console.log(fahrenheit + "°F");
});
});

Here’s the LM35 temperature circuit added to a large breadboard:

Run your code by typing node temp.js into your command line. Check the readings, and if there are anomalies, double check your wiring, make sure the Arduino is connected to the USB port, and the green power light is on. If all is good, we can move on to the light sensor!

Measuring light

Our light sensor is one of the simplest sensors available, known as an LDR, which stands for Light Dependent Resistor. An LDR acts like a regular resistor when added to a circuit, however, the main difference is that the LDR changes its resistance depending on the light conditions.

Light Dependent Resistor or LDR

Unfortunately, resistance isn’t easy for the analog input fields of the Arduino to measure. To convert this resistance change to voltage change, that the input fields are more comfortable measuring, we need to build a simple voltage divider circuit.

A voltage divider circuit splits a larger voltage into a smaller one as per the ratio of the two resistors included in the circuit.

Voltage divider circuit ()fritzing.org

The 5-volt input of this circuit comes from the Arduino through the red wire.

The output voltage through the green wire is directly proportional to the input voltage and the ratio of the resistors
(R1 , R2).

Vout = Vin * (R2 / (R1 + R2))

In this circuit we use two 1000Ω resistors so here’s how the equation looks like after substituting these values in:

Vout = 5V * (1000 / (1000 + 1000))
Vout = 5V * 0.5
Vout = 2.5V

This means that if two of the same resistors are used in a voltage divider circuit the output voltage will be half of the input voltage. 2.5 volts in our case.

Using the equation we also see that changing only one of the resistors will change the output voltage up or down. This here is the key learning for our light sensor circuit!

Let’s now change one of the regular resistors to the light dependent resistor. The resistance of the LDR will change with the light conditions in the voltage divider circuit which will constantly change the output voltage for our input pin in return.

Light sensor circuit completed

When the photoresistor is exposed to light, its resistance decreases so the voltage reading will be higher. Conversely, with less light, the voltage reading will be lower. The changing voltage value is then what the analog input pins of the Arduino factor in to calculate the light measurements.

The light dependent resistor changes its resistance between 150Ω in bright light and 9000Ω in dark. Keeping the original fixed 1000Ω resistor in and using the voltage divider equation we can tell that our output voltage can change between 4.35V and 0.5V which is a good range for the Arduino’s input pin.

Here’s how this circuit looks like on a breadboard:

The circuit is now completed so let’s add the light sensor to our JavaScript app into the Arduino’s “on ready” callback function. We initialise a new lightSensor then add an “on change” event listener:

const lightSensor = new five.Sensor({
pin: "A0",
freq: 250
});
lightSensor.on("change", function(){
console.log(this.value);
});

This piece of code is very similar to how the temperature sensor is handled by the Johnny-Five library. First, a new sensor needs to be initialised with a few settings, then the “on change” event listener is used to wait for readings to arrive.

Here’s the final version of the light sensor code:

const five = require("johnny-five");const arduino = new five.Board();let light = 0;arduino.on("ready", function () {
const lightSensor = new five.Sensor({
pin: "A0",
freq: 250
});

lightSensor.on("change", function () {
light = this.value;
console.log(light);
});
});

Saving this into a new light.js file and entering node light.js into the command line will result in light sensor readings appearing every quarter of a second. The freq (frequency) property is where we can change this behaviour by inputting a number in milliseconds.

Going forward

In this series of posts, you learned the basics of working with the Arduino UNO using Node.js. On Web on Devices (www.webondevices.com) you will find other interesting projects built using similar methods.

Check out the radio controlled car that was rebuilt from scratch using Arduino boards. It connects to a computer wirelessly and with the JavaScript Gamepad API allows the user to drive the car with a USB steering wheel.

Or there’s George, the talking plant. Through his sensors, he can detect temperature, light, motion and soil moisture changes. He complains when he is not happy with any of the sensor readings, and can also answer basic questions. He talks and listens using the WebSpeech API

This smart talking plant project is the final example in my second book called JavaScript Electronics.

There’s also an Arduino gyroscope project that lets you rotate 3D CSS objects on the screen using a physical controller.

Using Node.js to communicate with the Arduino is just one of many ways to use JavaScript for building electronic projects. In these examples, the JavaScript code was running on your computer processor, and we’ve been sending commands to the Arduino.

Other boards like the Raspberry PI, Arduino Yún, Tessel, and the Espruino can actually execute JavaScript without a computer. The Arduino compatible Particle boards expose a RESTful API, and there’s a Node.js library to work with them too. Particle boards connect to the Internet wirelessly, so the Node library doesn’t have to rely on a USB connection.

Follow Web on Devices on Facebook, Twitter or Instagram so you don’t miss any of the cool upcoming projects:

www.facebook.com/webondevices
www.twitter.com/web_on_devices
www.instagram.com/web_on_devices

JavaScript Electronics

Now that you have learned the basics of working with the Arduino UNO, its input and output pins and Node.js you are ready to start working on more complex projects. My second book called JavaScript Electronics discusses all areas covered in this introductory book in a lot more detail and contains many exciting projects to put all that knowledge into use!

There will be many example projects to help you understand some of the key principles in hardware development.

These projects include: controlling an LED light, reading electronic sensors, monitoring the soil moisture levels of a desk plant and alerting the owner with tweet and SMS messages and spoken words with speech synthesis, data logging and data displaying on charts, controlling the volume on a computer with a physical potentiometer, sensing motion with an infrared sensor and sounding an alarm.

In the final chapters of the book, we will look at a few other development boards with different sizes and set of features and compare them to the Arduino UNO.

Get the book now and get started building your very own projects with JavaScript and the Arduino UNO!

JavaScript Electronics on Amazon.com
JavaScript Electronics on Amazon.co.uk

--

--

Mate Marschalko

Senior Creative Developer, Generative AI, Electronics with over 15 years experience | JavaScript, HTML, CSS