Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Tutorial 6

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

Reading Sensors with an Arduino

The ease with which an Arduino can obtain sensor values is one of the features that makes
it so useful.
Sensors are devices that convert a physical quantity, such as light intensity or
temperature, into an electrical quantity. A thermocouple, for example, outputs a
voltage proportional to its temperature. There are many different types of sensors:

 Light  sensor
 Motion  sensor
 Temperature  sensor
 Magnetic fields  sensor
 Gravity  sensor
 Humidity  sensor
 Moisture  sensor
 Vibration  sensor
 Pressure  sensor
 Electrical fields sensor
 Sound sensor
 Position sensor

These sensors are used in thousands of different applications, including


manufacturing, machinery, aerospace, automobiles, medicine, and robotics.
 

EXPERIMENT 1: Distance sensor


In this experiment, we will use a Sharp GP2Y0A21YK proximity sensor to control
the brightness of an LED. 
SHARP IR Sensor

Hardware Required

 1 x Arduino Mega2560
 1 x breadboard
 1 x LED
 5 x jumper wires
 1 x 470 ohm resistor
 1 X Sharp GP2Y0A21YK proximity sensor

Wiring Diagram
Circuit Diagram

The Sharp proximity sensor can detect objects as close as 10 cm and as


far away as 80 cm. It emits a pulse of infrared light and then detects the
angle at which that light is reflected. The farther away an object is, the
lower the output voltage. If the sensor receives no reflection, the output
voltage of the sensor will be 0 V. If the object is 10 cm or closer, the
output voltage will be equal to 5 V. (In this experiment, we are supplying
5V to the sensor.)
The sensor's output is connected to an Arduino analog input. The
Arduino's analog-to-digital converter (ADC) then converts that value to a
value between 0 and 1023. This value is then mapped to a value between
0 and 255, and that number is used to set the duty cycle of a pulse-width
modulated output, which controls the brightness of the LED. The result is
that the closer an object is to the proximity sensor, the brighter the LED
will shine.
 
Code For Experiment 1
const int pwm = 2 ; //Initializing Pin for pwm
const int adc = A0 ; //Initializing Pin for adc

