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

Mechatronics Lab Manual 1-8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

1

LIST OF EXPERIMENTS
Introduction to Mechatronics

Sr. Taxonomy
Title of Experiment CLO PLO
No. Level

To Practice basics of Arduino Hardware P3 (Guided


1 1 PLO_1
Response)

P3 (Guided
2 To Practice basics of Arduino Software 1 PLO_1
Response)

Practicing the Interfacing of 4 channel relay module with P3 (Guided


3 1 PLO_1
Arduino 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)

Practicing the interface of thermocouple sensor with P3 (Guided


6 1 PLO_1
Arduino Response)

Practicing a water level indicating system using Arduino P3 (Guided


7 1 PLO_1
+ (Open Ended Lab) Response)

Practicing the interfacing keypad with Arduino and P3 (Guided


8 1 PLO_1
control electric door lock Response)

Demonstrate the introduction to MATLAB GUI and


9 2 PLO_2 P4 (Mechanism)
interfacing Arduino with MATLAB

Executing the interfacing of 4 channel relay module with


10 2 PLO_2 P4 (Mechanism)
Arduino Using MATLAB GUI

Executing the Interfacing PIR sensor with Arduino and


11 3 PLO_3 P4 (Mechanism)
controlling appliances with the help of relay module
Executing the interfacing PIR sensor with Arduino and
12 controlling electronics door lock with the help of relay 3 PLO_3 P4 (Mechanism)
module
Making a Line follower robot using Arduino
13 3 PLO_3 P4 (Mechanism)
+ (Open Ended Lab)

14 Making a stair climbing robot using Arduino 3 PLO_3 P4 (Mechanism)

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

To Practice Basics of Arduino Hardware

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.

Types of Arduino Boards

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

16Mhz 2KB SRAM,


Arduino Uno ATmega328 32KB flash 14 6 input, 0 output

84MHz 96KB SRAM,


Arduino Due AT91SAM3X8E 512KB flash 54 12 input, 2 output

16MHz 8KB SRAM,


Arduino Mega ATmega2560 256KB flash 54 16 input, 0 output

16MHz 2.5KB SRAM,


Arduino Leonardo ATmega32u4 32KB flash 20 12 input, 0 output

What is the Arduino Uno Board?

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.

Basic Hardware of Arduino/Genuino Uno

Arduino/Genuino Uno Board contains


Micro-controller (ATmega328P)
Micro-controller used in Arduino is ATmega328P (a single chip micro-controller) created by
Atmel. It has 32KB programmable flash memory, 2KB SRAM, 1KB EEPROM (Electrically
Erasable Programmable Read-Only Memory). ATmege328P micro-controller operates
between 1.8 to 5.5 volt. It contains 26 input/output pins in which there are 23 general purposes

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.

3. USB Interface Chip

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.

4. Digital I/O Pins

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.

5. Analog Input Pins

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.

8. Master Reset Button

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.

9. ICSP Header Pins

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.

10. RX/TX LED

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

To Practice Basic of Arduino Software

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

● Download Arduino software (IDE)


● Connect your Arduino to your computer
● Download necessary libraries

Install Arduino IDE

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.

Sample Arduino IDE Window

The Arduino UNO

Simplified layout of the Arduino UNO microcontroller

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.

Blank Arduino Sketch


Arduino programming basics
As mentioned previously, Arduino uses a variant of C++ to run its programs. This manual will
not go in-depth on programming C++ but for those who are interested, there are numerous
tutorials and guides found online. The following is a brief outline of core structures and
background information to set up your Arduino.
Syntax
Learning to write in C++ is somewhat similar to MATLAB. Key things to note are to remember
to declare any variables and their type (int, char, etc.) before using them, use opening and
closing curly braces ({}) for functions such as if statements, and include semicolons at the end
of function calls.
If-else Conditions
An if statement is one of the basic logic building blocks - it is one of the ways you can use
Python to make decisions. The basic layout of an if statement in English can be viewed as:
If this condition has been met, then do task 1. If this other condition has been met, do task 2.

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

Practicing the Interfacing of four channel relay module with


Arduino

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.

Output Connections of relay module


Before getting into the output connections of the relay, we have to understand the NO, COM
and NC connections.
COM (Common connection): The COM is the centre terminal of the relay and it is used in both
(Normally open and normally closed) connections.
NO (Normally open): This act like a switch. In normally open connection, there will be no
contact between COM and NO, since it is normally open. But when we will activate the relay
module, then it will get connected to the COM and will supply power to the load, which will
power up the light. Thus, the circuit will initially be in open state until we trigger the state.
NC (Normally closed): its behaviour is opposite to the normally open connection. It always
remains in contact with COM, even when relay module is not powered. When we will trigger
the relay module then it will open the circuit, so the connection is lost.
We will use the normally open connection. When you will use the relays in NO (Normally
Open) connection and you set the corresponding IN pin to LOW, then the power will flow from
the COM connector and out of the normally open connector powering your device.
Relay 1 (K1): Connect one end of the load to the COM and the other end to the NO.
Connections for the K2, K3 and K4 are the same.
Relay module interfacing with Arduino
The connection of 4 relay module to an Arduino is very easy and allows you to control many
devices through Arduino (both A.C and D.C). In this example we will connect a simple load
such as a LED at the output of the relay and will control it by using the Arduino. First connect
the 5v of the Arduino to the VCC of the 4-relay module and the ground of the Arduino to the
ground of the 4-relay module. Then we will have to connect the communication pins IN1, IN2,
IN3, and IN4 to the Arduino data pins 7, 6, 5, and 4.
We will use a 3v battery to power the LED’s. So, we have connected the positive of the battery
to the positive side of the LED’s and then we have connected the negative side to the com of
each relay and the NO to the negative side of the LED’s.

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

