Mechatronics Lab Manual 1-8
Mechatronics Lab Manual 1-8
Mechatronics Lab Manual 1-8
LIST OF EXPERIMENTS
Introduction to Mechatronics
Sr. Taxonomy
Title of Experiment CLO PLO
No. Level
P3 (Guided
2 To Practice basics of Arduino Software 1 PLO_1
Response)
P3 (Guided
4 Practicing the interfacing stepper motor with Arduino 1 PLO_1
Response)
P3 (Guided
5 Practicing the interface of servo motor with Arduino 1 PLO_1
Response)
2
Lab # 01 ................................................................................................................................................... 4
To Practice Basics of Arduino Hardware ................................................................................................. 4
Lab # 02 ................................................................................................................................................... 8
To Practice Basic of Arduino Software .................................................................................................... 8
Lab # 03 ................................................................................................................................................. 13
Practicing the Interfacing of four channel relay module with Arduino ................................................ 13
Lab # 04 ................................................................................................................................................. 17
Control Stepper Motor with L298N Motor Driver & Arduino............................................................... 17
Lab # 05 ................................................................................................................................................. 22
Practicing the interface of servo motor with arduino .......................................................................... 22
Lab # 06 ................................................................................................................................................. 26
Practicing the interface of thermocouple sensor with Arduino ........................................................... 26
Lab # 07 ................................................................................................................................................. 34
Practicing the water Level indicating system using Arduino ................................................................ 34
Lab # 08 ................................................................................................................................................. 41
Practicing the interfacing keypad with Arduino and controlling electric door lock ............................. 41
Lab # 09 ................................................................................................................................................. 54
Demonstrate the Introduction to MATLAB GUI and Interfacing Arduino with MATLAB...................... 54
Lab # 10 ................................................................................................................................................. 61
Executing the interfacing of 4 channel relay module with Arduino Using MATLAB GUI...................... 61
Lab # 11 ................................................................................................................................................. 71
Executing the Interfacing PIR sensor with Arduino and controlling appliances with the help of relay
module .................................................................................................................................................. 71
3
Lab # 01
Objective
To understand commonly available different types of Arduino boards available in market the
number of digital inputs/outputs, number of analog Inputs, clock frequency and other features
of different Arduino boards available in market.
Arduino board is an open-source platform used to make electronics projects. It consists of both
a microcontroller and a part of the software or Integrated Development Environment (IDE) that
runs on your PC, used to write & upload computer code to the physical board. The platform of
an Arduino has become very famous with designers or students just starting out with
electronics, and for an excellent cause.
4
Features of Different Types of Arduino Boards
The features of different types of Arduino boards are listed in the tabular form.
Arduino Board Processor Memory Digital I/O Analogue I/O
Arduino UNO Board or Genuino Uno Board is an open-source microcontroller board based
on ATmega328p chip. It is a widely used board of the Arduino Boards Family. Arduino Uno
features 14 digital I/O pins (6 pins can be used as PWM), 6 analog inputs, a 16 MHz quartz
crystal, a USB connection, Power Jack and a Reset Button.
5
I/O lines.
1. USB Connector
USB connector is used for two purposes in Arduino. The first one is to load the user program
to Arduino using Arduino IDE and another one is to power Arduino Board. Learn uploading
program to the Arduino board.
2. Power Port
The Arduino can be powered using AC to DC adapter or battery. 2.1mm center-positive plug
is used to power the Arduino Board. Recommended input power Voltage is 7-12V.
Arduino has Atmel ATmega16U2 as a USB interface chip. It is a bridge between Computer’s
USB Port and the main processor’s serial port.
In Arduino Uno board 14 Digital I/O Pins. The 14 Digital I/O Pins are numbered from Pin 0 to
Pin 13. In which 6 of them are PWM (Pulse-Width Modulation) Digital I/O Pins. Pin no 3, 5,
6, 9, 10, and 11 are PWM Pins which are marked as (~) symbol on the board. PWM pins are
used to simulate analog output. Digital I/O Pins are used to take Digital Input or provide Digital
Output in Arduino Uno Board.
In Arduino Uno board 6 Analog Input Pins. The 6 Analog Input Pins are numbered from Pin
A0 to Pin A5. Analog Input Pins are used to take the signal from analog sensors and convert it
into a digital value. The pins measure the voltage not current because it has a very high value
of internal resistance. So, the value of the current is much smaller as compared to the voltage.
6. Power Pins
Vin – The input voltage to the Arduino/Genuino board when it’s using an external power
source.
5V – This pin outputs a regulated 5V from the regulator on the board. Supplying voltage
via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don’t
advise it.
3V3 – This pin outputs a regulated 3.3-volt supply generated by the onboard regulator. The
maximum current draw from this pin is 50 mA.
GND – Ground pins.
IOREF – This pin on the Arduino/Genuino board provides the voltage reference with which
the microcontroller operates. A properly configured shield can read the IOREF pin voltage
and select the appropriate power source or enable voltage translators on the outputs to work
with the 5V or 3.3V.
7. Voltage Regulator
6
The main work of the Voltage Regulator is to regulate the input and output voltage of the
Arduino Uno board. It also regulates the voltage for 5V and 3V3 pins. If the power voltage of
the power port is more than 12V, the voltage regulator may overheat and damage the board.
Master Reset Button is used to reset the Arduino Uno board and restart the running program
from starting. It is useful when the programmer wants to run the program from the starting
point. When Master Reset Button is pressed, it sends the logical pulse to the reset pin of the
microcontroller.
A Full form of ICSP is In-Circuit Serial Programming also called In-System Programming
(ISP). It is used to program AVR microcontrollers. You can use the Arduino ISP to upload
sketches directly on the AVR-based Arduino boards without the need of the bootloader ICSP
Header Pins contains six pins MISO (Master In Slave Out), +Vcc, SCK (Serial Clock), MOSI
(Master Out Slave In), Reset, GND.
The RX and TX LEDs on the board will flash when data is being transmitted via the USB-to-
serial chip and USB connection to the computer.
Lab Task
1. Explain Arduino mega along with picture.
7
Lab # 02
Objective
This section will give quick references on how to get started with the Arduino Uno. However,
to understand the Arduino Uno and how it is being used in ME2110, you must read through
the rest of the manual.
Setup Steps
The Arduino IDE (Integrated Development Environment) allows you to write programs and
upload them to your Arduino. Have your Arduino board and USB cable near your computer?
Do not plug them in yet.
Download the latest version of the IDE from: a rduino.cc/download Windows Installation
After finishing the download, navigate to your download path and double-click on “arduino-
1.x.x-rx-windows.exe” (where the x depends on the version you downloaded). If a security
warning window shows up, click on” Run” or “Allow” and accept the License Agreement.
Click on “next” to choose the folder to install the IDE and click on “Install”.
Connect the Arduino board to the computer using a proper USB cable. The board will
automatically draw power from the USB connection of the computer and the green LED
(labeled ON) will turn on.
Windows should initiate its driver installation process when the board is plugged in. In some
cases, your computer won’t be able to find the drivers by itself. If so, you need to point it to
the proper folder.
Windows XP: If Windows Update asks about the path for the software, select “Yes, for this
time only” and the “Install from a list or specific location”
Other: A popup window asks you to install the driver automatically or to look for it in the
computer, choose to look for the driver on your computer.
If the installation doesn’t start automatically, click on the Start Menu and open the device
manager.
Look for the Arduino device under the category “Other Devices” or “Unknown Devices” and
select “Update Driver” or “Update Driver Software” clicking with the right button of the mouse.
Click on “browse” and select the “Drivers” folder (not the folder “FTDI USB Drivers”) in the
Arduino software IDE folder. Press “OK” and “Next”. If a dialog box about a
test on the Windows Logo shows up, click on “Continue Anyway”. Windows will now install
the driver.
8
In the “Device Manager”, under “Ports (COM & LPT)”, you should see a port similar to
“Arduino Uno (COM4)”.
Communicating with The Arduino
After the Arduino software IDE has been installed, you can now upload a program.
Open the Arduino IDE and appropriate program you would like to upload to the
microcontroller.
Ensure that the correct Board Type has been selected under “Tools” (1)
Ensure that the correct Communication Port has been selected. (2)
Use the button to verify the code does not have syntax or build errors. (3)
Use the button to upload the code to the Arduino. This will also verify the code, so Step
4 is optional.
9
Writing an Arduino Sketch
Programs in Arduino are called “sketches.” This is where the microcontroller will read sensors
and control actuators. The ME2110 library downloaded from GitHub handles most of the
coding required, reducing the overall complexity of the coding portion. An in-depth discussion
of the functions within the library is included later in this manual.
Each time you initialize the Arduino IDE a new, blank sketch is opened for you. Every sketch
in Arduino has two core functions prepopulated:
A setup function
Anything you want to set up (variables, initial variable states, etc.) will be done here and run
only once.
A loop function
Once the setup function has run, the microcontroller will run this loop repeatedly. Generally,
the bulk of your code will reside here.
10
Otherwise do task 3.
Programmatically it can be represented in pseudocode as:
if(condition==True){ do task 1;
}elseif(othercondition==True){ do task 2;
} else {
do task 3;
}
Loops
Loops are an implementation of “if-else” statements. The code inside a loop will be run
continuously until a number of iterations have passed (for loop) or until a condition is no longer
true (while loop). The loop function that almost every Arduino program uses is an example of
an infinite while loop. An example of a for loop could be:
Do task 1 until the 5 iterations have passed Programmatically:
for (int i = 0; i <= 5; i++) { do task 1;
}
To ensure the encoder is read correctly, you must include a wrapper function. This is done with
void encHandler() and its contents. A special function called an interrupt is used to read the
encoders. attachInterrupt(digitalPinToInterrupt(X), encHandler,
CHANGE);is added to the void setup()function to use it whenever the encoder is
turned. Note that there is one interrupt per channel of the encoder.
The last inclusion is optional but useful for debugging your sketch as you work.
Serial.begin(9600); opens a communication port between the Arduino and your computer. You
can print sensor data and other useful information to this monitor.
11
Lab Task
1) Write down a simple LED Blink code for Arduino and blink build in LED.
12
Lab # 03
Objective
Relay module for Arduino is one of the most powerful application for Arduino as it can be used
to control both A.C and D.C devices by simply controlling the relay by giving 5V. A relay is
basically a switch which is operated electrically by electromagnet. A relay can be used to
control high voltage electronic devices such as motors and as well as low voltage electronic
devices such as a light bulb or a fan.
Relays works on the principle of electromagnetism. When the electricity is provided to
the relay coil then it acts like a magnet and changes the state of the switch. The part which
powers the relay module is completely isolated from the part which turns ON or OFF. This is
why we can control a 220V appliance by simply controlling it using the 5V Arduino. you
should also read getting started projects of Arduino.
Components
Arduino Uno (You can use any other type)
4 Relay module
3v Battery
LED’s
1k ohm resistors
Breadboard
Relay Module
There many types of relay modules available like 1 relay, 2 relay, 5 relay and 8 relay but we
are using the 4 relay Arduino module. Once you will understand this then you can use all
other types.
13
Relay Module Pinout
Input Connections of relay module
Input2 (IN 2): This will be connected to the digital pin on your Arduino, or leave it unconnected
if you do not want to use this channel.
Input3 (IN 3): This will be connected to the digital pin on your Arduino, or leave it unconnected
if you do not want to use this channel.
Input4 (IN 4): This will be connected to the digital pin on your Arduino, or leave it unconnected
if you do not want to use this channel.
Logic VCC: This will be connected to the 5v pin of the Arduino o power the 4-relay module.
You can also power the 4-relay module using the external power by giving voltage from 5 to
24V DC.
14
Code of relay module interfacing with Arduino
The following code is for the basic 4 Relay Module connection to the Arduino. Each relay will
turn on for 5 seconds and then will turn off. You will hear the click sound as their state changes
from OFF to ON or from ON to OFF. You will also see the Red LED on the 4 Relay board
light up when the relay will on. Necessary comments are made in the code for better
understanding. For 4 input relay modules, we will turn on each relay for 5 seconds and than
turn it off.
#define RELAY1 7 //Defining the pin 7 of the Arduino for the 4 relay module
#define RELAY2 6 //Defining the pin 6 of the Arduino for the 4 relay module
#define RELAY3 5 //Defining the pin 5 of the Arduino for the 4 relay module
#define RELAY4 4 //Defining the pin 4 of the Arduino for the 4 relay module
void setup()
{
pinMode(RELAY1, OUTPUT); //Defining the pin 7 of the Arduino as output
pinMode(RELAY2, OUTPUT); //Defining the pin 6 of the Arduino as output
pinMode(RELAY3, OUTPUT); //Defining the pin 5 of the Arduino as output
pinMode(RELAY4, OUTPUT); //Defining the pin 4 of the Arduino as output
}
15
void loop()
{
digitalWrite(RELAY1,LOW); // This will Turn ON the relay 1
delay(5000); // Wait for 5 seconds
digitalWrite(RELAY1,HIGH); // This will Turn the Relay Off
16
Lab # 04
One of the easiest and inexpensive way to control stepper motors is to interface L298N Motor
Driver with Arduino. It can control both speed and spinning direction of any Bipolar stepper
motor like NEMA 17.
If you are planning on building your own 3D printer or a CNC machine, you will need to
control a bunch of stepper motors. And having one Arduino control all of them is not a good
option. Instead, it is recommended to use a dedicated stepper motor driver like A4988.
17
Below image illustrates driving stepper with H-Bridge.
Before we start hooking the motor up with the module, you will need to determine the A+, A-
, B+ and B- wires on the motor you plan to use. The best way to do this is to check the
datasheet of the motor. For our motor these are red, green, blue and yellow.
18
The connections are fairly simple. Start by connecting external 12V power supply to the VCC
terminal. And keep the 5V-EN jumper in place.
You also need to keep both the ENA & ENB jumpers in place so the motor is always enabled.
Now, connect the input pins (IN1, IN2, IN3 and IN4) of the L298N module to four Arduino
digital output pins (8, 9, 10 and 11).
Finally, connect the A+, A-, B+ and B- wires from the stepper motor to the module as shown
in the illustration below.
19
// Create Instance of Stepper library
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
void setup()
{
// set the speed at 60 rpm:
myStepper.setSpeed(60);
// initialize the serial port:
Serial.begin(9600);
}
void loop()
{
// step one revolution in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);
20
Next, we create an instance of the stepper library. It takes the steps per revolution of motor &
Arduino pin connections as parameter.
// Create Instance of Stepper library
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
In setup section of code, we set the speed of stepper motor by calling setSpeed() function and
initialize the serial communication.
void setup()
{
// set the speed at 60 rpm:
myStepper.setSpeed(60);
// initialize the serial port:
Serial.begin(9600);
}
In loop section of code, we simply call step() function which turns the motor a specific number
of steps at a speed determined by setSpeed() function. Passing a negative number to this
function reverses the spinning direction of motor.
void loop()
{
// step one revolution in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);
Lab Task
Revolve Stepper Motor 180o Clockwise and Counter clockwise with speed of 100?
21
Lab # 05
Objective
There are many beginners suffering from the basics of Arduino. So I decided to start a series
of articles discussing about basics of Arduino programming. Many of students and hobbyists
have a very good interest in electronics. And they drop their interest because of programming.
But the true fact is Arduino programming very simple. We need to understand the every line
of code and it's use.
In this article I am using only one Servo Motor. The Code is only for one Servo. For multiple
Servos the code may change. If you understand this code you will able to control multiple
servos.
COMPONENTS
Arduino UNO
SG 90 Micro-servo motor
UTSOURCE Electronics Parts
Jumper Wires
Arduino IDE
Steps
Arduino IDE is a great tool to develop the code and uploading the code to Arduino Board.
Step -1
In this project we need to use a library named "Servo.h". This is a inbuilt library with Arduino
IDE.
There is two way to include a library
Go to Sketch>Include library>Servo
OR
Just type #include<Servo.h>
#include<Servo.h>
Step -2
Next we need to declare a integer type variable. Now I am using the variable named as "pos".
This variable can only hold integer values.
Step - 3
In the declaration part, we need to declare another variable. Here I am using the variable name
as "Myservo". You can also use any other names. This variable is used to connect the
corresponding servo to the entire code. Here we using the keyword "Servo". The syntax is
22
"Servo variable_name". The code is look like,
Servo Myservo;
Step - 4
Every Arduino program is consist of a "void setup()" function and "void loop()" function.
When we turn on the Arduino the functions/statements in "void setup()" will work first and it
will work once. After that the functions/statements in void loop() will work like a loop.
We need to set the signal pin of servo motor to Arduino pin In the "void setup()". In the clear
voice, Here we are declaring which pin of Arduino to control the servo motor. Here we are
using Digital Pin 3 of Arduino to control the servo motor.
Here we using the keyword attach(). The syntax is "variable_name.attach(pin_number)". The
code is look like,
Myservo.attach(3);
Step - 5
Let discuss about the servo control statement. The keyword is "write()". and the syntax is
"variable_name.write(pos)". We can either use a variable or number which is in between 0 and
360 in write function.
Myservo.write(pos);
Step - 6
Now we need set a loop function. Here we are using "for()" loop to control the servo motor. In
for() loop, set the minimum value is 0. ie. (.pos=0) and maximum value is 180. ie. (pos<=180).
Then incriment the pos ie.(pos++). Then implement the write function(function in Step-6) in
the for loop. Then add a delay function. This delay function help to waits 15ms for the servo
to reach the position.
for(pos=0;pos<=180;pos++){
Myservo.write(pos);
delay(15);
}
Step - 7
Then add another delay function after the for() loop. This delay function for wait a
corresponding time(which is included in delay function) after above for loop.
delay(1000);
Step - 8
Now we need set another loop function. Here we are using "for()" loop to control the servo
motor. In for() loop, set the minimum value is 180. ie. (.pos=180) and maximum value is 0. ie.
(pos>=0). Then decriment the pos ie.(pos--). Then implement the write function(function in
Step-6) in the for loop. Then add a delay function. This delay function help to waits 15ms for
the servo to reach the position.
for(pos=180;pos>=0;pos--){
Myservo.write(pos);
delay(15);
}
Step - 9
23
Then add another delay function after the for() loop. This delay function for wait a
corresponding time(which is included in delay function) after above for loop.
delay(1000);
CODE
Arduino Uno with Servo Motor
Connect the servo signal pin to Arduino Pin 3
#include<Servo.h>
Servo Myservo;
int pos;
void setup()
{
Myservo.attach(3);
}
void loop()
{
for(pos=0;pos<=180;pos++){
Myservo.write(pos);
delay(15);
}
delay(1000);
for(pos=180;pos>=0;pos--){
Myservo.write(pos);
delay(15);
}
delay(1000);
}
SCHEMATICS
Arduino Uno with one Servo Motor
24
25
Lab # 06
Objective
In this lab, we will learn how to read temperature using a K-Type Thermocouple with the
MAX6675 amplifier with the Arduino board. A K-type thermocouple is a type of temperature
sensor with a wide measurement range like −200ºC to 1350ºC (−326 to 2300ºF).
This lab covers how to interface the k-type thermocouple with your Arduino board, install the
required library and use a simple sketch to display the sensor readings in the Serial Monitor.
Components
Arduino UNO
MAX6675 Amplifier
K-Type thermocouple
What is a K-Type Thermocouple?
A thermocouple is a device that consists of two different electrical conductors that form an
electrical junction—thermal junction. The change in temperature at the junction creates a
slightly but measurable voltage at the reference junction that can be used to calculate the
temperature.
A thermocouple can be made of different metals. The metals used will affect the voltage range,
cost, and sensitivity. There are standardized metal combinations that result in different
thermocouple types: B, E, J, N, K, R, T, and S.
Our lab is about the k-type thermocouple. A k-type thermocouple is made out of chrome and
alumel conductors and has a general temperature range of -200 to 1260ºC (-326 to 2300ºF).
26
MAX6675 Amplifier
To get the temperature from the thermocouple we need a thermocouple amplifier. The
temperature output from the thermocouple amplifier depends on the voltage read on the
reference junction. The voltage at the reference junction depends on the temperature difference
between the reference junction and the thermal junction. So, we need to know the temperature
at the reference junction.
The MAX6675 thermocouple comes with a temperature sensor to measure temperature at the
reference junction (cold-compensation reference) and amplifies the tiny voltage at the reference
junction so that we can read it using our microcontrollers. The MAX6675 amplifier
communicates with a microcontroller using the SPI communication protocol and the data is
output in a 12-bit resolution.
27
Usually, you can get a pack with a k-type thermocouple and the MAX6675 amplifier. Here’s a
list of the MAX6675 most relevant features.
Direct digital conversion of k-type thermocouple output
Cold-junction compensaiton
Simple SPI-compatible serial interface
Operating voltage range: 3.0 to 5.5V
Operating temperature range: -20 to 85ºC
Resolves temperatures to 0.25ºC, allows readings as high as 1024ºC (1875ºF).
Interfacing K-Type Thermocouple with MAX6675 Amplifier
As mentioned previously, the MAX6675 communicates with a microcontroller using SPI
communication protocol.
MAX6675 Microcontroller
SO MISO
CS CS
SCK CLK
GND GND
28
Get Temperature from K-Type Thermocouple with MAX6675 Amplifier
In this section, you’ll learn how to get temperature from your k-type thermocouple. We’ll show
you a simple example that reads the temperature and displays it on the Arduino IDE Serial
Monitor.
MAX6675 Arduino
29
GND GND
VCC 3.3V
SCK Pin 6
CS Pin 5
SO Pin 4
30
#include "max6675.h"
int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;
void setup() {
Serial.begin(9600);
Serial.println("MAX6675 test");
// wait for MAX chip to stabilize
delay(500);
}
void loop() {
// basic readout test, just print the current temp
Serial.print("C = ");
Serial.println(thermocouple.readCelsius());
Serial.print("F = ");
Serial.println(thermocouple.readFahrenheit());
// For the MAX6675 to update, you must delay AT LEAST 250ms between reads!
delay(1000);
}
How the Code Works
First, include the max6675.h library.
#include "max6675.h"
Define the pins that are interfacing with the MAX6675 thermocouple amplifier.
int thermoDO = 12;
int thermoCS = 15;
int thermoCLK = 14;
31
Create a MAX6675 object called thermocouple on the pins we’ve defined previously.
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
In the setup(), initialize the Serial Monitor at a baud rate of 9600.
Serial.begin(9600);
In the loop(), we read the temperature and display it on the Serial Monitor. The library provides
a method to read the temperature in Celsius and a method to read the temperature in Fahrenheit
degrees.
thermocouple.readCelsius(): returns temperature in Celsius degrees.
thermocouple.readFahrenheit(): returns temperature in Fahrenheit degrees.
The following lines read the temperature and display it on the Serial Monitor.
Serial.print("C = ");
Serial.println(thermocouple.readCelsius());
Serial.print("F = ");
Serial.println(thermocouple.readFahrenheit());
As you can see, it’s very simple to get temperature readings using the K-type thermocouple
with the MAX6675 amplifier.
Demonstration
Upload the code to your Arduino board. Don’t forget the select the board you’re using
in Tools > Board and select the COM port your board is connected to in Tools > Port.
After uploading the code, open the Serial Monitor at a baud rate of 9600.
New temperature readings are displayed on the Serial Monitor every second.
Lab Task
Operate Fan relay when temperature is above 25 oC using thermocouple and relay module.
32
33
Lab # 07
Objective
The water level indicator with Arduino is a mini water management system. Here, you will get
step by step guide of how to build this water level indicator.
By using this project you will get an exact idea about how much water you should use.
Nowadays, all over world, there is a water crisis. To solve this crisis, we need proper water
management on the individual level and we need a water level indicator. By doing water
management at the individual level we can save plenty of water and could get rid of the water
crisis.
You may have a doubt here about how to do water management individually? Well, it's simple.
All we have to do is to use a little sensor in our water storage system i.e. water tank.
The sensor will give you an indication of the water level in your water tank. If you know the
water level every time, you can easily turn your water pump ON/OFF as per the need.
In this tutorial, we are going to interface the water level sensor with the Arduino UNO and we
are going to measure the water level of the water tank. If the water level will be low it will turn
ON the pump, If the water level is high it will turn it OFF.
Components
Water level sensor
Arduino Uno
Connecting Wires
LEDs
Resistors
Breadboard
34
Let's discuss, what is water level sensor, its hardware, working, and pin description in detail.
Hardware Outline Of The Water Level Sensor
Here, we are going to use a water level sensor to detect water levels. Basically, this sensor is a
combination of the attached series of ten exposed copper traces. The copper traces are merged
with each other in order to have one sense trace between two copper traces.
In short, there are alternate copper traces and sense traces. These traces form a bridge by water
when dipped in the water. For power indication, there is an onboard power LED.
Working Of The Water Level Sensor
This sensor works on the principle of variable resistance. The sensor consists of a series of
parallel exposed conductors. Together this series acts as a variable resistor, whose resistance
varies according to the water level in the water tank.
As more water sensor is submerged in, the better is the conductivity and the lower is the
resistance. The less the water sensor is submerged in, the poor is the conductivity and the higher
is the resistance.
The output of the water level sensor is according to the resistance of the water produced. i.e. it
will produce a voltage proportional with resistance.
35
Pin Description
S(signal pin) is an analog output that will be connected to the analog pin of the Arduino.
+VCC is powering pin of the sensor. The approved input voltage is 3.3v to 5v.
-GND is simply a ground connection.
How To Calibrate Water Level Sensor
To make sure the sensor provides accurate data you need to calibrate the sensor for the
particular type of water you are going to use.
Before initiating the project or storing the data in the sensor, you should see what readings you
are exactly getting from your sensor.
Make a note of the proper values of your sensor outputs when the sensor is completely dry,
when it is partially submerged in the water and when it is completely submerged.
In this calibration, you need to do some trial and error. It will be difficult in starting to calibrate
this sensor with accurate values. once you will get the accurate values you can handle the
project very well. Now you are ready to start.
36
Interfacing Diagram
Hook up your circuit as shown in the following diagram.
In this interfacing, connect the signal pin of the sensor to the A0 of the Arduino.
Connect the VCC of the sensor to the Digital pin 7 of the Arduino.
Connect GND of the sensor to the Ground of the Arduino.
Connect the cathode of RED, YELLOW, GREEN LED to the 2,3,4 digital pin of the Arduino
respectively.
Connect all anodes of the LED commonly to the GND pin of the Arduino.
In this way, you can interface this sensor with the Arduino.
Software & Code
Once your circuit is done, upload the following code in your Arduino software.
To represent our threshold level there are two variables that are used as the Upper Threshold
& Lower Threshold.
Below threshold level, red LED will turn on, above threshold level green LED will turn on, in
between these two levels yellow led will turn on.
/* Change these values based on your calibration values */
int lowerThreshold = 420;
int upperThreshold = 520;
// Sensor pins
#define sensorPower 7
#define sensorPin A0
37
// Declare pins to which LEDs are connected
int redLED = 2;
int yellowLED = 3;
int greenLED = 4;
void setup() {
Serial.begin(9600);
pinMode(sensorPower, OUTPUT);
digitalWrite(sensorPower, LOW);
void loop() {
int level = readSensor();
if (level == 0) {
Serial.println("Water Level: Empty");
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, LOW);
}
else if (level > 0 && level <= lowerThreshold) {
Serial.println("Water Level: Low");
digitalWrite(redLED, HIGH);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, LOW);
38
}
else if (level > lowerThreshold && level <= upperThreshold) {
Serial.println("Water Level: Medium");
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, HIGH);
digitalWrite(greenLED, LOW);
}
else if (level > upperThreshold) {
Serial.println("Water Level: High");
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, HIGH);
}
delay(1000);
}
39
40
Lab # 08
Objective
In this project, we are going to make a keyless door lock system which uses a 4X4 keypad to
enter the keys and a DC lock to open or close the door. A 16X2 LCD will be used for display
COMPONENTS
Arduino UNO
Button Pad 4x4
LCD - 16x2
Relay
9V battery
Potentiometer- 10k ohms
Resistor 10k ohm
.
Working
Whenever the keys are pressed, they are matched with the keys already stored. If the keys that
are pressed match the initial password stored in the EEPROM which is ‘1234’, then the lock
will open up. If the password does not match, then it will print “access denied” on the LCD.
If the ‘#’ key will be pressed, it will ask you to enter the current password and if it matches,
then it will ask you to enter the new password and the password will be changed.
Circuit Diagram
First, connect the 4X4 keypad to the Arduino; connect the first six pins on the 4X4 keypad
with the A0 and A5 pins on the Arduino. Then connect the last two pins on the 4X4 keypad
module to digital pins 3 and 2 on the Arduino.
After that, connect the LCD to the Arduino. The connections for connecting the LCD with the
Arduino are as follows
Connect pin 1 on the LCD, which is the VSS pin, to GND on the Arduino
Connect pin 2, which is the VDD pin, to the 5V pin on the Arduino
Connect pin 3, which is the V0, to the middle of the 10k potentiometer and connect the other
two pins on the potentiometer to 5V and GND on the Arduino. This pin is for setting the LCD’s
contrast.
41
Connect pin 4, which is the RS pin, to pin 7 on the Arduino
Connect pin 5, which is the R/W pin, to the GND pin on the Arduino
Connect pin 6, which is the Enable pin, to pin 6 on the Arduino
Connect pins 11, 12, 13, and 14 which are the data pins, to the pins 5, 4, 3, and 2 on the Arduino
Connect pin 15, which is the LCD’s backlight pin, to 5V on the Arduino through the 220-ohm
resistor
Connect pin 16 on the Arduino, which is the negative pin of the backlight, to GND on the
Arduino
Last, we will connect the DC lock with the Arduino. The Lock operates on a voltage from 7 to
12V, so we cannot directly connect it to the Arduino. To connect it to the Arduino, we will
require a relay and a battery.
Connect the signal pin of the relay to pin 10 on the Arduino and the lock’s VCC and GND to
5V and GND on the Arduino. Then on the other end of the relay, connect the negative of the
battery to the common on the relay and the NO (Normally open) on the relay to one side of the
lock. Then connect the other side of the lock to the positive terminal on the battery.
#include<LiquidCrystal.h>
#include<EEPROM.h>
LiquidCrystal liquid_crystal_display(9,8,7,6,5,4,);
42
char password[4];
char initial_password[4],new_password[4];
int i=0;
char key_pressed=0;
char hexaKeys[rows][columns] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
43
void setup()
pinMode(relay_pin, OUTPUT);
liquid_crystal_display.begin(16,2);
liquid_crystal_display.print(" DIYhacking.com");
liquid_crystal_display.setCursor(0,1);
delay(2000);
liquid_crystal_display.clear();
liquid_crystal_display.print("Enter Password");
liquid_crystal_display.setCursor(0,1);
initialpassword();
void loop()
44
digitalWrite(relay_pin, HIGH);
key_pressed = keypad_key.getKey();
if(key_pressed=='#')
change();
if (key_pressed)
password[i++]=key_pressed;
liquid_crystal_display.print(key_pressed);
if(i==4)
delay(200);
for(int j=0;j<4;j++)
initial_password[j]=EEPROM.read(j);
if(!(strncmp(password, initial_password,4)))
liquid_crystal_display.clear();
liquid_crystal_display.print("Pass Accepted");
45
digitalWrite(relay_pin, LOW);
delay(2000);
liquid_crystal_display.setCursor(0,1);
liquid_crystal_display.print("Pres # to change");
delay(2000);
liquid_crystal_display.clear();
liquid_crystal_display.print("Enter Password:");
liquid_crystal_display.setCursor(0,1);
i=0;
else
digitalWrite(relay_pin, HIGH);
liquid_crystal_display.clear();
46
liquid_crystal_display.print("Wrong Password");
liquid_crystal_display.setCursor(0,1);
liquid_crystal_display.print("Pres # to Change");
delay(2000);
liquid_crystal_display.clear();
liquid_crystal_display.print("Enter Password");
liquid_crystal_display.setCursor(0,1);
i=0;
void change()
int j=0;
liquid_crystal_display.clear();
liquid_crystal_display.print("Current Password");
47
liquid_crystal_display.setCursor(0,1);
while(j<4)
char key=keypad_key.getKey();
if(key)
new_password[j++]=key;
liquid_crystal_display.print(key);
key=0;
delay(500);
liquid_crystal_display.clear();
48
liquid_crystal_display.print("Wrong Password");
liquid_crystal_display.setCursor(0,1);
liquid_crystal_display.print("Try Again");
delay(1000);
else
j=0;
liquid_crystal_display.clear();
liquid_crystal_display.print("New Password:");
liquid_crystal_display.setCursor(0,1);
while(j<4)
char key=keypad_key.getKey();
if(key)
initial_password[j]=key;
liquid_crystal_display.print(key);
49
EEPROM.write(j,key);
j++;
liquid_crystal_display.print("Pass Changed");
delay(1000);
liquid_crystal_display.clear();
liquid_crystal_display.print("Enter Password");
liquid_crystal_display.setCursor(0,1);
key_pressed=0;
void initialpassword(){
for(int j=0;j<4;j++)
EEPROM.write(j, j+49);
50
for(int j=0;j<4;j++)
initial_password[j]=EEPROM.read(j);
}
Code Explanation
First of all, we will include the libraries for the 4X4 keypad, LCD, and a library for storing the
password. The EEPROM library is used to store the password. The default password stored in
it is ‘1234’.
#include <Keypad.h>
#include<LiquidCrystal.h>
#include<EEPROM.h>
In the loop function, the key pressed will be stored in the ‘key_pressed’ variable and it will be
compared with the other keys. If the pressed key is ‘#’, then the change function will be called
and it will ask for the new password.
key_pressed = keypad_key.getKey();
if(key_pressed=='#')
change();
The keys pressed are stored in the ‘password’ variable and these are shown on the LCD when
the keys are pressed. Then these keys will be matched with the initial password stored in the
EEPROM. If the keys that were pressed match the initial password, then the lock will get open
and “Pass accepted” will be printed on the LCD. If the password does not match, then it will
ask to enter the password again.
if (key_pressed)
password[i++]=key_pressed;
liquid_crystal_display.print(key_pressed);
51
if(i==4)
delay(200);
for(int j=0;j<4;j++)
initial_password[j]=EEPROM.read(j);
if(!(strncmp(password, initial_password,4)))
liquid_crystal_display.clear();
liquid_crystal_display.print("Pass Accepted");
digitalWrite(relay_pin, LOW);
delay(2000);
If the ‘#’ key is pressed, then it will call the ‘change()’ function. In the change function, it will
ask you to enter the current password. If the current password is correct, then it will ask you to
enter the new password. Upon entering the new password, the password will be changed.
void change()
int j=0;
liquid_crystal_display.clear();
liquid_crystal_display.print("Current Password");
liquid_crystal_display.setCursor(0,1);
52
while(j<4)
char key=keypad_key.getKey();
if(key)
new_password[j++]=key;
liquid_crystal_display.print(key);
key=0;
delay(500);
53