Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Internet of Things Programming with JavaScript

You're reading from  Internet of Things Programming with JavaScript

Product type Book
Published in Feb 2017
Publisher Packt
ISBN-13 9781785888564
Pages 298 pages
Edition 1st Edition
Languages

Table of Contents (15) Chapters

Internet of Things Programming with JavaScript
Credits
About the Author
www.packtpub.com
Customer Feedback
Preface
Getting Started with Raspberry Pi Zero Connecting Things to the Raspberry Pi Zero Connecting Sensors - Measure the Real Things Control-Connected Devices Adding a Webcam to Monitor Your Security System Building a Web Monitor and Controlling Devices from a Dashboard Building a Spy Police with the Internet of Things Dashboard Monitoring and Controlling Your Devices from a Smart Phone Putting It All Together

Chapter 3. Connecting Sensors - Measure the Real Things

The objectives of this book are to build a Home Security System, control domestic appliances by electronically controlled systems with sensors, and monitor them from a dashboard. First, we need to consider that our sensors are connected to an end device that can read the signals and transmit them to the network.

For the end devices, we will use Arduino boards to acquire the readings from the sensors. We can see that the Raspberry Pi doesn't have analog inputs. For this reason, we use an Arduino board to read that signals.

In the previous chapter, we talked about how to connect devices to the Raspberry Pi; in this section, we will see how to interface sensors with Arduino boards to see how to read real signals from different applications for real measurements. We will cover the following topics in this chapter:

  • Using a flow sensor to calculate the volume of water

  • Measuring the concentration of gas with a sensor

  • Measuring the level of alcohol...

Measuring flow sensor to calculate the volume of water


We need to take automatic measurements from the water that we're using in the home. For this project, we will use a sensor to perform this reading and make the reading of measurement automatic.

To make this project, we need the following materials:

Flow Water Sensor and Arduino UNO board:

Hardware connections

Now we have the connections for out flow sensor. We can see that it has three pins -- the red pin is connected to +VCC 5 volts, the black one is connected to GND, and the yellow pin is connected to pin number 2 of the Arduino board as seen in the following image:

Reading the sensor signal

An interrupt is used for the pulses generated by the passage of water to be accounted as follows:

attachInterrupt(0, count_pulse, RISING); 

The interruption is of type RISING counts the pulses that pass from a low state to a high:

Function for counting pulses: 
 
voidcount_pulse() 
{ 
pulse++; 
} 

Reading and counting pulses with Arduino


In this part of the code, we explain that it counts the signals from the sensor using an interrupt, executes, and we have configured it as RISING, so it counts the pulses from digital signal zero to digital signal one:

int pin = 2; 
volatile unsigned int pulse; 
constintpulses_per_litre = 450; 
 
void setup() 
{ 
Serial.begin(9600); 
 
pinMode(pin, INPUT); 
attachInterrupt(0, count_pulse, RISING); 
} 
 
void loop() 
{ 
pulse=0; 
interrupts(); 
delay(1000); 
noInterrupts(); 
 
Serial.print("Pulses per second: "); 
Serial.println(pulse); 
} 
 
voidcount_pulse() 
{ 
pulse++; 
} 

Open the Arduino Serial Monitor, and blow air through the water flow sensor using your mouth. The number of pulses per second will be printed on the Arduino Serial Monitor for each loop, as shown in the following screenshot:

Calculating water flow rate based on the pulses counted


