Arduino Pressure Sensors

Arduino Pressure Sensors 2018

Arduino Sensors: Arduino Pressure Sensors

sensor is a device that can detect some events and changes and gives the corresponding output. The output is generally in the form of an electronic signal. In the electronics field, sensors are divided into analog and digital sensors. Digital sensors can only detect 2 types of states, either on or off. For example, A button is a digital sensor, that can only sense 2 states either on or off.
 
Arduino Pressure Sensors

Analog sensors, however, can sense a range of values. The LDR, for example, is an analog sensor that changes the output voltage depending on the light level cast on the sensor surface. light dependent resistor (LDR) that gives the outputs a voltage, that depends on the level of light cast on the sensors.

 

The remaining examples will use sensors that include pre-built circuits on a PCB board. In this blog, we will also take a look at different ways to communicate with our prototyping board and how to send data back to the computer and Arduino Pressure Sensors 2018.

 

If you run out of digital pins, you can always use the analog pins even for reading digital sensors. Just remember that the output will be read in the range of 0 to 1023 and not HIGH and LOW if you are reading them as analog pins. The analog pins can be used as digital pins as well. Analog pin A1 is the same as digital pin 14, and so on.

 

Sensors

In this blog, we will cover bend sensors, pressure sensors, light sensors, accelerometer, gyroscopes, and compass sensors. A sensor is a device that can detect events or changes of different kinds and can provide a corresponding output. It is a device that changes some characteristics due to external conditions and can be connected to a circuit, converting the signal so that it can be interpreted by a microprocessor.

 

With some sensors, you need to build your own circuitry and interpret the data provided by the sensor through code. Some complex sensors have a built-in communication protocol, which enables them to provide data corresponding to their function. The sensitivity of a sensor indicates how much the output data can change.

 

A bend sensor

bend_sensor

The first sensor we will try out is a bend sensor. Sometimes it is also known as a flex sensor, and the name gives a good hint at what kind of sensor this is. As the name suggests, this sensor senses bends. The sensor works similarly to most analog sensors. These sensors are built on the same principle, where they take a voltage input and the sensor acts as a resistor that can change its own resistance.

 

The component labeled as 1, is a regular resistor, which measures 10kΩ. Resistors are some of the most common electronic components that you can find and are used in almost all electronic devices.

 

A resistor is used to limit the flow of current in an electronic signal. This means that if you apply a voltage at one end of the resistor, it will output a lower voltage at the other end. In the case of this example, we need a resistor to create what is known as a voltage divider in order to get good values from our sensor.

 

The component labeled number 2. These sensors detect bending in one direction. When left untouched, the bend sensor will measure about 10kΩ, and when fully bent it will measure around 20 kΩ. Number 3, is the FLORA board we used in the previous blog:

 

The 10kΩ resistor 2. A Bend/flex sensor 3. The FLORA board 4. The breadboard Number 4, is a breadboard, and this is not technically a component. Breadboards are used for prototyping with electronics. When electronics are made, components are soldered together, but before you show how everything connects and what you want to make, it's good if you can try connections out before soldering them together. This is when a breadboard comes in handy.

 

The lines of a breadboard are connected vertically in the middle of the board and horizontally at the edges. The + and – line marks the horizontal connections, while in the middle segment of the board the lines connect between the numbers and down from a to j.

 

Working with Sensors

Breadboards make a circuit bulkier, but they are not used for the final designs. They are mainly used for trying out connections before soldering your components together. Wires have also been added, so we can connect our sensor to the FLORA board, later on, you will find the necessary connections to be made: On the left side of the resister, we have a wire that connects to the 3.3 V output of the FLORA board. Resistors have no polarity, which means the direction of connection does not matter.

 

They work both ways so to say. On the right side of the resistor, we connected one of the connections to the bend sensor and one to a wire that we will connect to an analog pin of the FORA board.

bend_sensor

The second connection of the bend sensor is connected to the ground. In this circuit, power will be passed and limited through the resistor. Once on the other side of the resistor, some of the electricity will be passed through the sensor and some will be passed back to the analog pin. When we bend the sensor, we make it harder or easier for the electricity to pass through the sensor depending on how we bend it.

 

The overload of electricity that can't be passed through the sensor will be passed back along the analog pin, which we will read through our FLORA board.

  • Cable number 1 connects to 3.3 V
  • Cable number 2 connects to D10
  • Cable number 3 connects to GND

 

In order to check that everything works, we need to connect the FLORA board to our computer and write some code. For all of the sensor examples in this blog, we will be using the serial library to send the data back to the serial monitor in your Arduino IDE. Serial communication is not used in every sketch, so to save memory space, the code that enables the communications is put in a library, which we can call upon when we need it.

 

This is why all serial commands start with Serial, which means that we are calling any command afterward from the library. Serial communication is just one of the many communication protocols that can be used. Communication protocols are basically a set of rules on how two devices should act in order to communicate with each other.

//variable to store the analog pin

int bendSensor = 10;
void setup(){
//Start the serial communication
Serial.begin(9600);
}
void loop(){
//Save the data from the sensor into storeData int storeData=analogRead(bendSensor);
//Print the data and add a new line
Serial.println(storeData);
//Give the computer some time to receive the data delay(200);
}

 

The setup is where we initialize the serial communication. When this is done, When using serial communication, always use a delay in your sketch to give the receiving side some time to be able to read it. If you don't need to read it at humanly readable speed, a delay of about 30 milliseconds will suffice. In the bottom of the right corner in the serial monitor, you will find a drop-down menu with the available speeds.

 

If there is no reason for choosing a particular speed, I usually use 9600 baud. This rate is fast enough for most applications and is supported by most devices. At the top of the serial monitor, you will find an input box where you can send information to the FLORA board. The preceding also shows data that is sent from the sensor.

 

In my case, the sensor outputs a steady value of 489 when left untouched. When the sensor is fully bent, the value increases to around 650. In the previous code example, the data was sent back to the computer using the Serial.println() command, which adds a carriage return.

 

This means that when the data is received by the computer, it adds it to a new line when presented on the screen. You can send data without the carriage return by simply using the Serial.print()command. However, this will keep on printing data on the right, on the same line, until the Arduino sends a line return.

 

The data can instead be formatted by the serial monitor using the drop-down menu to the left of the speed menu. In this drop-down, you will find different formatting options such as adding a new line, carriage return, both, or none of them. Remember that the built-in formatting in the serial monitor only works for incoming data. On outgoing data, you will need to format your data in code. In the next example, we will take a look at how to interact with a pressure sensor.

 

Arduino Pressure sensors

Pressure_sensor

This example follows the same principals as the previous bend sensor, but this time, we will try out a pressure sensor. The pressure sensor does the same thing as the bend sensor where it regulates a voltage output depending on the pressure applied to the sensor. If the sensor is pressed, it will add to the resistance and the voltage coming out the other end of the sensor will be lower. Again, we will use the FLORA board to detect the changes in the value of the output.

 

The FLORA board, breadboard, pressure sensor and 10 kΩ resistors From the left, you have the FLORA board, breadboard, pressure sensor, and a 10 kΩ resistor. In order to make the circuit, we will be using the same setup as we did in the bend sensor example. The pressure sensor is also known as a force sensor and can be used to detect physical force, touching, or even weight.

 

If weight is what you are looking for, this might not be the best choice since this sensor doesn't output an actual weight value, though by using some fixed weights and some calibration you could make a crude scale.

 

Let's take a closer look at the connections:

On the side of the resistor with only one wire, we have a connection to the 3.3V pin on the FLORA board. On the other side of the resistor, we have a connection to the first pin of the pressure sensor and a wire connection to D12 on the FLORA board. The second pin of the pressure sensor connects to GND of the FLORA board.

 

To test the range of the sensor, you can use the same code used for the bend sensor, as it prints the analog data back to your serial monitor. In the case of the sensor, I was using, it gave me almost the full range from 0 up to 1023. In the following example, we use the value from the sensor to make a small visualization using the onboard LED on the FLORA board:

declare variables to store pin numbers