void setup()
{
pinMode(pwm,OUTPUT) ; // To change LED brightness
}
void loop()
{
int sensor_val = analogRead(adc) ;
sensor_val = map(sensor_val, 0, 1023, 0, 255) ;

/*
-----------map funtion------------
The above funtion scales the output of adc,which is
10 bit and gives values btw 0 to 1023, in values btw
0 to 255 form analogWrite funtion which only recieves
values btw this range.
*/

analogWrite(pwm,sensor_val) ; // setting sensor value as pwm

   Download Code  
EXPERIMENT 2: Heat Sensor
In this experiment, the Arduino will measure the temperature using an LM35 sensor
IC. The LM35 is a low voltage IC which requires a power supply from +4 VDC to +20
VDC. This is ideal because we can power the sensor with the Arduino's +5 V output.
The LM35 has just 3 pins, 2 for the power supply and one for the analog output. The
output pin provides an analog voltage output that is linearly proportional to the
temperature in degrees C. The output ranges from 0 V - 1.5 V, when powered with a
single power supply. An output of 0 V corresponds to a temperature of 0 degrees C,
and the output increases 10 mV for every degree increase in the temperature. To
convert the output voltage to temperature, you need only to divide the output voltage in
mV by 10. For example, if the output value equals 315 mV (0.315 V), the temperature
is 31.5°C.

Pin Configuration of LM35 IC:

Pin Configuration
Hardware Required

 1 x LM35 Temperature Sensor


 2 x LEDs
 1 x matchbox
 2 X 470 ohm resistors 
 1 x Arduino Mega2560
 1 x breadboard
 10 x jumper wires

Wiring Diagram
Circuit Diagram
Code For Experiment 2
The LM35's output pin (pin 2) is connected to A0 of the Arduino. The code uses the
function analogRead() to convert the output voltage to a number between 0 and 1023.
Multiplying this number by 0.48828125 converts that value to degrees C, which is then
displayed on the serial monitor:
const int adc = 0 ; //naming pin 0 of analog input side as adc
const int high = 8 ; // For turning on and off yellow LED
const int low = 9 ; // For turning on and off Green LED
void setup()
{
Serial.begin(9600) ; //Starting serial Communication at baud rate of 9600
pinMode(high,OUTPUT); //declaring LED pins as OUTPUT
pinMode(low,OUTPUT);
}
void loop()
{
int adc = analogRead(0) ; //reading analog voltage and storing it in an integer
adc = adc * 0.48828125; //converting reading into Celsius
Serial.print("TEMPRATURE = "); //to Display on serial monitor
Serial.print(adc); //Temperature reading
Serial.print("*C"); //TEMPRATURE = 27*C ETC
Serial.println(); //To end the line
delay(1000); //1 Sec delay
/*
LOGIC:
if (temperature (adc) > 70 ° C )
turn on Yellow Leds
turn off Green Leds
else
turn off Yellow Leds
turn on Green Led
*/
if(adc>70) // This is the control statement
{
digitalWrite(high,HIGH) ;
digitalWrite(low,LOW) ;
}
else
{
digitalWrite(high,LOW) ;
digitalWrite(low,HIGH) ;
}
Arduino - Humidity Sensor
In this section, we will learn how to interface our Arduino board with different sensors.
We will discuss the following sensors −

 Humidity sensor (DHT22)


 Temperature sensor (LM35)
 Water detector sensor (Simple Water Trigger)
 PIR SENSOR
 ULTRASONIC SENSOR
 GPS

Humidity Sensor (DHT22)


The DHT-22 (also named as AM2302) is a digital-output, relative humidity, and
temperature sensor. It uses a capacitive humidity sensor and a thermistor to measure
the surrounding air, and sends a digital signal on the data pin.
In this example, you will learn how to use this sensor with Arduino UNO. The room
temperature and humidity will be printed to the serial monitor.

The DHT-22 Sensor


The connections are simple. The first pin on the left to 3-5V power, the second pin to
the data input pin and the right-most pin to the ground.

Technical Details
 Power − 3-5V
 Max Current − 2.5mA
 Humidity − 0-100%, 2-5% accuracy
 Temperature − 40 to 80°C, ±0.5°C accuracy

Components Required
You will need the following components −

 1 × Breadboard
 1 × Arduino Uno R3
 1 × DHT22
 1 × 10K ohm resistor

Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
Arduino Code
// Example testing sketch for various DHT humidity/temperature
sensors

#include "DHT.h"
#define DHTPIN 2 // what digital pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due
connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the
sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third
parameter to
// tweak the timings for faster processors. This parameter is no
longer needed
// as the current DHT reading algorithm adjusts itself to work on
faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}

void loop() {
delay(2000); // Wait a few seconds between measurements
float h = dht.readHumidity();
// Reading temperature or humidity takes about 250 milliseconds!
float t = dht.readTemperature();
// Read temperature as Celsius (the default)
float f = dht.readTemperature(true);
// Read temperature as Fahrenheit (isFahrenheit = true)
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Compute heat index in Fahrenheit (the default)


float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print ("Humidity: ");
Serial.print (h);
Serial.print (" %\t");
Serial.print ("Temperature: ");
Serial.print (t);
Serial.print (" *C ");
Serial.print (f);
Serial.print (" *F\t");
Serial.print ("Heat index: ");
Serial.print (hic);
Serial.print (" *C ");
Serial.print (hif);
Serial.println (" *F");
}

Code to Note
DHT22 sensor has four terminals (V cc, DATA, NC, GND), which are connected to the
board as follows −

 DATA pin to Arduino pin number 2


 Vcc pin to 5 volt of Arduino board
 GND pin to the ground of Arduino board
 We need to connect 10k ohm resistor (pull up resistor) between the DATA and the
Vcc pin
Once hardware connections are done, you need to add DHT22 library to your Arduino
library file as described earlier.

Result
You will see the temperature and humidity display on serial port monitor which is
updated every 2 seconds.
Arduino - Temperature Sensor
The Temperature Sensor LM35 series are precision integrated-circuit temperature
devices with an output voltage linearly proportional to the Centigrade temperature.
The LM35 device has an advantage over linear temperature sensors calibrated in
Kelvin, as the user is not required to subtract a large constant voltage from the output
to obtain convenient Centigrade scaling. The LM35 device does not require any
external calibration or trimming to provide typical accuracies of ±¼°C at room
temperature and ±¾°C over a full −55°C to 150°C temperature range.

Technical Specifications
 Calibrated directly in Celsius (Centigrade)
 Linear + 10-mV/°C scale factor
 0.5°C ensured accuracy (at 25°C)
 Rated for full −55°C to 150°C range
 Suitable for remote applications

Components Required
You will need the following components −

 1 × Breadboard
 1 × Arduino Uno R3
 1 × LM35 sensor

Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.

Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
Arduino Code
float temp;
int tempPin = 0;

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

void loop() {
temp = analogRead(tempPin);
// read analog volt from sensor and save to variable temp
temp = temp * 0.48828125;
// convert the analog volt to its temperature equivalent
Serial.print("TEMPERATURE = ");
Serial.print(temp); // display temperature value
Serial.print("*C");
Serial.println();
delay(1000); // update sensor reading each one second
}

Code to Note
LM35 sensor has three terminals - V s, Vout and GND. We will connect the sensor as
follows −

 Connect the +Vs to +5v on your Arduino board.


 Connect Vout to Analog0 or A0 on Arduino board.
 Connect GND with GND on Arduino.
The Analog to Digital Converter (ADC) converts analog values into a digital
approximation based on the formula ADC Value = sample * 1024 / reference voltage
(+5v). So with a +5 volt reference, the digital approximation will be equal to input
voltage * 205.

Result
You will see the temperature display on the serial port monitor which is updated every
second.
Arduino - Water Detector / Sensor
Water sensor brick is designed for water detection, which can be widely used in
sensing rainfall, water level, and even liquid leakage.

Connecting a water sensor to an Arduino is a great way to detect a leak, spill, flood,
rain, etc. It can be used to detect the presence, the level, the volume and/or the
absence of water. While this could be used to remind you to water your plants, there is
a better Grove sensor for that. The sensor has an array of exposed traces, which read
LOW when water is detected.
In this chapter, we will connect the water sensor to Digital Pin 8 on Arduino, and will
enlist the very handy LED to help identify when the water sensor comes into contact
with a source of water.

Components Required
You will need the following components −

 1 × Breadboard
 1 × Arduino Uno R3
 1 × Water Sensor
 1 × led
 1 × 330 ohm resistor

Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.

Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking on New.
Arduino Code
#define Grove_Water_Sensor 8 // Attach Water sensor to Arduino
Digital Pin 8
#define LED 9 // Attach an LED to Digital Pin 9 (or use onboard
LED)