digitalWrite(RELAY2,LOW); // This will Turn ON the relay


delay(5000); // Wait for 5 seconds
digitalWrite(RELAY2,HIGH); // This will Turn the Relay Off

digitalWrite(RELAY3,LOW); // This will Turn ON the relay


delay(5000); // Wait for 5 seconds
digitalWrite(RELAY3,HIGH); // This will Turn the Relay Off

digitalWrite(RELAY4,LOW); // This will Turn ON the relay


delay(5000); // Wait for 5 seconds
digitalWrite(RELAY4,HIGH); // This will Turn the Relay Off
}

16
Lab # 04

Control Stepper Motor with L298N Motor Driver & Arduino

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.

Control Stepper Motor with A4988 Driver Module & Arduino


If you are planning to build your own 3D printer or CNC machine, then you will need to control
a bunch of stepper motors. And...

Controlling a Stepper Motor with an H-Bridge


As L298N module has two H-Bridges, each H-Bridge will drive one of the electromagnetic
coils of a stepper motor.
By energizing these electromagnetic coils in a specific sequence, the shaft of a stepper can be
moved forward or backward precisely in small steps.
However, the speed of a motor is determined by the how frequently these coils are energized.

17
Below image illustrates driving stepper with H-Bridge.

Driving Bipolar Stepper Motor (NEMA 17)


In our experiment, we are using NEMA 17 bipolar stepper rated at 12V. It offers 200 steps per
revolution, and can operate at 60 RPM. If you don’t already have these specifications, find out
now as you will need them for the sketch.

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.

Wiring NEMA 17 Stepper Motor with L298N & Arduino


Arduino Code – Controlling NEMA 17 Stepper Motor
The following sketch will give you complete understanding on how to control a bipolar
stepper motor like NEMA 17 with L298N motor driver and can serve as the basis for more
practical experiments and projects.

// Include the Arduino Stepper Library


#include <Stepper.h>

// Number of steps per output rotation


const int stepsPerRevolution = 200;

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);

// step one revolution in the other direction:


Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
}
Code Explanation:
The sketch starts with including Arduino Stepper Library. The stepper library comes packaged
with the Arduino IDE and takes care of sequencing the pulses we will be sending to our stepper
motor.
// Include the Arduino Stepper Library
#include <Stepper.h>
After including the library, we define a variable named stepsPerRevolution. As the name
suggests it’s the number of steps per revolution that our motor is rated at. In this case it’s 200
i.e. 1.8 degrees per step.
// Number of steps per output rotation
const int stepsPerRevolution = 200;

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);

// step one revolution in the other direction:


Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
}

Lab Task
Revolve Stepper Motor 180o Clockwise and Counter clockwise with speed of 100?

21
Lab # 05

Practicing the interface of servo motor with arduino

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

Practicing the interface of thermocouple sensor with Arduino

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

VCC VCC (3.3V or 5V)

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.

Schematic – Arduino with K-type thermocouple and MAX6675 Amplifier


Wire the MAX6675 Amplifier to the Arduino as shown in the following schematic diagram.

You can also follow the next table.

MAX6675 Arduino

29
GND GND

VCC 3.3V

SCK Pin 6

CS Pin 5

SO Pin 4

Installing MAX6675 Arduino Library


There are different libraries to get temperature from a K-type thermocouple using the
MAX6675 amplifier. We’ll use the max6675 library from Adafruit.
Follow the next steps to install the library in your Arduino IDE:
Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The Library
Manager should open.
Search for “max6675 ” in the search box and install the library from Adafruit.

Code – Get Temperature from K-Type Thermocouple with MAX6675 Amplifier


Getting temperature from the K-Type thermocouple with the Arduino is very simple. The
library provides an example that gets temperature and displays the results on the Arduino IDE
Serial monitor.
This code is the example provided by the library.
// this example is public domain. enjoy! https://learn.adafruit.com/thermocouple/

30
#include "max6675.h"

int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

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

Practicing the water Level indicating system using Arduino

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

Why We Need Water Level Indicator?


This tutorial guides you on how to develop a water level control system. Many times we cannot
guess the water level in the water tank from outside, hence we keep the water pump ON. This
results in wastage of water. By using this project we can control the water level in the tank.
Also, we can analyze the water level in the tank by the indication with simple LEDs. This helps
us to do the water management on our own. By using this tutorial we are not only controlling
the water level but also monitoring it. So let's get started.
Water Level Sensor

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

// Value for storing water level


int val = 0;

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);

// Set LED pins as an OUTPUT


pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);

// Initially turn off all LEDs


digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, 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);
}

//This is a function used to get the reading


int readSensor() {
digitalWrite(sensorPower, HIGH);
delay(10);
val = analogRead(sensorPin);
digitalWrite(sensorPower, LOW);
return val;
}

39
40
Lab # 08

Practicing the interfacing keypad with Arduino and controlling


electric door lock

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.

Arduino Keypad Lock Code


The initial password is 1234.
#include <Keypad.h>

#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;

int relay_pin = 10;

char key_pressed=0;

const byte rows = 4;

const byte columns = 4;

char hexaKeys[rows][columns] = {

{'1','2','3','A'},

{'4','5','6','B'},

{'7','8','9','C'},

{'*','0','#','D'}

};

byte row_pins[rows] = {A0,A1,A2,A3};

byte column_pins[columns] = {A4,A5,3,2};

Keypad keypad_key = Keypad( makeKeymap(hexaKeys), row_pins, column_pins, rows,


columns);

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);

liquid_crystal_display.print("Electronic Lock ");

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);

if((strncmp(new_password, initial_password, 4)))

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

You might also like