int pressureSensor=12;
int led=13;
void setup() {
//declar pin as an output
pinMode(led,OUTPUT);
}
void loop() {
// read the input on analog pin 12:
int pressureValue = analogRead(pressureSensor);
//turn the led on
digitalWrite(led,HIGH);
//wait using the value from the sensordelay(pressureValue);
//turn the led off
digitalWrite(led,LOW);
//turn the led on
delay(pressureValue);
}

In the sketch, we use the data from the sensor to set the delay time of the LED. When you press the sensor, this will lower the value, which will lessen the delay between blinks. This, in turn, will mean that the LED will start to blink faster. Remember that your sensor might have a slightly different value range, so you might need to modify the value in order to find a satisfactory blinking speed.

 

The best way is to print out your sensor data to the serial monitor using serial communication in order to check your range of values. Then, you can add or subtract with any amount you prefer inside the delay, an example of this is shown as follows:

digitalWrite(led,HIGH);


//wait using the value from the sensor

delay(pressureValue+1000);

//turn the led off

digitalWrite(led,LOW);

//turn the led on

delay(pressureValue+1000);
 
In the next sketch, for example, we will make a mini-game where the goal is to find the sweet spot. The code is set up so that you have to press the sensor in order to find the hidden spot defined in the code. Once you find it, the LED will start to shine for as long as you can hold the spot:
 
//declare variables to store pin number
int pressureSensor=10;
int led=7;
void setup()
{
//declare pin as an output
pinMode(led,OUTPUT);
Serial.begin(9600);
}
void loop() {
//read the input on analog pin 12:
int pressureValue = analogRead(pressureSensor);
//as long as the value is in between 500 and 700 keep on looping while(pressureValue>500 && pressureValue<700){
//turn the led on
digitalWrite(led,HIGH);
//check so that the value
pressureValue = analogRead(pressureSensor);
}
//turn the led off
digitalWrite(led,LOW);
}

The sweet spot is hidden in the range of 500 to 700. When the value is in the sweet spot range, we enter the while loop, which will keep on looping until the condition for the while loop is no longer met. This is why we need to add an additional reading of the sensor inside the loop, or the code will get stuck inside the while loop forever. As long as you can keep the value inside the range, the LED will light up.

 

If you press the sensor too hard or too little, the while loop will be broken and the LED will turn off. If you find it too easy to find the sweet spot, try to decrease the range. This will make it much hard to find the spot.

 

Light-dependent resistors

In this example, we will have a closer look at an LDR. The principle behind it is the same as the bend sensor used in previous bend sensor example. Depending on the light levels cast onto the sensor, the sensor changes its output voltage. LDR comes in different shapes and sizes and the LDR comes premounted with a surface mounted resistor on a small PCB manufactured by Adafruit. The principal of the PCB is similar to the circuit created using a breadboard and components.

 

The difference is that in the case of the PCB, in this example, everything is mounted nicely and we only need to attach it to the FLORA board using alligator clips, the LDR PCB has three connections VCC, OUT, and GND.

 

Sometimes VCC is used to indicate power in. OUT, in this case, is the output signal, which is an analog signal, you will find the necessary connections to the FLORA board. There is not a lot of space between the connections, so make sure that the alligator clips do not touch one another.

 

Since we are using the same connections as in the previous example in the blog, you can use the same code to test your sensor. The following sketch is based on the same code as used in the bend/lex sensor example, but we have implemented some code to remap the range of values from the sensor into a new larger range of values.

//Variable to store the pin

int ldrSensor = 10;
void setup(){
//Start the serial communication
Serial.begin(9600);
}
void loop(){
//Save the data from the sensor into storeData int storeData=analogRead(ldrSensor);
//Re-map storeData to a new range of values int mapValue=map(storeData,130,430,0,2000);
//Print the re-mapped value
Serial.println(mapValue);
//Give the computer some time to print
delay(200);
}

The map() function in the code is used to take on a value range and remap it to a new range of values. In order for this function to work, you need to know the range of values possible from the sensor you are using. Using the code from the bend sensor example, you can do this. In order to check you LDR sensor range, you need to print the data to your serial monitor.

 

First, check the value you get when the LDR is not covered and write this down. Then, cover the LDR as much as possible and check the value. Make sure to remember this value as well since you'll need it. The map function takes five parameters map(sensorValue, sensor in, sensorMax, desiredMin, and desired max). The first parameter is the actual sensor data. The second and third are the minimum and maximum values from the sensor, which you wrote down from the previous test.

 

The fourth and fifth are the minimum and maximum values of your desired range. In the case of the LDR that I an using, this gives a range of values between 130 to 430, which we will choose to remap into a value range of 0 to 2000. The map function comes in handy in many cases when you want to use the data from a sensor but the default range does not it your needs. Using the map function, you can translate it into any desired range.

 

The accelerometer, compass, and gyroscope

Accelerometer

In the following example, we will try out an accelerometer, which is a device used for sensing g-force. The accelerometer can sense movement in different directions. Normally, there are two types of accelerometer: the 2 axes and 3 axes. The 2 axes measures in two directions, left to right and front to back, and these directions are often named as the x-axis and y-axis.

 

The 3 axes accelerometer also measures in a z-axis, which is up and down. The accelerometer measures movement relative to its own position, which means that when you move it, it measures the g-force in the direction you are moving it. The sensor used in this example is the FLORA accelerometer/compass/gyroscope, which is actually three sensors in one.

 

Besides the accelerometer, it holds a compass, known as a magnetometer, which senses where the strongest magnetic field is coming from. If there are no other magnets nearby, the strongest magnetic field comes from the Earth's north pole.

 

The third sensor is the gyroscope, which is a device that can sense the rate of orientation on a spin axis through external torque. This basically means that the gyroscope can sense in which direction you are turning, compared to the accelerometer that senses which direction you are tilting the sensor.

 

In previous examples, we have been using serial communication to communicate with our sensors, but in the case of the FLORA accelerometer/compass/gyro, we will be using a different communication protocol called I2C. The I2C is a protocol developed by Philips and is used to connect low-speed devices to microprocessors, among other things. It uses a master-slave system, which involves one device acting as the master and all the other devices connected to the communication channel acting as slaves.

 

The master can talk to all of the slaves, but the slaves can only talk to the master. I2C is a two-wire protocol where you can hook up multiple slaves to the same communication lines in any order you want since all slaves are given a unique ID to keep track of them. Keeping track of the communication is the master job so no more than one slave can communicate at the time.

 

In the case of this example, we only have two devices, the FLORA, which will be acting as a master, and the accelerometer/compass/gyro sensor, acting as slaves. Using I2C, we can communicate with all three sensors without connecting them on separate communication channels.

Accelerometer
The FLORA accelerometer/compass/gyro is based on a chip called LSM9DS0, which by default is a bit tricky to communicate with. There are many breakout boards based on the LSM9DS0 available, and most of them are supplied with Arduino libraries, even the FLORA one. On the following GitHub link, Adafruit Industries Adafruit_LSM9DS0_Library you can find the Adafruit LSM9DS0 library written by

 

Kevin Towsend, which is an excellent library that simplifies the communication with the LSM9DS0. Just press the Download ZIP button on the GitHub repository and the library will start downloading.

 

As I mentioned before, libraries contain code that is usually too long and complicated to copy. In most cases, the code is used for different functionalities and does not need to be changed. In order to make life easier for others to use their code, some kind souls have made them into libraries so that they can easily be shared.

 

Once the LSM9DS0 library is downloaded, you need to unzip the folder and rename it to Adafruit_LSM9DS0. then place it into your libraries folder, inside you Arduino folder, by navigating to Arduino | libraries. If this is the first time you are installing a library, this folder might be missing, and in that case, you just create a folder inside the Arduino folder called libraries.

 

To find out where your libraries folder is located, you can check in the Arduino IDE by navigating to Arduino | Preferences.

This will open up a new window that shows the full path to your libraries folder.

The LSM9DS0 library is dependent on another library by Adafruit, which you also need to install.

Install it as you did with the LSM9DS0 library and rename it as Adafruit_Sensor.