void setup() {
pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an
Input
pinMode(LED, OUTPUT); // The LED is an Output
}

void loop() {
/* The water sensor will switch LOW when water is detected.
Get the Arduino to illuminate the LED and activate the buzzer
when water is detected, and switch both off when no water is
present */
if( digitalRead(Grove_Water_Sensor) == LOW) {
digitalWrite(LED,HIGH);
}else {
digitalWrite(LED,LOW);
}
}

Code to Note
Water sensor has three terminals - S, V out(+), and GND (-). Connect the sensor as
follows −
 Connect the +Vs to +5v on your Arduino board.
 Connect S to digital pin number 8 on Arduino board.
 Connect GND with GND on Arduino.
 Connect LED to digital pin number 9 in Arduino board.
When the sensor detects water, pin 8 on Arduino becomes LOW and then the LED on
Arduino is turned ON.

Result
You will see the indication LED turn ON when the sensor detects water.
Arduino - PIR Sensor
PIR sensors allow you to sense motion. They are used to detect whether a human has
moved in or out of the sensor’s range. They are commonly found in appliances and
gadgets used at home or for businesses. They are often referred to as PIR, "Passive
Infrared", "Pyroelectric", or "IR motion" sensors.
Following are the advantages of PIR Sensors −

 Small in size
 Wide lens range
 Easy to interface
 Inexpensive
 Low-power
 Easy to use
 Do not wear out

PIRs are made of pyroelectric sensors, a round metal can with a rectangular crystal in
the center, which can detect levels of infrared radiation. Everything emits low-level
radiation, and the hotter something is, the more radiation is emitted. The sensor in a
motion detector is split in two halves. This is to detect motion (change) and not average
IR levels. The two halves are connected so that they cancel out each other. If one-half
sees more or less IR radiation than the other, the output will swing high or low.
PIRs have adjustable settings and have a header installed in the 3-pin
ground/out/power pads.

For many basic projects or products that need to detect when a person has left or
entered the area, PIR sensors are great. Note that PIRs do not tell you the number of
people around or their closeness to the sensor. The lens is often fixed to a certain
sweep at a distance and they are sometimes set off by the pets in the house.

Components Required
You will need the following components −

 1 × Breadboard
 1 × Arduino Uno R3
 1 × PIR Sensor (MQ3)

Procedure
Follow the circuit diagram and make the connections as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.

Arduino Code
#define pirPin 2
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int PIRValue = 0;

void setup() {
Serial.begin(9600);
pinMode(pirPin, INPUT);
}

void loop() {
PIRSensor();
}