In this part, we measure the pulses and convert them to the flow of water using the following steps:

  1. Open a new Arduino IDE, and copy the following sketch.

  2. Verify and upload the sketch on the Arduino board.

            int pin = 2; 
            volatile unsigned int pulse; 
            constintpulses_per_litre = 450; 
     
            void setup() 
            { 
              Serial.begin(9600); 
     
              pinMode(pin, INPUT); 
              attachInterrupt(0, count_pulse, RISING); 
            } 
    
  3. The following code will calculate the pulses that are reading from the sensor; we divide the number of pulses counted in one second, and we have pulses per liter:

          void loop() 
          { 
            pulse = 0; 
            interrupts(); 
            delay(1000); 
            noInterrupts(); 
     
            Serial.print("Pulses per second: "); 
            Serial.println(pulse); 
     
            Serial...

Calculating flow and volume of water:


You can now either copy the code inside a file called Flow_sensor_measure_volume.ino, or just get the complete code from the folder for this project.

In this part, we calculate the flow and volume from the sensor:

int pin = 2; 
volatile unsigned int pulse; 
float volume = 0; 
floatflow_rate =0; 
constintpulses_per_litre = 450; 

We set up the interrupt:

void setup() 
{ 
Serial.begin(9600); 
pinMode(pin, INPUT); 
attachInterrupt(0, count_pulse, RISING); 
} 

Start the interrupt:

void loop() 
{ 
pulse=0; 
interrupts(); 
delay(1000); 
noInterrupts(); 

Then we display the flow rate of the sensor:

Serial.print("Pulses per second: "); 
Serial.println(pulse); 
 
flow_rate = pulse * 1000/pulses_per_litre; 

We calculate the volume of the sensor:

Serial.print("Water flow rate: "); 
Serial.print(flow_rate); 
Serial.println(" milliliters per second"); 
...

Measuring the concentration of gas


It's important to have in our system a sensor that detects gas so we can apply it in our home in order to detect a gas leak. Now we´re going to describe how to connect to an Arduino board and read the concentration of gas.

In this section, we will use a gas sensor and Methane CH4. In this case, we will use an MQ-4 sensor that can detect concentrations from 200 to 10000 ppm.

This sensor has an analog resistance in its output and can connect to an ADC; it needs a coil energize of 5 volts. The image for the sensor can be seen as follows:

We can find information for the MQ-4 sensor at https://www.sparkfun.com/products/9404.

Connections with the sensor and Arduino board

According to the preceding diagram, we will now see the connections made in the following image:

Open the Arduino IDE, and copy the following sketch:

void setup(){ 
  Serial.begin(9600); 
} 
 
void loop() 
{ 
  float vol; 
  int sensorValue = analogRead(A0); 
...

Measuring the level of alcohol with a sensor


In this section, we will build a very cool project: Your very own Alcohol Breath Analyser. To do that, we are going to use a simple Arduino Uno board along with an ethanol gas sensor:

The following diagram shows the connection of the sensor with the Arduino:

We are now going to write the code for the project. Here, we are simply going to go over the most important parts of the code.

You can now either copy the code inside a file called Sensor_alcohol.ino, or just get the complete code from the folder for this project:

int readings=0; 
void setup(){ 
Serial.begin(9600); 
} 
 
void loop(){ 
lectura=analogRead(A1); 
Serial.print("Level of alcohol= "); 
Serial.println(readings); 
delay(1000); 
} 

When it doesn't detect alcohol, we can see the number of values that the Arduino reads:

If it detects alcohol, we see values from the analog read from Arduino as shown in the following screenshot:

Detecting fire with a sensor


If there's a fire in our home, it's vital to detect it; so in the next section, we will create a project that detects fire with a sensor.

In the following image, we see of the fire sensor module:

You can now either copy the code inside a file called Sensor_fire.ino, or just get the complete code from the folder for this project.

We define the variables for our program at the beginning:

int ledPin = 13;             
int inputPin= 2; 
int val = 0;                    

We define the output signals and the serial communication:

void setup() { 
pinMode(ledPin, OUTPUT);       
pinMode(inputPin, INPUT);      
Serial.begin(9600); 
} 

Now we display the value of the digital signal:

void loop(){ 
val = digitalRead(inputPin); 
Serial.print("val : ");   
Serial.println(val); 
digitalWrite(ledPin, HIGH);  // turn LED ON 

Then we compare: If the value detects a high logic state, it turns off the output; if it reads...

Measuring the humidity for plants


In this section, we will see the testing of humidity inside a plant and the soil using a sensor:

I will now go through the main parts of this first piece of code. Then we set up the serial communication: 

int value;   
 
void setup() { 
Serial.begin(9600); 
}  

In the main loop, we will read the analog signal from the sensor:

void loop(){   
Serial.print("Humidity sensor value:"); 
Value = analogRead(0);   
Serial.print(value);   

We compare the value of the sensor and display the result on the serial interface:

if (Value<= 300)   
Serial.println(" Very wet");   
if ((Value > 300) and (Value<= 700))   
Serial.println(" Wet, do not water");    
if (Value> 700)   
Serial.println(" Dry, you need to water");  
delay(1000);  
} 

Here, the screenshot shows the results of the readings:

The following screenshot shows that the plant doesn't require water;  because it has enough...

Measuring the level of water in a recipient


Somtimes, we need to measure the level of water in a recipient, or if you want to see the level of water in a tank, it is a requirement to measure the levels of water that it has; so in this section, we will explain how to do this.

The sensor is Normally Open. When the water is over the limit, the contact opens, and it sends a signal to the Arduino board. We use pin number 2, which is a digital input:

We declare the variables and const in the program:

const int buttonPin = 2;     // the number of the input sensor pin 
const int ledPin =  13;      // the number of the LED pin 

We also define the states of the digital signals:

// variables will change: 
intbuttonState = 0;         // variable for reading the pushbutton status 

We configure the signals of the program, inputs, and outputs:

void setup() { 
  // initialize the LED pin as an output: 
pinMode(ledPin, OUTPUT); 
  // initialize the pushbutton pin as an input...

Measuring temperature, humidity, and light and displaying data on an LCD


In this section, I will teach you how to monitor temperature, humidity, and light detection on an LCD screen.

Hardware and software requirements

In this project, you will use an Arduino UNO board; but you can also use an Arduino MEGA, which also works perfectly.

For temperature reading,  we require a DHT11 sensor, a resistor of 4.7k, a photoresistor (light sensor), and a 10k resistor.

It also requires a 16 x 2 LCD screen, where you performed the tests; I used an I2C communication module for the screen interfaced with Arduino card. I recommend using this communication since only two pins of Arduino are required for sending data:

Finally, it requires a breadboard and male-male and female-male cables for connections.

Here is the list of components for the project:

  • Arduino UNO

  • Temperature and humidity sensor DHT11

  • LCD Screen 16 x 2

  • Module I2C for LCD

  • A breadboard

  • Cables

We connect the different components:

Here, we can see the image...

Detecting motion with a PIR sensor


We will build a project with a common home automation sensor: a motion sensor (PIR). Have you ever noticed those little white plastic modules that are in the top corners in some rooms of the houses, the modules that change color to red when someone walks in front of them? That's exactly what we will do in this project.

The motion sensor must have three pins: two for the power supply and one for the signal. You should also use a 5V voltage level to be compatible with the Arduino card, which also operates at 5V. The following image shows a simple motion sensor:

For practical purposes, we will use the signal input 8 for connecting the motion sensor, the signal voltage of 5 volts and ground GND.

PIR sensor interfaced with Arduino

PIR sensors detect body heat (infrared energy). Passive infrared sensors are the most widely used motion detectors in home security systems. Once the sensor warms up, it can detect heat and movement in the surrounding areas, creating a...

Detecting if the door is open with a reed switch


An example has been added as an option to implement a magnetic sensor in order to detect when a door or window is open or closed.

The sensor outputs a 0 when it detects the magnetic field and when the field is far away the output would be a 1; so you can determine when the door is open or closed.

The program in the Arduino is performed as follows:

We define the input signal of the sensor, and configure the serial communication:

void setup() { 
  pinMode(sensor, INPUT_PULLUP); 
  Serial.begin(9600); 
} 

We read the state of the sensor:

void loop() { 
state = digitalRead(sensor); 

It compares the digital input and displays the status of the door in the serial interface:

  if (state == LOW){ 
    Serial.println("Door Close"); 
  } 
  if (state == HIGH){ 
    Serial.println("Door Open"); 
  } 
} 

Detecting who can get in the house with a fingerprint sensor


In this section, we will create a project that can help us make a complete security system. In this project, the fingerprint access will be addressed by reading the fingerprint using a fingerprint sensor as shown in the following image:

In this part, we will see how to connect and configure our hardware in order to activate our relay.

Hardware configuration:

As usual, we will use an Arduino Uno board as the brain of the project. The most important part of this project is the fingerprint sensor.

We are first going to see how to assemble the different parts of this project. Let's start by connecting the power supply. Connect the 5V pin from the Arduino board to the red power rail and the GND from Arduino to the blue power rail on the breadboard.

Now, let's connect the fingerprint sensor. First, connect the power by connecting the cables to their respective color on the breadboard. Then, connect the white wire from the sensor to Arduino...

Summary


In this chapter, we saw how to interact with different sensors connected to the Arduino board, such as flow current for energy consumption, detecting a risk in the home, implementing a gas sensor, implementing flow water sensor to measure the water volume, making a security system, and controlling access with a fingerprint sensor. All of these sensors can be integrate a complete system for monitoring and controlling everything you work on any project.

In the next chapter, we will see how to integrate everything for monitoring and controlling a complete system, and reading the sensors and actuators in a dashboard using your Arduino board and the Raspberry Pi Zero as a central interface.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Internet of Things Programming with JavaScript
Published in: Feb 2017 Publisher: Packt ISBN-13: 9781785888564
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}