When the libraries are installing, we can carry on with hooking up our sensor to the FLORA board.

 

The first connection that needs to be made is the 3.3 V, which connects to the 3.3 V pin on the FLORA board. Then connect SDA, SCL, and GND to the same pins with the same name on the FLORA board. Once all the connections have been made, you can enter the following code into the IDE and upload it to the FLORA board:

 

/*Import the necessary libraries. Wire.h and SPI.h are included in the IDE and does not need to be downloaded*/

#include <Wire.h>

#include <SPI.h>
#include <Adafruit_LSM9DS0.h>
#include <Adafruit_Sensor.h>
// set up i2c
Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0();
void setupSensor()
{
/*Set the accelerometer range where the range can be changed to 4G,8G or 16G */
lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_2G);//lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_4G); //lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_6G); //lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_8G); //lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_16G);
}
void setup()
{
//Wait for communication to start
while (!Serial);
//Set the baud rate
Serial.begin(9600);
//Print message to serial monitor
Serial.println("Starting communication");
Try to initialize and warn if we couldn't detect the chip if (!lsm.begin())
{
Serial.println("Something went wrong, check you connections"); while (1);
}
Serial.println("Connection established"); Serial.println(""); Serial.println("");
}
void loop()
{
//Get data from the sensor
lsm.read();
//Print the accelrometer sensor data to the serial monitor
Serial.print("Accel X: ");
Serial.print((int)lsm.accelData.x);
Serial.print(" ");
Serial.print("Y: ");
Serial.print((int)lsm.accelData.y);
Serial.print(" ");
Serial.print("Z: ");
Serial.println((int)lsm.accelData.z);
Serial.print(" ");
delay(200);
}

This code example initializes the accelerometer and prints the data from the sensor back to the serial monitor. Don't forget to open the monitor in order to see the data low. If the sensor is left untouched, you will find that the sensor data does not change that much. In the case of my sensor, the values on all three axes ranged from +30 to -30 as some noise is expected.

 

When I start tilting the sensor to the left, the value starts to increase on the x-axis, and if I tilt it to the right, the x-axis value starts to decrease. The value range on your sensor might be different, so try it out yourself by tilting the sensor in different directions while looking at the serial monitor to get a sense of your sensor range. Accelerometers can only sense movement in 180 degrees, so once your lip it to 180 degrees, the value starts over for the corresponding value on the other side.

 

In the next code example, we added the functionality of both the compass and gyroscope alongside the accelerometer code in order to show the sensors full functionality.

//Import the necessary libraries

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LSM9DS0.h>
#include <Adafruit_Sensor.h>
// set up i2c
Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0();
void setupSensor()
{
/*Set the accelerometer range where the range can be changed to 4G,8G or 16G*/
lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_2G);
//Set the magnetometer sensitivity where the range can be changed to 4GAUSS, 8GAUSS or 12GAUSS
lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS);
/*Setup the gyroscope sensitivity where the range can be changed 500DPS or 2000DPS*/
lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_245DPS);
}
void setup()
{
//Wait for communication to start
while (!Serial);
//Set the baud rate
Serial.begin(9600);
//Print message to serial monitor
Serial.println("Starting communication");
Try to initialize and warn if we couldn't detect the chip if (!lsm.begin())
{
Serial.println("Something went wrong, check you connections"); while (1);
}
Serial.println("Connection established"); Serial.println(""); Serial.println("");
}
void loop()
{
//Get data from the sensors
lsm.read();
//Print the accelrometer sensor data to the serial monitor Serial.print("Accel X: "); Serial.print((int)lsm.accelData.x);
Serial.print(" ");
Serial.print("Y: "); Serial.print((int)lsm.accelData.y); Serial.print(" ");
Serial.print("Z: "); Serial.println((int)lsm.accelData.z); Serial.print(" ");
//Print the compass sensor data to the serial monitor Serial.print("Compass X: "); Serial.print((int)lsm.magData.x);
Serial.print(" ");
Serial.print("Y: "); Serial.print((int)lsm.magData.y); Serial.print(" ");
Serial.print("Z: "); Serial.println((int)lsm.magData.z); Serial.print(" ");
//Print the gyro sensor data to the serial monitor Serial.print("Gyro X: "); Serial.print((int)lsm.gyroData.x);
Serial.print(" ");
Serial.print("Y: "); Serial.print((int)lsm.gyroData.y); Serial.print(" ");
Serial.print("Z: "); Serial.println((int)lsm.gyroData.z); Serial.println(" ");
//wait for a bit
delay(200);
}
With the help of the preceding code, we will now be able to show the sensors full functionality.
 

Machine-to-Machine Communications

machine_sensor
In this blog, we are going to look at another field of the Internet of Things: Machine-to-Machine (M2M) communications. Those are the cases where no human intervention is required, and when machines communicate directly with each other to accomplish particular tasks.

 

And this is exactly what we are going to illustrate with ESP8266 boards in this blog. We are first going to make a very simple project to illustrate M2M communications, and then we are going to apply this knowledge to build a light-activated relay, based on two ESP8266 boards. Let's start!

 

Hardware and software requirements

hardware
For this project, you will, of course, need an ESP8266 chip. As for most of this blog, I used the Adafruit Huzzah ESP8266 module, but any ESP8266 module will work fine here.

 