void PIRSensor() {
if(digitalRead(pirPin) == HIGH) {
if(lockLow) {
PIRValue = 1;
lockLow = false;
Serial.println("Motion detected.");
delay(50);
}
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW) {
if(takeLowTime){
lowIn = millis();takeLowTime = false;
}
if(!lockLow && millis() - lowIn > pause) {
PIRValue = 0;
lockLow = true;
Serial.println("Motion ended.");
delay(50);
}
}
}

Code to Note
PIR sensor has three terminals - Vcc, OUT and GND. Connect the sensor as follows −

 Connect the +Vcc to +5v on Arduino board.


 Connect OUT to digital pin 2 on Arduino board.
 Connect GND with GND on Arduino.
You can adjust the sensor sensitivity and delay time via two variable resistors located
at the bottom of the sensor board.
Once the sensor detects any motion, Arduino will send a message via the serial port to
say that a motion is detected. The PIR sense motion will delay for certain time to check
if there is a new motion. If there is no motion detected, Arduino will send a new
message saying that the motion has ended.

Result
You will see a message on your serial port if a motion is detected and another
message when the motion stops.
Arduino - Ultrasonic Sensor
The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object
just like the bats do. It offers excellent non-contact range detection with high accuracy
and stable readings in an easy-to-use package from 2 cm to 400 cm or 1” to 13 feet.
The operation is not affected by sunlight or black material, although acoustically, soft
materials like cloth can be difficult to detect. It comes complete with ultrasonic
transmitter and receiver module.

Technical Specifications
 Power Supply − +5V DC
 Quiescent Current − <2mA
 Working Current − 15mA
 Effectual Angle − <15°
 Ranging Distance − 2cm – 400 cm/1″ – 13ft
 Resolution − 0.3 cm
 Measuring Angle − 30 degree

Components Required
You will need the following components −

 1 × Breadboard
 1 × Arduino Uno R3
 1 × ULTRASONIC Sensor (HC-SR04)

Procedure
Follow the circuit diagram and make the connections as shown in the image given
below.

Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
Arduino Code
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor

void setup() {
Serial.begin(9600); // Starting Serial Terminal
}

void loop() {
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}

long microsecondsToInches(long microseconds) {


return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {


return microseconds / 29 / 2;
}

Code to Note
The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND connected as
follows −

 Connect the +5V pin to +5v on your Arduino board.


 Connect Trigger to digital pin 7 on your Arduino board.
 Connect Echo to digital pin 6 on your Arduino board.
 Connect GND with GND on Arduino.
In our program, we have displayed the distance measured by the sensor in inches and
cm via the serial port.

Result
You will see the distance measured by sensor in inches and cm on Arduino serial
monitor.
Arduino - Connecting Switch
Pushbuttons or switches connect two open terminals in a circuit. This example turns on
the LED on pin 2 when you press the pushbutton switch connected to pin 8.

Pull-down Resistor
Pull-down resistors are used in electronic logic circuits to ensure that inputs to Arduino
settle at expected logic levels if external devices are disconnected or are at high-
impedance. As nothing is connected to an input pin, it does not mean that it is a logical
zero. Pull down resistors are connected between the ground and the appropriate pin on
the device.
An example of a pull-down resistor in a digital circuit is shown in the following figure. A
pushbutton switch is connected between the supply voltage and a microcontroller pin.
In such a circuit, when the switch is closed, the micro-controller input is at a logical high
value, but when the switch is open, the pull-down resistor pulls the input voltage down
to the ground (logical zero value), preventing an undefined state at the input.
The pull-down resistor must have a larger resistance than the impedance of the logic
circuit, or else it might pull the voltage down too much and the input voltage at the pin
would remain at a constant logical low value, regardless of the switch position.
Components Required
You will need the following components −

 1 × Arduino UNO board


 1 × 330 ohm resistor
 1 × 4.7K ohm resistor (pull down)
 1 × LED

Procedure
Follow the circuit diagram and make the connections as shown in the image given
below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking on New.

Arduino Code
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 8; // the number of the pushbutton pin
const int ledPin = 2; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

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

void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

Code to Note
When the switch is open, (pushbutton is not pressed), there is no connection between
the two terminals of the pushbutton, so the pin is connected to the ground (through the
pull-down resistor) and we read a LOW. When the switch is closed (pushbutton is
pressed), it makes a connection between its two terminals, connecting the pin to 5
volts, so that we read a HIGH.

Result
LED is turned ON when the pushbutton is pressed and OFF when it is released.

You might also like