For the first project of this blog, you will need an LED, along with a 330 Ohm resistor. You will also need a mini push button and a 1K Ohm resistor. For the second project of this blog, you will need a relay, a 10K Ohm resistor, and a small photocell. You will also need a 3.3V/5V FTDI USB module to program the ESP8266 chip. Finally, you will also need some jumper wires and a breadboard.

 
This is a list of all the components that will be used in this blog:
 
  • Adafruit ES8266 module (x2) (https://www.adafruit.com/ products/2471)
  • FTDI USB module (https://www.adafruit.com/products/284)
  • LED (https://www.sparkfun.com/products/9590)
  • 330 Ohm resistor (https://www.sparkfun.com/products/8377)
  • Relay (https://www.sparkfun.com/products/10747)
  • Photocell (https://www.sparkfun.com/products/9088)
  • 10K Ohm resistor (https://www.sparkfun.com/products/8374)
  • Mini push button (https://www.sparkfun.com/products/97)
  • 1K Ohm resistor (https://www.sparkfun.com/products/8980)
  • Breadboard (x2) (https://www.sparkfun.com/products/12002)
  • Jumper wires (https://www.sparkfun.com/products/9194)
ESP8266

On the software side, if it's not been done yet, you will need to install the latest version of the Arduino IDE, which you can get from:http://www.arduino.cc/en/Main/Software Then, you will also need to have the aREST and PubSubClient libraries installed. To install a library, simply use the Arduino library manager.

 

To make the ESP8266 chips talk to each other, we are also going to use the IFTTT web service. IFTTT is a service where you can create recipes that will perform a given action when a given trigger is received, which is perfect for M2M communications. If it's not been done yet, create an account at IFTTT: IFTTT helps your apps and devices work together

 

In the first project of this blog, we are going to see a very simple case of M2M communication, where one ESP8266 Wi-Fi chip will send a trigger signal to another chip (via the cloud, of course), that will in response toggle the state of an LED. For the trigger, we'll use a simple push button connected to the first ESP8266.

 

Let's first assemble the hardware for this project. For the LED board, the hardware configuration is really easy: simply place the resistor in series with the LED, just as we already did in earlier blogs. Then, connect the resistor to pin 5 of the ESP8266, and the other pin to the ground.

 

This is the final result for the LED board:

For the board that will host the push button, first place the push button on the board, as well as the ESP8266. Then, connect the resistor to one side of the push button, and the other side of the resistor to the ground. Also, connect pin 5 of this ESP8266 Wi-Fi chip to this side of the push button. Finally, connect the other side of the push button to the VCC pin of the ESP8266.

 

This is the final result for the board with the push button:

We are now going to configure both boards so they can communicate with each other. As I said earlier, we are going to use the IFTTT service to make the two boards talk to each other.

 

We are first going to configure the LED board so it can receive commands from the cloud. For that, we'll use the aREST framework once again:

 

1. This sketch starts by importing the required libraries:

  • #include <ESP8266WiFi.h>
  • #include <PubSubClient.h>
  • #include <aREST.h>

 

2. Next, we create the required clients to connect to the cloud:

  • WiFiClient espClient;
  • PubSubClient client(espClient);

 

3. We also initialize the aREST library: aREST rest = aREST(client);

 

4. Next, we give a unique ID to the device:

char* device_id = "01e47f";

You also need to need to enter your Wi-Fi network credentials here:

  • const char* ssid = "wifi-name";
  • const char* password = "wifi-password";

 

5. Next, we define a Boolean variable to hold the current state of the LED:

  • bool ledState;
  • We also define a function to toggle the LED, which we will implement later:
  • int toggle(String command);

 

6. In the setup() function of the sketch, we expose the toggle function to aREST, and also connect the chip to the Wi-Fi network:

void setup(void)
{
// Start Serial Serial.begin(115200);
// Set callback client.setCallback(callback);
// Give name and ID to device rest.set_id(device_id); rest.set_name("led");
// Function rest.function("toggle", toggle);
// LED state
ledState = false;
// Connect to WiFi WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Pin 5 as output pinMode(5, OUTPUT);
}
7. In the loop() function of the sketch, we simply keep the connection with the aREST cloud platform:
  • void loop() {
  • // Connect to the cloud rest.handle(client);
  • }

 

8. At the end, we also need to implement the function to toggle the LED. We simply invert the state of the LED when the function is called, and then we also apply this new state to the LED:

// Toggle LED
int toggle(String command) {
ledState = !ledState;
digitalWrite(5, ledState);
return 1;
}

Now, we are going to see how to configure the board on which the push button is located, which will trigger an event at IFTTT whenever the button is pressed:

 

1. This starts by including the ESP8266 Wi-Fi library:

#include <ESP8266WiFi.h>

 

2. Next, you also need to define your Wi-Fi credentials:

const char* ssid = "wifi-name";

const char* password = "wifi-pass";

 

3. You also need to insert your IFTTT key at this point:

const char* host = "maker.ifttt.com"; const char* eventName = "button_pressed"; const char* key = "ifttt-key";

 

4. In the setup() function of the sketch, we simply connect the ESP8266 to your Wi-Fi network:

void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Pin 5 as input pinMode(5, INPUT);
}
5. In the loop() function of the sketch, we check whether the button has been pressed:

if (digitalRead(5)) {

 

6. If that's the case, we send a message to IFTTT. We first connect to their servers and create a request:

// Use WiFiClient class to create TCP connections WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request String url = "/trigger/";
url += eventName; url += "/with/key/"; url += key;
Serial.print("Requesting URL: ");
Serial.println(url);
 
7. Once that's done, we actually send the request to IFTTT:
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
int timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) { Serial.println(">>> Client Timeout !"); client.stop();
return;
}
}
 
8. To end the request, we read the data coming back from IFTTT and print it:
while(client.available()){
String line = client.readStringUntil('\r'); Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}

9. You can now also grab the sketch from the GitHub repository for the blog and upload it to the board.

However, for now, our two boards are not communicating with each other. This is why we are now going to go to IFTTT in order to create a recipe to link those two boards.

10. On the IFTTT website, create a new recipe and choose the Maker channel as the trigger:

11. Next, choose to Receive a web request as the trigger type:

12. As the event, enter button_pressed, which is also what we entered inside the Arduino sketch:

13. As the action channel, also choose the Maker channel:

14. For the action, select Make a web request:

15. For the action parameters, we basically need to call the function on the device we created.

16. You, of course, need to modify the URL with the device ID you set inside the code. After that, create the recipe, which should now appear inside your IFTTT account.

 

17. You can now finally test the project, as IFTTT is now making the link between our two boards. Just press on the push button, and should quickly see that the LED will come on. Note that this can take 2-3 seconds, as the information needs to go through the IFTTT servers first. You can also press the button again to switch the LED off. You have now built your first basic M2M communication project!

 

Building a light-activated relay

Now that we know how to build M2M projects using the ESP8266, we are going to apply it to a simple project, in which you won't even have to press a push button at all. We are going to build a light-activated relay that will control a relay connected to one ESP8266 module depending on the light level measured by another ESP8266. This project will simulate a part of a home automation system, where you automatically want to switch the lights on when it's getting dark outside.

 

First, we need to assemble both boards. Let's start with the board that will host the relay, as it is the easiest one to assemble: Simply connect the VCC pin of the relay to the VCC pin of the ESP8266 GND to GND and SIG or EN pin of the relay to pin 5 of the ESP8266.

 

For the board that will host the photocell, first place the ESP8266 on the breadboard, and then the 10K Ohm resistor in series with the photocell on the breadboard as well. Then, connect the common pin of the photocell and the resistor to pin A or ADC of the ESP8266, which is the analog input pin on the ESP8266 board. Then, connect the other end of the photocell to VCC, and the other end of the resistor to GND.

 

Let's now see how to configure those boards. For the relay board, you can simply use the same sketch as for the LED board in the previous project, as we are again going to use the aREST cloud server. For the photocell board, it will be very similar to the push button board in the first project, so we will only talk about the main differences here.

 

First, we set a variable that will define whether the light level is currently low or high. We'll set it to low by default, by assigning a false value to the variable:

bool lightLevel = false;

 

In the loop() function of the sketch, we first measure the state of the analog pin, and we print it on the Serial monitor:

Serial.print("Light level: ");

Serial.println(analogRead(A0));

 

Next, we check whether the light level is below a given threshold, and also whether the previous light level state was high. Note that the threshold is arbitrary here, it is just to illustrate M2M communications between the two boards. If we are indeed in those conditions, we send an event, light_level_low:

if (analogRead(A0) < 700 && lightLevel) {

lightLevel = false;
makeRequest("light_level_low");
}
On the other end, if the light level is high, and we were in the low state before, we send a light_level_high event to IFTTT:
if (analogRead(A0) > 800 && !lightLevel) {
lightLevel = true;
makeRequest("light_level_high");
}

 

You can now configure the board with the photocell using this code, which you can also find in the GitHub repository for the blog. Again, we now need to create recipes on IFTTT to link the two boards.

 

Go to IFTTT again and create a new recipe. Again, use the Maker channel as the trigger, and set the event name to light_level_low as defined in the sketch. For the action, select the Maker channel again, and create a web request with the following parameters:

 

Here, we are setting pin 5 to a high state on the target board, as we want to switch the relay on if the light levels are low. Of course, make sure to change the device ID of your device inside the URL to be called by IFTTT. Create the recipe, and do exactly the same with the other scenario by creating another recipe. This time, choose light_level_high as the trigger event:

 

For the action, enter exactly the same request as before, but this time with a 0 at the end, as we want to switch the lights off if the light level gets high again: You should now see both recipes active inside your IFTTT dashboard:

 

You can now test the project! To simulate it being dark outside, just place your hand on top of the photocell. You should see that 2-3 seconds after that, the relay should automatically switch to an active state on the other board. If you remove your hand, the relay should switch off again.

 

Note that because we are using M2M communications via a cloud service, both boards can, of course, be placed in different locations. For example, you could easily have one board outside and one inside your home, even if that means they are connected to different Wi-Fi networks.

 

Sending Notifications from the ESP8266

In this blog, we are going to see how to integrate a very important element of the IoT with the ESP8266: notifications. IoT devices constantly alert users when something significant is happening, or simply at regular intervals, for example, to report data.

 

We are going to see three scenarios in this blog. First, we'll see how to send simple e-mail notifications from the ESP8266. Then, we'll learn how to make the chip regularly send data via text messages to your phone. Finally, we will see how to send alerts via push notifications. Let's start!

 

Hardware and software requirements

For this project, you will, of course, need an ESP8266 chip. As for most of this blog, I used the Adafruit Huzzah ESP8266 module, but any ESP8266 module will work fine here. As a sensor, I'll use the DHT11 sensor here just to illustrate the behavior of two out of the three scenarios in this blog. However, you could use any sensor, or even use dummy data for this blog. The goal is really to learn how to send notifications.

 

You will also need a 3.3V/5V FTDI USB module to program the ESP8266 chip. Finally, you will also need some jumper wires and a breadboard. This is a list of all the components that will be used in this blog:

  • Adafruit ES8266 module
  • FTDI USB module
  • DHT11 sensor
  • Breadboard
  • Jumper wires

 

On the software side, if it's not been done yet, you will need to install the latest version of the Arduino IDE, which you can get from here: Arduino - Software

 

Then, you will need to have an IFTTT account, which we will use for all the projects in this blog. IFTTT is a very cool web service that can put two web services in contact via "recipes" that are activated by a trigger (the If) which in return triggers an action (the that). To create an account, simply go to IFTTT

 

Sending an e-mail notification

It's now time to make our first project: sending e-mail notifications! For this first approach to notifications, we'll simply send a message at regular intervals to the e-mail address of your choice.

 

To connect the ESP8266 to IFTTT, we need a channel called Maker, which is available on IFTTT. You first need to go to the Channels tab and find this channel:

 

Once the channel is opened on your screen, you need to connect it to your IFTTT account. This will allow you to get a key for your Maker Channel:

Make sure you have this key to hand; you'll need it really soon. As for all channels, you only need to do this once.The next channel we'll add is the Email Channel:

 

Here, enter the e-mail that you will use to receive the text messages coming from the IFTTT server. Make sure to put your own e-mail, otherwise it would be considered spam. Then, we can create a recipe that will link the Maker Channel to sending an e-mail. Simply click on the following button on the main page:

 

From the screen where you can create a new recipe, select the Maker channel we connected earlier:

As a trigger, we'll simply write hello:

Then, you will be asked to fill in the active channel with what e-mail you want to send. As we just want to test notifications here, simply enter a simple message:

 

You can now save the recipe, which will appear inside your IFTTT dashboard:

Now that the recipe is active, it's time to build the Arduino sketch to actually activate this recipe. As usual, I'll detail the most important parts of the sketch here:

 

1. It starts by including the ESP8266 Wi-Fi library:

#include <ESP8266WiFi.h>

2. Then, you need to insert your Wi-Fi name and password:

  • const char* ssid = "wifi-name";
  • const char* password = "wifi-pass";

 

3. After that, you need to put in some information about IFTTT, such as the event name and your IFTTT Maker channel key:

  • const char* host = "IFTTT";
  • const char* event name = "hello";
  • const char* key = "your key";

 

4. Now, in the setup() function, we connect the ESP8266 to the Wi-Fi network:

Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
5. In the loop() function, we first connect to the IFTTT server:
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
6. Then, we prepare the request with the event name:
String url = "/trigger/";

url += eventName;

url += "/with/key/";

url += key;
7. We can then send the request to the server:
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
int timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) { Serial.println(">>> Client Timeout !"); client.stop();
return;
}
}
8. And we read the answer from the server:
while(client.available()){

String line = client.readStringUntil('\r'); Serial.print(line);
}

Serial.println();

Serial.println("closing connection");

9. Finally, we wait one minute before each send: delay(60 * 1000);

 

Then, modify the code with your own Wi-Fi settings and IFTTT dataUpload the code to the board. Open the serial monitor, and you should see that the board is connected to the IFTTT servers and receiving the confirmation that the event has been triggered:

 

Now, check your e-mail inbox. You should see that you just received a message from your ESP8266: Of course, make sure to quickly disconnect your ESP8266 or shut down the recipe, or you will be spammed by your own project!

 

Sending data via text message

We are now going to use the same hardware to make a completely different project. We'll use IFTTT again to send measurement data from the ESP8266 chip to your mobile phone:

 

1. To do that, the first step is to connect the SMS channel to your IFTTT account. It's very simple, and you will just have to put in your phone number:

2. It's now time to create a new recipe. This time, use data as the name of the event:

3. Then, select the newly created SMS channel as the action of the recipe:

 

4. Now, we are going to build a more complex message than earlier, because we want to have the information about the measurements done by the ESP8266 in the message. Thanks to IFTTT, it's very easy using the assistant to add values coming from the trigger channel:

5. This is how your message should look at the end:

6. Finally, create the recipe

 

Now that the recipe is active, we can move on to the creation of the Arduino sketch. As there are many elements in common with the previous sketch, I will only detail the important elements here:

 

1. You need to include the DHT library: #include "DHT.h"

 

2. Then, we set the DHT sensor pin and type:

#define DHTPIN 5

#define DHTTYPE DHT11

3. We also create an instance of the DHT sensor: DHT dht(DHTPIN, DHTTYPE, 15);

4. This time, we name the event data: const char* eventName = "data";

5. In the setup() function of the sketch, we initialize the DHT sensor: dht.begin();

6. Then, inside the loop() function, we measure data from the sensor:

float h = dht.readHumidity();

float t = dht.readTemperature();

 

7. After that, we put the data that was just measured into the request:

 style="margin: 0px; width: 947px; height: 130px;">String url = "/trigger/";
url += eventName;
url += "/with/key/";
url += key;
url += "?value1=";
url += String(t);
url += "&value2=";
url += String(h);

It's now time to test the sketch! Grab it from the GitHub repository for the blog, and make sure to modify the sketch with your Wi-Fi settings and IFTTT data. Then, upload the code to the board. After a few moments, you should receive a message on your mobile phone showing the data that was measured:

 

Receiving alerts via push notifications

In the last project of the blog, we are going to see how to send a third type of notification: push notifications. These are perfect for important alerts, as they will show up right on your phone when they're triggered. To do so, we'll be using an application called Pushover that exists for iOS and Android. You first need to create an account at Simple Notifications

 

Inside the Pushover dashboard, you'll need to get the API key; you'll need it in a moment to link Pushover to your IFTTT account. Inside IFTTT, you can now connect the Pushover channel. Now, we are ready to create the final recipe for this blog. Like the event name, this time choose alert. Then, as the active channel, select the Pushover channel:

 

As the message for the push notification, you can choose what you want, for example, a message saying that the humidity is too high:

Finally, save the recipe, which should now appear on your dashboard:

Let's now configure the ESP8266 board. As the sketch is really similar to the sketches we already saw, I will only tell you about what changed here.

 

The first thing we need to change is the name of the event sent to IFTTT: const char* eventName = "alert";

Then, we set up the board to send an alert whenever the humidity rises above 30%: if (h > 30.00) {

We also need to add a bigger delay when the alert is triggered, just to make sure you don't receive an alert every 5 seconds: delay(10 * 60 * 1000);

 

It's finally time to test the project! Grab the code from GitHub, and change the Wi-Fi settings and also the IFTTT data. Then, upload the code to the board. If the humidity is indeed above the threshold, you should receive a notification pretty soon on your phone:

 

This is much better than just an e-mail, as you'll see it even if you are not currently checking e-mails or text messages. Therefore, it's just perfect for urgent alerts, and you now know how to send those alerts right from your ESP8266.

Fingerprint Scanner for Arduino

 

fingerprint sensor with Arduino

In this blog, we are going to build a more complex secret agent project: an access control system using a fingerprint sensor. We will connect the fingerprint sensor to Arduino along with a relay and an LCD screen. The following are the steps that we will take for this project:

  •  First, we are going to record your fingerprint in the sensor so that you can get access
  • Then, we will use the fingerprint sensor to open or close the relay
  • Finally, we will create a system with the LCD screen to grant access to a secret piece of data stored in Arduino

Let's dive in!

 

Hardware and software requirements

First, let's see with the fingerprint sensor: software requisites "what with fingerprint sensor: hardware requisites" are the required components for this project. 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. The following is an image of the sensor that I used:

 

You with fingerprint sensor: software requisites "need to get with fingerprint sensor: hardware requisites" the exact same model (from Adafruit). Otherwise, the code for this project won't work. You will also need an LCD screen for the last part of this project. I also used a Pololu 5V relay module, which is really convenient to connect to Arduino. A relay will basically allow us to control a wide range of devices, for example, from a simple LED to electrical appliances.

 

Finally, here is the list of all the components that we will use in this project:

Fingerprint Scanner  Arduino

  • Arduino Uno (https://www.sparkfun.com/products/11021)
  • Adafruit Fingerprint Sensor (https://www.adafruit.com/products/751)
  • DFRobot 4x20 LCD screen (http://www.robotshop.com/en/dfrobot-i2c-twi-lcd-module.html)
  • Pololu relay module (https://www.pololu.com/product/2480)
  • Breadboard (https://www.sparkfun.com/products/12002)
  •  Jumper wires (https://www.sparkfun.com/products/8431)

 

On the software side, you will need two Arduino libraries: the LiquidCrystal_I2C library with fingerprint sensor: software requisites "for the LCD with fingerprint sensor: hardware requisites" screen and the Adafruit Fingerprint Sensor library. You can get them both using the Arduino library manager. You can also visit the GitHub repository of the Fingerprint Sensor library, to learn more about the different functions, available at https://github.com/adafruit/ Adafruit-Fingerprint-Sensor-Library.

 

Hardware configuration

hardware

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 pin 3 and the green wire to pin number 2. After that, we are going to connect the relay module. Connect the VCC pin to the red power rail, GND pin to the blue power rail, and the EN pin to Arduino pin 7.

 

Finally, let's connect the LCD screen. First, connect the power: VCC to the red power rail and GND pin to the blue power rail. After that, connect the I2C pins (SDA and SCL) to the Arduino board. The I2C pins are next to pin 13 on the Arduino Uno board. The following is the final result: If your project is similar to the preceding image, congratulations, you can now proceed to the next section of this blog and build exciting applications based on the fingerprint sensor!

 

Enrolling your fingerprint

fingerprint

The first thing that we have to dois enroll at least one fingerprint so that it can be later recognized by the sensor. We will do that in this section. Here is most of the code for this section:

// Libraries

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
// Fingerprint enroll function
uint8_t getFingerprintEnroll(uint8_t id);
// Software Serial instance
SoftwareSerial mySerial(2, 3);
// Fingerprint sensor instance
Adafruit_Fingerprint finger = Adafruit_Fingerprint(andmySerial);
void setup()
{
// Start serial Serial.begin(9600); Serial.println("fingertest");
// Set the data rate for the sensor serial port finger.begin(57600);
// Verify that sensor is present
if (finger.verifyPassword()) { Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :("); while (1);
} }
void loop()
{
// Wait for fingerprint ID
Serial.println("Type in the ID # you want to save this finger as...");
uint8_t id = 0;
while (true) {
while (! Serial.available());
char c = Serial.read();
if (! isdigit(c)) break;
id *= 10;
id += c - '0';
}
Serial.print("Enrolling ID #");
Serial.println(id);
while (! getFingerprintEnroll(id) );
}

 

You will note that I didn't include all the details of fingerprint sensofunctions as they are too long to be displayed here. You can, of course, find the whole code in the GitHub repository of this blog. Now, let's see the details of the code. It starts by including the required libraries:

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
Then, we declare the function that we will use in order to enroll our fingerprint:
uint8_t getFingerprintEnroll(uint8_t id);
After that, we create the software serial instance that we will use to communicate with the server:
SoftwareSerial mySerial(2, 3);
We will also create the fingerprint sensor instance:
Adafruit_Fingerprint finger = Adafruit_Fingerprint(andmySerial);
Now, in the setup() function of the sketch, we will initialize serial communications:
Serial.begin(9600);
Serial.println("fingertest");
Then, we will initialize the communication with the sensor:
finger.begin(57600);
We will also check whether the sensor is present:
if (finger.verifyPassword()) { Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :("); while (1);
}

 

In the loop() function of the code, we will first wait for an input from the user, which is the ID of the fingerprint that we want to store. Then, we go through the process of storing the fingerprint. This is all done by the following code snippet:

 // Wait for fingerprint ID
Serial.println("Type in the ID # you want to save this finger as..."); uint8_t id = 0;
while (true) {
while (! Serial.available());
char c = Serial.read();
if (! isdigit(c)) break;
id *= 10;
id += c - '0';
}
Serial.print("Enrolling ID #");
Serial.println(id);
while (! getFingerprintEnroll(id) );

 

It's now the time to test the enrollment process. First, get the complete code, for example, from the GitHub repository of the blog, which is available at https://github.com/marcoschwartz/arduino-secret-agents.

 

Then, copy the code in the Arduino IDE. After that, upload the code to the Arduino board and open the serial monitor with a speed of 9600 baud. The following screenshot is what you should see. On being prompted, enter the ID of the fingerprint that you want to store and press enter. The sketch will now ask you to put your finger on the sensor. Do so and, after a while, you should see that the image was taken and you can now remove your finger:

 

Then, as asked by the sketch, put your finger on the sensor once more. The sketch will then confirm that the fingerprint has been stored. If you can see this message, it means that your fingerprint is now stored in the sensor and you can move to the next section.

 

Controlling access to the relay

fingerprint

Now that your fingerprint is stored in the sensor, you can build your first application using the hardware that we previously built. We are going to open or close the relay every time the sensor recognizes our fingerprint. The following is the complete code for this part, excluding the details about recognition functions:

// Libraries

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
// Function to get fingerprint int getFingerprintIDez();
// Init Software Serial SoftwareSerial mySerial(2, 3);
// Fingerprint sensor instance
Adafruit_Fingerprint finger = Adafruit_Fingerprint(andmySerial);
// Relay parameters int relayPin = 7;
bool relayState = false;
// Your stored finger ID int fingerID = 0;
// Counters
int activationCounter = 0;
int lastActivation = 0;
void setup()
{
// Start Serial Serial.begin(9600);
// Set the data rate for the sensor serial port finger.begin(57600);
// Check if sensor is present
if (finger.verifyPassword()) { Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :("); while (1);
}
Serial.println("Waiting for valid finger...");
// Set relay as output pinMode(relayPin, OUTPUT);
}
void loop()
{
// Get fingerprint # ID
int fingerprintID = getFingerprintIDez();
// Activation ?
if ( (activationCounter - lastActivation) > 2000) {
if (fingerprintID == fingerID && relayState == false) { relayState = true;
digitalWrite(relayPin, HIGH);
lastActivation = millis();
}
else if (fingerprintID == fingerID && relayState == true) { relayState = false;
digitalWrite(relayPin, LOW);
lastActivation = millis();
}
}
activationCounter = millis();
delay(50);
}

As you can see, many elements are common with the sketch that we saw in the previous section. We are only going to see those elements which are important and are added to this new sketch. We have to define on which pin the relay is connected and also state that the relay is off by default:

int relayPin = 7;

bool relayState = false;

Then, we will define the ID under which we stored the fingerprint in the previous section. I used 0 here as I stored my fingerprint with the ID number 0:

int fingerID = 0;

 

Also, we don't want the relay to continuously switch state when we have our finger on the sensor. Therefore, we need the following two variables to count 2 seconds before the state of the relay can be changed again:

int activationCounter = 0;

int lastActivation = 0;
We will then set the relay pin as an output:
pinMode(relayPin, OUTPUT);
Then, in the loop() function of the sketch, we check whether the sensor is reading any fingerprint ID that is already stored in the sensor:
int fingerprintID = getFingerprintIDez();
The following is the check for the activation period:
if ( (activationCounter - lastActivation) > 2000) {

 

We will then check whether the ID corresponds to the ID that we defined earlier and also check the state of the relay. If the ID corresponds to the ID that we entered in the sketch, we switch the state of the relay:

if (fingerprintID == fingerID && relayState == false) { relayState = true; digitalWrite(relayPin, HIGH);

lastActivation = millis();
}
else if (fingerprintID == fingerID && relayState == true) { relayState = false;
digitalWrite(relayPin, LOW);
lastActivation = millis();
}
Finally, we will refresh the activation counter and wait 50 milliseconds until the next read:
activationCounter = millis();
delay(50);

 

It's now time to test the sketch. Get all the code, for example, from the GitHub repository of the blog and then upload it to the board. Make sure that you change the ID in the sketch, corresponding to the fingerprint that you stored earlier.

 

Then, open the serial monitor with the speed of 9600 baud. Place the finger that you recorded previously on the sensor. You should immediately see the following in the serial monitor. You should also hear the relay click, meaning that it just changed its state. You can now do the same operation after some seconds; you should hear the relay switch back to its initial state. You can try with another finger or ask someone else to try the project; nothing will happen at all.

 

Accessing secret data

In the last section of this blog, we are going to use all the hardware that we connected to the project for another cool application: accessing a secret piece of data with your fingerprint. It can, for example, be a secret code that you only want to be accessible with your own fingerprint. We will use the LCD screen for this, removing the need to have the serial monitor opened.

 

The following is the complete code for this part, excluding the functions to read the fingerprint sensor data:

// Libraries

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
// LCD Screen instance LiquidCrystal_I2C lcd(0x27,20,4);
// Function to get fingerprint int getFingerprintIDez();
// Init Software Serial SoftwareSerial mySerial(2, 3);
// Fingerprint sensor instance
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
// Relay parameters int relayPin = 7;
bool relayState = false;
// Your stored finger ID int fingerID = 0;
// Counters
int activationCounter = 0;
int lastActivation = 0;
// Secret data
String secretData = "u3fks43";
void setup()
{
// Start Serial Serial.begin(9600);
// Set the data rate for the sensor serial port
finger.begin(57600);
// Check if sensor is present if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!"); } else {
Serial.println("Did not find fingerprint sensor :("); while (1);
}
Serial.println("Waiting for valid finger...");
// Set relay as output
pinMode(relayPin, OUTPUT);
// Init display lcd.init(); lcd.backlight(); lcd.clear(); lcd.setCursor(0,0); lcd.print("Scan your finger");
}
void loop()
{
// Get fingerprint # ID
int fingerprintID = getFingerprintIDez();
// Activation ?
if ( (activationCounter - lastActivation) > 2000) {
if (fingerprintID == fingerID) {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Access granted!");
lcd.setCursor(0,1);
lcd.print("Your secret data is:");
lcd.setCursor(0,2);
lcd.print(secretData);
if (relayState == false) {
relayState = true;
digitalWrite(relayPin, HIGH);
}
else if (relayState == true) {
relayState = false;
digitalWrite(relayPin, LOW);
}
lastActivation = millis();
}
}
activationCounter = millis();
delay(50);
}

 

As you can see, this code has some common parts with the code that we saw in the earlier section. Therefore, we are only going to talk about the most important elements here.

It starts by including the required libraries:

#include <Adafruit_Fingerprint.h>

#include <SoftwareSerial.h>

#include <LiquidCrystal_I2C.h>

#include <Wire.h>

 

Then, we need to create an instance of the LiquidCrystal_I2C LCD screen:

LiquidCrystal_I2C lcd(0x27,20,4);

We will also define a string containing our secret data:
String secretData = "u3fks43";
Of course, feel free to put anything here. Then, in the setup() function, we will initialize the LCD screen:
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Scan your finger");

 

Then, in the loop() function of the sketch, if we are outside of the activation period of 2 seconds, we will compare the fingerprint that was measured with the ID that we set in the sketch. If this is correct, we will print a message on the LCD saying that the access was granted along with the secret data:

 

if (fingerprintID == fingerID) {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Access granted!");
lcd.setCursor(0,1);
lcd.print("Your secret data is:");
lcd.setCursor(0,2);
lcd.print(secretData);

 

Now, it's time to test the sketch. Get all the code, for example, from the GitHub repository of the project and upload it to the board.

Converting Finger Gestures to Text

Here we will look deeper into the realm of sensors. You will learn a lot on this blog about using a touch sensor to create cool projects. You will be introduced to Arduino's sister software (technically its father). Processing, which is often used along with the Arduino to either create an interface to communicate with the Arduino or simply to display data in a much more comprehensible way.

 

This blog is divided into three sections. We will start by learning the basics of Processing. Then we will use the number touchpad and the processing software to create a tic-tac-toe (X's & O's) game. And, in the final section, we will use the touchpad to recognize stroke patterns and different alphabets and display them on the screen.

 

This blog uses less hardware; however it involves a lot of programming, so you should be ready for that.

In this blog, we'll cover the following topics:

  • A brief note on capacitive sensors
  • Introduction to Processing
  • Tic-tac-toe with touch
  • Pattern recognition with touch

 

Prerequisites

You will need the following components to add a touch element to your Arduino projects:

1x Arduino-compatible board such as the UNO

1x USB Cable A to B

1x capacitive touch kit (http://www.dfrobot.com/index. php?route=product/product&keyword=capac&product_id=463) Only the capacitive number pad and touchpad.

 

What is a capacitive touch sensor?

A capacitive touch sensor is an upgrade from the commonly used resistive sensors that relied on a change in resistance due to a change in resistor geometry due to the applied pressure. A capacitive sensor works on the principle that your finger acts as an external capacitor that changes the total capacitance of the system, which is then measured by onboard chips and converted into readable data.

 

An introduction to Processing

Processing is very similar to Arduino in the sense that it has a similar interface to the Arduino IDE. But Processing is used mainly to create graphical interfaces or to display data in real time, which is what we are going to be doing in this blog. Let's get started.

 

The first thing you will have to do is to download and install the latest version of Processing. Install it like you installed Arduino.

 

  • Open the application. The environment looks very similar to the Arduino IDE, right? This should make it easy for you to work with.
  • For a quick demo on what Processing can do, go to File | Example and, under Inputs, choose MouseXY (Mouse2D). Run the sketch and be amazed! Try some other examples, such as (Topics | Simulate | Flocking), to see what else can be achieved.
  • Now we are going to use this powerful software along with the Arduino and number touchpad to create a tic-tac-toe game.

 

Tic-tac-toe with touch

Remember how, while using Arduino, you needed to install libraries to make certain functions work? We need to do the same with Processing because it cannot directly communicate with the Arduino. To do this, go to http://playground. arduino.cc/Interfacing/Processing and download the processing2-Arduino. zip file. Processing, like Arduino, also creates a directory by default in the Documents folder. Extract the downloaded ZIP file to C:\Users\<user>\Documents\ Processing\libraries for Windows and Documents/Processing/libraries for

 

Mac and Linux.

Do the same for the matrix library we will be using in the next section from http://pratt.edu/~fbitonti/pmatrix/matrix.zip. Restart Processing.

 

If you do not have a libraries folder in the Processing directory, go ahead and create a new one. Now launch the Processing IDE (not the Arduino IDE). Connect the Arduino and run this sketch:

import processing.serial.*;

import cc.arduino.*;
Arduino arduino;
int ledPin = 13;
void setup()
{
//println(Arduino.list());
arduino = new Arduino(this, Arduino.list()[0], 57600); arduino.pinMode(ledPin, Arduino.OUTPUT);
}
Converting Finger Gestures to Text
void draw()
{
arduino.digitalWrite(ledPin, Arduino.HIGH);
delay(1000);
arduino.digitalWrite(ledPin, Arduino.LOW);
delay(1000);
}

 

What do you observe? The LED that is connected to pin 13 should begin blinking. This means that you have coded the Arduino successfully with Processing. If it didn't work, try using Arduino.list()[1] instead of Arduino.list()[0]. Ok, now we want to test out the capacitive touchpad. Create the following circuit, taken from DFRobot's wiki:

 

The connections are as follows (Arduino UNO | NumPad):

  • GND – GND
  • VCC – 5V
  • SCL – A5 (analog pin 5)
  • SDA – A4
  • IQR – D2 (digital pin 2)
  • ADDR – no connection necessary

This particular touchpad also requires a library. Go to http://www.dfrobot.com/ image/data/DFR0129/MPR121%20v1.0.zip to download it. As before, extract it to the Processing libraries directory. Now it is time to get to the actual tic-tac-toe program.

 

Arduino and Processing

Open up a new sketch on Arduino and paste in the following:

#include <Wire.h> // default Wire library

#include <mpr121.h> // touch pad library
int num = 0; // variable to store pressed number
void setup()
{
Serial.begin(19200); // begin the Serial Port at 19200 baud Wire.begin(); // initiate the wire library CapaTouch.begin(); // inititate the capacitive touch library delay(500);
}
void loop()
{
num = CapaTouch.keyPad(); // stores the pressed number to num if(num > 0){ // checks if the key pressed is within scope
Serial.print(num); // prints the number to the serial port
}
delay(200); // small delay to allow serial communication
}
Save it as before, to tic_tac_toe.ide.

 

You must be thinking: Oh! You said there would be a lot of programming in this blog! This code is so small! Running the program will give you a Serial Monitor display like this: Well, that was just the Arduino sketch. Now we need to add the processing sketch that will allow us to communicate with the Arduino and create a nice little graphical interface where you can play a two-player tic-tac-toe game.

 

This involves a lot of things, as you will find out. Using Processing, open the file called tic_tac_toe_pro.pde that came with this blog and, when you're ready, run it.

 

Tic-tac-toe final output

Pretty neat, huh? If you are feeling really adventurous and have complete confidence in your programming skills, you can go ahead and program a player versus AI game, which is outside the scope of this blog.

 

Now that we have had a small taste of what is possible using a touch sensor, we will move on to the pattern recognition part of the blog where we will push the capacitive grid sensor and our coding capabilities to their limits.

 

Pattern recognition

Firstly, go ahead and create this circuit: Touchpad circuit (credits: Lauren, DFRobot) Your capacitive touchpad and its controller (the central component in the image), are connected using the corresponding numbers labeled on the pins. The connections from the Arduino to the controller are as follows (literally the same connections as before):

  • GND – GND
  • VCC – 5V
  • SCL – A5 (analog pin 5)
  • SDA – A4
  • IQR – D2 (digital pin 2)
  • ADDR – no connection necessary

Do not worry if the touchpad doesn't look exactly like this; as long as the connections are fine, everything will work out.

 

Open up Arduino and go to File | Examples | MPR121 | Examples | Touchpad or copy the following code:

#include <Wire.h>

#include <mpr121.h>
int X ; // X-coordinate
int Y ; // Y-coordinate
// ========= setup =========
void setup()
{
// initialize function
Serial.begin(19200);
Wire.begin();
CapaTouch.begin();
delay(500);
Serial.println("START");
}
// =========
loop
=========
void loop()
{
X=CapaTouch.getX(); // Get X position.
Y=CapaTouch.getY(); // Get Y position.
if(X>=1 && X<=9 && Y>=1 && Y<=13)
{
// Determine whether in the range. If not, do nothing. Serial.print("X=");

Serial.print(X); Serial.print(" Y=");
Serial.println(Y);
}
delay(300);
}

 

Now, run this program, open up the Serial Monitor, and set it to a baud rate of 19200. Play around with the touchpad using your fingertip and you should get something like this:

 

Serial Monitor with touchpad

Before we jump into how we are going to use this device, let's take a minute to think about what exactly we are trying to do using the device. You can use it for various things but, for the purpose of this project, we are going to use the touchpad, Arduino, and Processing to convert your finger strokes into meaningful text (alphabets for simplicity). 

 

Now, before we link this to Processing, we need to learn how to tackle the problem that has haunted engineers for decades, namely, image processing. In this case, however, the image processing is not too complex, but some sort of logical brainstorming is required. Look at your capacitive touchpad.

 

Capacitive touchpad

What is the first thing that you think of that would aid in analyzing the stroke patterns? Right away, you would guess, a two-dimensional array! You are right.

 

A 2D array or matrix like the one that we used in the X's & O's section will help us to tackle this problem. If you have already played with the touchpad, and if yours looks similar to the one used in this blog, the first two rows both have an X value of 1, the last two have a value of 13, the two left columns have a Y value of 1 and the two right-most columns have a Y value of 9. Let's try to put them to good use. This is what the layout of the touchpad would look like with coordinates added in for visualization.

 

Capacitive touchpad - Labeled

We are going to create a 13x9 matrix with a starting value of 0 for each element. When the capacitive touch sensor pad is touched, the corresponding value in the matrix will be changed to 1. In this way, we have a mathematical means of representing the stroke layout.

 

To further alleviate the complexity of the problem of having to understand and iterate all of the twists and bends of alphabets, we will be using block diagrams.

 

What is wrong with that D? It is enough to know that, if the D was written as a complete rectangle, it would simply represent O. These typefaces are much easier to process as they are mainly composed of lines.

Let's look at the block letter A.

Let's name each of the straight lines:

  • Top Horizontal – T
  • Bottom Horizontal – B
  • Middle Horizontal – H
  • Left Vertical – L
  • Right Vertical - R
  • Middle Vertical - V

With the labels, it looks like this:

 

Note how the Bottom Horizontal line and the Vertical Line are faded; this is because the alphabet A does not contain these strokes. We can calculate if a particular combination of T, B, H, L, R, and V exists for each alphabet in the matrix we made before. If we denote true (exists) as 1, then for A:

  • T = 1
  • B = 0 (does not exist)
  • H = 1
  •  L = 1
  • R = 1
  • V = 0

You see where we are going with this, right? In this way, we can map out the characteristics of all the alphabets. Some alphabets, though, are a bit tricky. For example, the letter P looks like this: What do we do for the Right Vertical (R) line? To solve this issue, if we come across a half-line, we will denote it with a 2. A ½ would be more representative but, when using ½ as a coding parameter, it will simply disappear into a zero in the integer format, hence 2 is used.

So P would become:

  • T = 1
  • B = 0
  • H = 1
  • L = 1
  • R = 2
  • V = 0

Now, to represent the touch panel in real time or to process a display to represent it requires the ability to use the power of matrices. So we will code a simple layout that looks like this: And, with the strokes on an ideal block A, it would look something like this:

 

Processing grid layout for 'A'

Now that we have understood how to solve this entire problem, let's finally go to the code.Fire up Arduino and paste in the following code. Or you could just use the touch_pad.ide file supplied to you with this blog.

// Connections:

// SDA (MPR121) -> PIN A4 (Arduino)
// SCL (MPR121) -> PIN A5 (Arduino)
// IRQ (MPR121) -> PIN A2 (Arduino)
// Libraries
#include <Wire.h>
#include <mpr121.h> // Touch Pad library
int X ; // X-coordinate
int Y ; // Y-coordinate
int inByte = 0; // incoming serial byte
void setup()
{
Serial.begin(57600); // Begin serial at 57600 baud rate (faster)
Wire.begin(); // intiialize wire library
CapaTouch.begin(); // initialize the capacitive touch library delay(500); // brief delay for initialization
}
void loop()
{
X = CapaTouch.getX(); // Get X position.
Y = CapaTouch.getY(); // Get Y position.
// Determine whether in the range.If not,do nothing. if(X>=1&&X<=9&&Y>=1&&Y<=13) { // Debug lines, can be uncommented to check inputs //Serial.print("X=");

//Serial.write(X); //Serial.print(" Y="); //Serial.write(Y); // convert X and Y coordinates into one variable if(Y<10) { Serial.print(X*10+Y); // prints to serial port } else if(Y>9)
{
Serial.print(X*100+Y); // prints to serial port
}
}
delay(200); // delay for message to be relayed
}

 

Save it as touch_pad under. Note how we converted both the X and Y coordinates into one integer so that we send a single data point through the serial port. Open a new processing sketch and open the file named touch_pad_pro.pde. Run it.

 

Save it as touch_pad_pro. Upload the Arduino code first and only then run this program! If you get an error with the libraries, make sure they are installed in your Processing directory in Documents. Go ahead and play with it. I recommend the first character to be an 'I', nice and simple. Make sure the strokes are gentle. You can go over previous lines, so do not worry about that. You will soon find out that the strokes don't have to be perfect for the program to identify what they are.