Line Follower

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

MT-359L – Microcontroller & Embedded Systems Lab

Line Following Robot

MICROCONTROLLER AND EMBEDDED SYSTEM

Submitted by: -

SADIA SAEED (180842)

BEMTS – (2018-2022)

Submitted to:

Engr. Zargham Raza

(Lab Instructor)

DEPARTMENT OF MECHATRONICS ENGINEERING,

FACULTY OF ENGINEERING

Page 1 of 37
RAHBER Line Following Robot

AIR UNIVERSITY, ISLAMABAD

Chapter 1

INTRODUCTION
A line follower robot is basically a robot designed to follow a line or path already pre-
determined by the user. This line or path may be as simple as a physical white line on the floor
or as complex path marking schemes e.g. embedded lines, magnetic markers and laser guide
markers. In order to detect these specific markers or ‘lines’, various sensing schemes can be
employed. These schemes may vary from simple low cost line sensing circuit to expansive
vision systems. The choice of these schemes would be dependent upon the sensing accuracy
and flexibility required. From the industrial point of view, line following robot has been
implemented in semi to fully autonomous plants. In this environment, these robots functions as
materials carrier to deliver products from one manufacturing point to another where rail,
conveyor and gantry solutions are not possible. Apart from line following capabilities, these
robots should also have the capability to navigate junctions and decide on which junction to
turn and which junction ignore. This would require the robot to have 90 degree turn and also
junction counting capabilities. To add on to the complexity of the problem, sensor positioning
also plays a role in optimizing the robots performance for the tasks mentioned earlier.

Line-following robots with pick- and- placement capabilities are commonly used in
manufacturing plants. These move on a specified path to pick the components from specified
locations and place them on desired locations. Basically, a line-following robot is a self-
operating robot that detects and follows a line drawn on the floor. The path to be taken is
indicated by a white line on a black surface. The control system used must sense the line and
man oeuvre the robot to stay on course while constantly correcting the wrong moves using
feedback mechanism, thus forming a simple yet effective close d- loop system.

1.1 Objective of Study

The robot must be capable of following a line.

• It should be capable of taking various degrees of turns

• It must be prepared of a situation that it runs into a territory which has no line to follow.

• The robot must also be capable of following a line even if it has breaks.

• The robot must be insensitive to environmental factors such as lighting and noise.
Page 2 of 37
MT-359L – Microcontroller & Embedded Systems Lab

• It must allow calibration of the line’s darkness threshold.

• The robot must be reliable

• Scalability must be a primary concern in the design.

• The color of the line must not be a factor as long as it is darker than the Surroundings

1.2 Problem Definition

In the industry carriers are required to carry products from one manufacturing plant to another
which are usually in different buildings or separate blocks. Conventionally, c arts or trucks
were used with human drivers. Unreliability and inefficiency in this part of the assembly line
formed the weakest link. The project is to automate this sector, u sing carts to follow a line
instead of laying railway tracks which are both costly and an inconvenience

1.3 Problem Statement

Design a Line Following Robot that should have following features:

1. Should follow a black line using three IR sensors (that in Proteus simulation you can add
as push buttons rename them as sensors).
2. Climate controlled air conditioning system using temperature sensor (Use LM35
temperature sensor). Temperature should be displayed on LCD.
3. Motors speed should must be controlled using PWM (add DC motors in simulation and
rename them left and right motor as per your design also connect LED in series with
motors whose brightness will indicate the motors speed).
4. Robot should also have hurdle detection system (it should stop when a hurdle is placed in
front of it and start when the hurdle is removed but the robot should stop and start
moving again slowly not abruptly) and a message should be displayed on LCD when
hurdle gets detected (for hurdle detection sensor you can either use ADC sensor that can
be variable a resistor or use any serial communication sonar sensor that provides distance
values serially to the controller).
5. Sensors and motor driving system should be connected to one controller and LCD
displaying system on another controller (you can use any serial communication protocol
to communicate between controllers to transfer sensors data or any message to display it
on LCD)

Page 3 of 37
RAHBER Line Following Robot

1.4 Initial Feasibility

The car to be made shall be self-automated that will be able to make decisions on its own. The
robot shall be able to do this because of the integration of infrared sensors that will be placed
on top of it. The integration of the Sensors with that of the Arduino or any other
microcontroller will help the automation to make more efficient moves on the go and will be
able to perform various maneuvers.

1.5 Project Scope

The robot can be further enhanced to let the user decide whether it is a dark line on a white
background or a white line on a dark background. The robot can also be programmed to decide
what kind of line it is, instead of a user interface. The motor control could be modified to steer
a convectional vehicle, and not require a differential steering system. The robot could be
modified to be a four wheel drive. Extra sensors could be attached to allow the robot to detect
obstacles, and if possible bypass it and get back to the line. In other words, it must be capable
predicting the line beyond the obstacle. S peed control could also be incorporated. Position and
distance sensing devices could also be built in which can transmit information to a mother
station, which would be use full in tracking a lost carrier.

1.6 Basic Block Diagram


Power
supply

Sensor Crystal
array ATmega328P

MICRO-
CONTRLLER Reset
circuit

H-bridge

Left Right
motor motor

Page 4 of 37
MT-359L – Microcontroller & Embedded Systems Lab

1.7 Technical Standards

At a given straight line, the robot shall be able to cover 10km/h, given that it is provided a
constant good load of voltage as a driving power. The car would be equipped with two good
motors that is being powered by a useful LM298 motor driver, so it should provide the speed
that has been stated above. Another technical aspect that comes in is the sensitivity of the
infrared sensors. These sensors are found commonly and have a very vast range of sensitivity.
These sensors has adjusted potentiometers that can be changed in order to vary the sensitivity
and the calibration of these sensors.

1.8 List of Features and Specifications

Large line follower robots are usually used in industries for assisting the automated production
process. They are also used in military applications, human assistance purpose, delivery services
etc.

Line follower Robot is one of the first robots that beginners and students would get their first
robotic experience with. In this project, we have designed a simple Line Follower Robot using
Arduino and some other components.

The control of the robot is the most important aspect of its working. Here the term control refers
to the robot motion control, i.e. controlling the movement of the wheels.

A basic line follower robot follows certain path and the motion of the robot along this path is
controlled by controlling the rotation of wheels, which are placed on the shafts of the two
motors.

So, the basic control is achieved by controlling the motors. The control circuitry involves the
use of sensors to sense the path and the microcontroller or any other device to control the motor
operation through the motor drivers, based on the sensor output.

1.9 Basic Flowchart

Sensor
for line
detection

Page 5 of 37
RAHBER Line Following Robot

Micro- Motor Motors for


controller for driver precise
decision making L298 motion
on direction

Right Left
motor motor
1.10 Project Development Process

Page 6 of 37
MT-359L – Microcontroller & Embedded Systems Lab

Chapter 2
LITERATURE SURVEY
In recent years a great deal of time and effort has been spent of developing systems to enable
an autonomous robot to follow a marked path using a vision system. Not surprisingly, the
majority of this research has been towards modifying, or designing from scratch, a full-sized
road vehicle so that it can drive on ordinary roads without human supervision. Due to the large
amount of space available in an ordinary road vehicle, high performance computers can be
used to perform complex image processing and, typically, to maintain a mathematical model of
the vehicle and the environment.

Research into autonomous driving using smaller robots typically follows one of two
approaches. In the first approach a mathematical model of the vehicle and its surroundings is
generated, tested in simulation, and then applied to a robot built specifically for the purpose. In
the second approach a combination of a visual servoing system and a kinematic model is used,
again the robot is typically designed around the solution technique. Due to the size of these
robots, the processing resources available are quite limited so simpler models and techniques,
such as visual servoing, are used to reduce the processing load.

2.1 Autonomous Robots


Autonomous robots are independent of any controller and can act on their own. The robot is
programmed to respond in a particular way to an outside stimulus. The bump-and-go robot is a
good example. This robot uses bumper sensors to detect obstacle. When the robot is turned on,
it moves in a straight direction and when it hits an obstacle, the crash triggers its bumper
sensor. The robot gives a programming instruction that asks the robot to back up, turn to the
right direction and move forward. This is its response to every bump. In this way, the robot can
change direction every time, it encounters an obstacle.

A more elaborate version of the same idea is used by more advanced robots. Robotics create
new sensor systems and algorithms to make robots more perceptive and smarter. Today, robots
are able to effectively navigate a variety of environments. Obstacle avoidance can be

Page 7 of 37
RAHBER Line Following Robot

implemented as a reactive control law whereas path planning involves the pre-computation of
an obstacle-free path which a controller will then guide a robot along.

Some mobile robots also use various ultrasound sensors to see obstacles or infrared. These
sensors work in a similar fashion to animal echolocation. The robot sends out a beam of
infrared light or a sound signal. It then detects the reflection of the signal. The robot locates
this distance to the obstacles depending on how long it takes the signal to bounce back.

Some advanced robots also use stereo vision. Two cameras provide robots with depth
perception. Image recognition software then gives them the ability to locate, classify various
objects. Robots also use smell and sound sensors to gain knowledge about its surroundings

2.2 Working Principle


Robotics is an interesting subject to discuss about and in this advanced world Robots are
becoming a part of our life. In this project we are going to discuss about a robot which is
capable of following a line without the help of any external source.

The Embedded Line following robot uses two motors to control rear wheels and the single
front wheel is free. It has 3-infrared sensors on the bottom for detection of black t racking tape.
When the middle sensor detects the black color, this sensor output is given to the comparator
LM358. The output of comparator compares this sensor output with a reference voltage and
gives an output. The output of comparator will be low when it receives an input from the
sensor.

We follow a simple logic to implement this project. As we know that black color is capable of
absorbing the radiation and white color or a bright color reflects the radiation back. Here we
use 3 pairs of IR TX and Rx .The robot uses these IR sensors to sense the line and the
arrangement is made such that sensors face the ground. The output from the sensors is an
analog signal which depends on the amount of light reflected back and this analog signal is
given to the comparator to produce 0s and 1s.

Internally we have an OTP (one time programmable) processor which is used to control the
rotation of the wheels. The rotation of these wheels depends up on the response from the
comparator. Let us assume that when a sensor is on the black line it reads 0 and when it is on
the bright surface it reads 1.

Here we can get three different cases, they are:

1. Straight direction

Page 8 of 37
MT-359L – Microcontroller & Embedded Systems Lab

2. Right curve

3. Left curve

2.2.1 Straight direction

We can expect our robot to move in straight direction when the middle sensors response is low
and the remaining two sensors response is high. i.e., according to our arrangement the middle
sensor will always be on the line and as the line is black in color it will not reflect the emitted
radiation back and the response of the sensor will be low and the response of the remaining
two sensors will be high as they will be on the bright surface.

2.2.2 Right curve:

When a right curve is found on the line the responses will change i.e. the response of the first
sensor which is to the right will become low as that sensor will be facing the b lack line and
the reaming sensors response will be high. We this data is achieved the control of the wheels is
changed i.e. the right wheel is held and the left wheel is made to move freely until the response
from the middle sensor becomes low. Then the same process repeats again.

2.2.3 Left curve

When a left curve is found on the line the response of the left most sensor will be changed
from high to low as the sensor will now face the black or the dark surface. Then the control of
the wheel changes i.e. by holding the left wheel and allowing the right wheel to move freely
until the middle sensor changes it is response from high to low. The same process continues
for all the turns and the robot moves continuously until the supply is remove.

2.3 Hardware Components


1. IR SENSOR

2. MICROCONTROLLERS ATMEGA 328P

3. MOTOR DRIVER IC L298

4. LCD

5. TEMPERATURE SENSOR LM35

6. SONAR SENSOR

Page 9 of 37
RAHBER Line Following Robot

Chapter 3
STEPS IN CIRCUIT DESIGNING
3.1 Circuit Diagram and Explanation

In this Line Follower Robot circuit we have used an IR sensor for detecting the line. 10 K
potentiometer is connected at its inverting terminal for adjusting reference voltage and IR
receiver’s output is directly connected at non-inverting pins of all comparators. Our sensor is
working, then signal goes to microcontroller IC which is programmed and gives the output to
the motor driver IC which rotates the motor s as per the programming of microcontroller IC.

3.1.1 Block Diagram

The first step is the block diagram which gives an overview of the interconnection among
various components. The components are microcontroller (Atmega328), IR Sensors and Motor
Driver IC (L293).

Page 10 of 37
MT-359L – Microcontroller & Embedded Systems Lab

3.1.2 Proteus circuit

3.1.3 Software Tools

The software used for coding is ATMEL STUDIO and the language used for coding is
“embedded c”.

The program code acts as the decision-maker embedded in the microcontroller i.e. it decides
what will be the outputs for particular set of input combination. Programs for the AVR series
of microcontrollers can be written in assembly C and AVR Studio etc. We are using ATMEL
STUDIO 7 for programming and AVR Studio for simulating (Simulation means debugging the
code on software, one can virtually give the input and check the output for that code).

In ATMEL STUDIO 7 programmers Notepad we write our C code, after compilation it


generates ‘.hex’ file that is a hardware level code.

The hex file is than loaded in the micro-controller so that it can perform a desired function.

Page 11 of 37
RAHBER Line Following Robot

The screen shots of ATMEL studio is given below

Page 12 of 37
MT-359L – Microcontroller & Embedded Systems Lab

Page 13 of 37
RAHBER Line Following Robot

Page 14 of 37
MT-359L – Microcontroller & Embedded Systems Lab

Page 15 of 37
RAHBER Line Following Robot

Page 16 of 37
MT-359L – Microcontroller & Embedded Systems Lab

Chapter 4
SERIAL PERIPHERAL INTERFACE (SPI)

4.1 Introduction
SPI is a common communication protocol used by many different devices. For example, SD
card modules, RFID card reader modules, and 2.4 GHz wireless transmitter/receivers all use SPI
to communicate with microcontrollers

In serial communication, the bits are sent one by one through a single wire. The following
diagram shows the serial transmission of the letter “C” in binary (01000011):

One unique benefit of SPI is the fact that data can be transferred without interruption. Any
number of bits can be sent or received in a continuous stream. With I2C and UART, data is sent
in packets, limited to a specific number of bits. Start and stop conditions define the beginning
and end of each packet, so the data is interrupted during transmission.

Devices communicating via SPI are in a master-slave relationship. The master is the controlling
device (usually a microcontroller), while the slave (usually a sensor, display, or memory chip)
takes instruction from the master. The simplest configuration of SPI is a single master, single
slave system, but one master can control more than one slave

Page 17 of 37
RAHBER Line Following Robot

4.1.1 Pin Description:

The SPI typically uses 4 pins for communication, wiz. MISO, MOSI, SCK, and SS.
These pins are directly related to the SPI bus interface.

 MOSI (Master Output/Slave Input) – Line for the master to send data to the slave.

 MISO (Master Input/Slave Output) – Line for the slave to send data to the master.

 SCLK (Clock) – Line for the clock signal.


 SS/CS (Slave Select/Chip Select) – Line for the master to select which slave to send
data to.

THE SPI OF THE AVR

The SPI of AVRs is one of the simplest peripherals to program. As the AVR has an 8-bit
architecture, so the SPI of AVR is also 8-bit. In fact, usually the SPI bus is of 8-bit width. It is
available on PORTB on all of the ICs, whether 28 pin or 40 pin.

Some of the images used in this tutorial are taken from the AVR datasheets.

Page 18 of 37
MT-359L – Microcontroller & Embedded Systems Lab

4.2 HOW SPI WORKS


4.2.1 THE CLOCK

The clock signal synchronizes the output of data bits from the master to the sampling of bits by
the slave. One bit of data is transferred in each clock cycle, so the speed of data transfer is
determined by the frequency of the clock signal. SPI communication is always initiated by the
master since the master configures and generates the clock signal.

The clock signal in SPI can be modified using the properties of clock polarity and clock phase.
These two properties work together to define when the bits are output and when they are
sampled. Clock polarity can be set by the master to allow for bits to be output and sampled on
either the rising or falling edge of the clock cycle. Clock phase can be set for output and
sampling to occur on either the first edge or second edge of the clock cycle, regardless of
whether it is rising or falling

4.2.2 SLAVE SELECT

The master can choose which slave it wants to talk to by setting the slave’s CS/SS line to a low
voltage level. In the idle, non-transmitting state, the slave select line is kept at a high voltage
level. Multiple CS/SS pins may be available on the master, which allows for multiple slaves to
be wired in parallel. If only one CS/SS pin is present, multiple slaves can be wired to the master
by daisy-chaining.

4.2.3 MULTIPLE SLAVES

SPI can be set up to operate with a single master and a single slave, and it can be set up with
multiple slaves controlled by a single master. If the master has multiple slave select pins, the
slaves can be wired in parallel like this:

Page 19 of 37
RAHBER Line Following Robot

4.2.4 MOSI AND MISO

The master sends data to the slave bit by bit, in serial through the MOSI line. The slave receives
the data sent from the master at the MOSI pin. Data sent from the master to the slave is usually
sent with the most significant bit first.

The slave can also send data back to the master through the MISO line in serial. The data sent
from the slave back to the master is usually sent with the least significant bit first.

4.3 STEPS OF SPI DATA TRANSMISSION


1. The master outputs the clock signal:

2. The master switches the SS/CS pin to a low voltage state, which activates the slave:

3. The master sends the data one bit at a time to the slave along the MOSI line. The slave reads
the bits as they are received:

4. If a response is needed, the slave returns data one bit at a time to the master along the MISO
line. The master reads the bits as they are received:

Page 20 of 37
MT-359L – Microcontroller & Embedded Systems Lab

4.4 ADVANTAGES AND DISADVANTAGES OF SPI


There are some advantages and disadvantages to using SPI, and if given the choice between
different communication protocols, you should know when to use SPI according to the
requirements of your project:

4.4.1 ADVANTAGES

 No start and stop bits, so the data can be streamed continuously without interruption

 No complicated slave addressing system like I2C

 Higher data transfer rate than I2C (almost twice as fast)

 Separate MISO and MOSI lines, so data can be sent and received at the same time

4.4.2 DISADVANTAGES

 Uses four wires (I2C and UARTs use two)

 No acknowledgement that the data has been successfully received (I2C has this)

 No form of error checking like the parity bit in UART

 Only allows for a single master

4.5 REGISTER DESCRIPTIONS


The AVR contains the following three registers that deal with SPI:

1. SPCR – SPI Control Register – This register is basically the master register i.e. it
contains the bits to initialize SPI and control it.

2. SPSR – SPI Status Register – This is the status register. This register is used to read the
status of the bus lines.

3. SPDR – SPI Data Register – The SPI Data Register is the read/write register where the
actual data transfer takes place.

4.5.1 The SPI Control Register (SPCR)

As is obvious from the name, this register controls the SPI. We will find the bits that enable SPI,
set up clock speed, configure master/slave, etc. Following are the bits in the SPCR Register.

Page 21 of 37
RAHBER Line Following Robot

Bit 7: SPIE – SPI Interrupt Enable

The SPI Interrupt Enable bit is used to enable interrupts in the SPI. Note that global interrupts
must be enabled to use the interrupt functions. Set this bit to ‘1’ to enable interrupts.

Bit 6: SPE – SPI Enable

The SPI Enable bit is used to enable SPI as a whole. When this bit is set to 1, the SPI is enabled
or else it is disabled. When SPI is enabled, the normal I/O functions of the pins are overridden.

Bit 5: DORD – Data Order

DORD stands for Data Order. Set this bit to 1 if you want to transmit LSB first, else set it to 0,
in which case it sends out MSB first.

Bit 4: MSTR – Master/Slave Select

This bit is used to configure the device as Master or as Slave. When this bit is set to

1, the SPI is in Master mode (i.e. clock will be generated by the particular device), else when it
is set to 0, the device is in SPI Slave mode.

Bit 3: CPOL – Clock Polarity

This bit selects the clock polarity when the bus is idle. Set this bit to 1 to ensure that SCK is
HIGH when the bus is idle, otherwise set it to 0 so that SCK is LOW in case of idle bus. This
means that when CPOL = 0, then the leading edge of SCK is the rising edge of the clock. When
CPOL = 1, then the leading edge of SCK will actually be the falling edge of the clock.

Bit 2: CPHA – Clock Phase

This bit determines when the data needs to be sampled. Set this bit to 1 to sample data at the
leading (first) edge of SCK, otherwise set it to 0 to sample data at the trailing (second) edge of
SCK.

Page 22 of 37
MT-359L – Microcontroller & Embedded Systems Lab

Bit 1, 0: SPR1, SPR0 – SPI Clock Rate Select

These bits, along with the SPI2X bit in the SPSR register (discussed next), are used to choose
the oscillator frequency divider, wherein the f OSC stands for internal clock, or the frequency of
the crystal in case of an external oscillator. The table below gives a detailed description.

4.5.2 THE SPI STATUS REGISTER (SPSR)

The SPI Status Register is the register from where we can get the status of the SPI bus and
interrupt flag is also set in this register. Following are the bits in the SPSR register.

4.5.3 The SPI Data Register (SPDR)

The SPI Data register is an 8-bit read/write register. This is the register from where we read the
incoming data, and write the data to which we want to transmit.

Page 23 of 37
RAHBER Line Following Robot

4.6 DATA MODES


The SPI offers 4 data modes for data communication, wiz SPI Mode 0,1,2 and 3, the only
difference in these modes being the clock edge at which data is sampled. This is based upon the
selection of CPOL and CPHA bits.

Chapter 5
INTRODUCTION TO ADC IN AVR

5.1 Introduction

Page 24 of 37
MT-359L – Microcontroller & Embedded Systems Lab

An ADC, or Analog to Digital Converter, allows one to convert an analog voltage to a digital
value that can be used by a microcontroller. There are many sources of analog signals that one
might like to measure. There are analog sensors available that measure temperature, light
intensity, distance, position, and force, just to name a few.

5.2 Working ADC in AVR- Microcontroller


The AVR ADC allows the AVR microcontroller to convert analog voltages to digital values
with few to no external parts. The ATmega8 features a 10-bit successive approximation
ADC.ATmega8 has 7 channel ADC at Port C. The ADC has a separate analog supply voltage
pin, AVCC. AVCC must not differ more than ± 0.3V from VCC. The voltage reference may be
externally decoupled at the AREF pin. AVCC is used as the voltage reference. The ADC can
also be set to run continuously (the free-running mode) or to do only one conversion.

Page 25 of 37
RAHBER Line Following Robot

5.3 ADC Conversion Formula

Where Vin is the voltage on the selected input pin and Vref the selected voltage reference

5.4 How to Configure ADC in ATmega328P

Page 26 of 37
MT-359L – Microcontroller & Embedded Systems Lab

5.5 ADLAR Selection

ADC Left Adjust Result

The ADLAR bit affects the presentation of the ADC conversion result in the ADC Data
Register. Write one to ADLAR to left adjust the result. Otherwise, the result is right adjusted

When an ADC conversion is complete, the result is found in ADCH and ADCL When ADCL is
read, the ADC Data Register is not updated until ADCH is read. Consequently, if the result is
left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH.
Otherwise, ADCL must be read first, then ADCH. Analog Channel Selection Bits The value of
these bits selects which analog inputs are connected to the ADC.

Page 27 of 37
RAHBER Line Following Robot

Chapter 6

Page 28 of 37
MT-359L – Microcontroller & Embedded Systems Lab

FLOWCHARTS

Page 29 of 37
RAHBER Line Following Robot

Page 30 of 37
MT-359L – Microcontroller & Embedded Systems Lab

Basic Calculations
Temperature Calculations:

Temperature calculated by the formula

((ADC) Temp/2.1) +1

Distance Calculations:

(ADC) distance /2.1

Motor Speed:

Motor speed is calculated by

( duty-cycle /255)+5V

For 55 duty-cycle:

Motor Speed= 1.078Vm

For 155 duty-cycle:

Motor Speed= 3.039Vm

For 255: duty-cycle

Motor speed= 5V

REFERENCES:
https://drive.google.com/file/d/1b_q2PbWxYwsvz6PF8eP5dOLWwFPzPW5N/view
https://www.instructables.com/Introduction-to-ADC-in-AVR-Microcontroller
https://www.circuitbasics.com/basics-of-the-spi-communication-protocol/

Page 31 of 37
RAHBER Line Following Robot

SOURCE CODE:
Master code
#define F_CPU 16000000 //Speed of the microprocessor (16 MHz)
#include <avr/io.h> // provides PORT* and DDR* registers
#include <util/delay.h> //INCLUDING AVR DELAY LIBRARY _delay_ms(),F_CPU
#include <avr/interrupt.h> //INCLUDING AVR INTERUPTS LIBRARY
#include <stdlib.h> //INCLUDING AVR STANDARED LIBRARY

//SPI FUNCTIONS
void Ini_as_MSTR(); //Initializing as master
void Send_data(char u); //Sending data to Slave
void Send_String(char *p); //sending a string

#define MOSI 3 //The Master line for sending data to the peripherals
#define MISO 5 //The Slave line for sending data to the master
#define SS 2 //Master can use this pin to enable and disable devices

//PWM FUNCTIONS
void Ini_PWM_Timer_0();
void Ini_PWM_Timer_1();
int set_duty_cycle(int speed);
void Motor_1(int duty_cycle);
void Motor_2(int duty_cycle);

//ADC FUNCTIONS
void ADC_Init();
void ADC_Control();
int v;
int get_temperature ();

int duty_cycle = 50;


//MAKING GLOBAL VARIABLE DUTYCYCLE = 50
int speed = 2; //MAKING GLOBAL VARIABLE speed = 2

//IR SENSORS
#define right_sensor 0
#define middle_sensor 6
#define left_sensor 7

//DISTANCE SENSOR
char value [16];
int distance =0;
void intialize_INT0();
void read_distance();

void Ini_as_MSTR() //Initializing as master


{
DDRB = (1<<MOSI)|(1<<MISO)|(1<<SS); // SCK, MOSI and SS as outputs
SPCR |= (1<<MSTR); // Set as Master
SPCR |= (1<<SPR0)|(1<<SPR1); // divided clock by 128
SPCR |= (1<<SPE); // Enable SPI
}

Page 32 of 37
MT-359L – Microcontroller & Embedded Systems Lab

void Send_data(char u) //Sending data to Slave


{
PORTB &= ~(1<<SS); // drive SS low
SPDR = u; // send the data
while (!(SPSR & (1<<SPIF))); // wait until transmission is complete
//PORTD = SPDR; // all data has been send to slave
PORTB |= (1<<SS); // drive SS high
}

void Send_String(char *p)


{char c='c';
while(*p!='\0')
{
Send_data(*p);
p++;
}
Send_data(c)}

int set_duty_cycle(int speed){

if(speed == 0){ //Speed 0 at 0% of PWM


duty_cycle = 0;
}
if(speed == 1){ //Speed 1 at 21% of PWM
duty_cycle= 20;
}
if(speed == 2){ //Speed 2 at 60% of PWM
duty_cycle = 50;
}
if(speed == 3){ //Speed 3 at 100% of PWM
duty_cycle = 100;
}
return duty_cycle; }
//PWM FUNCTIONS DEFINITION
void Motor_1(int speed)
{
set_duty_cycle(2);
OCR0A = (duty_cycle/100.0)*255.0;
//SETTING VALUE IN OUTPUT COMPARE REGISTER FOR DESIRED DUTYCYCLE
}
void Motor_2(int speed)
{
set_duty_cycle(2);
OCR1A = (duty_cycle/100.0)*255.0;
//SETTING VALUE IN OUTPUT COMPARE REGISTER FOR DESIRED DUTYCYCLE
}
// LINE FOLLOWER MOVEMENT FUNTION DEFINITION
void forward()
{
Motor_1(speed);
Motor_2(speed);
}
void left()
{
Page 33 of 37
RAHBER Line Following Robot

Motor_1(speed);
Motor_2(0);}
void right()
{
Motor_1(0);
Motor_2(speed);}
void stop()
{
Motor_1(0);
Motor_2(0);}
//DISTANCE FUNTION DEFINITIONS
void intialize_INT0()
{EICRA |= (1<<ISC00)|(0<<ISC01); //interrupt occur at any logic change
EIMSK |= (1<<INT0); //enabling int0 external
interrupt
}
// ADC FUNCTIONS DEFINITIONS
void ADC_Init(void)
{ADMUX = (1 << REFS0) | (1 << MUX0) | (1 << MUX2); } //CHANNEL SELECT ADC5,
AVCC WITH EXTERNAL CAPACITOR AT AREF PIN

void ADC_Control(void)
{ADCSRA = (1 << ADEN) | (1 << ADIE) | (1 << ADPS0) | (1 << ADPS1) | (1 <<
ADPS2); } //ENABLE ADC, ADC CONVERSION INTERRUPT ACTIVATED, CLK 128

//PWM INITIALIZATION TIMER FUNCTIONS DEFINITION


void Ini_PWM_Timer_0()
{TCCR0A = (1 << COM0A1) | (1 << WGM00) | (1 << WGM01); //COM0A1
reacts the timer as it reach the compare value
//SETTING BITS HIGH IN TCCR0A REGISTER FOR FAST PWM MODE
TCCR0B = (1 << CS00);
//SETTING NO PRESCALER MODE }
void Ini_PWM_Timer_1()
{TCCR1A = (1 << COM0A1) | (1 << WGM00) | (1 << WGM01); //COM0A1
reacts the timer as it reach the compare value
//SETTING BITS HIGH IN TCCR1A REGISTER FOR FAST PWM MODE
TCCR1B = (1 << CS00);
//SETTING NO PRESCALER MODE}

int main()
{Ini_as_MSTR();
//for DISTANCE
intialize_INT0();
DDRD= (0<<2)|(1<<6); //Making PD2 I/P for
distance , PD6 O/P ENA0 PWM_0A
DDRB = (0<<0)|(1<<1)|(1<<6)|(1<<7); //PB0,PB6,PB7 for
IR sensor I/P , PB1 for ENA1 PWM_1A
DDRC= (1<<0)|(1<<1)|(1<<2)|(1<<3)|(0<<5); //pins for IN1 ,
IN2, IN3 , IN4 and taking input from temp sensor
int v;
char value[10];

Ini_PWM_Timer_0();
Ini_PWM_Timer_1();
while(1)
Page 34 of 37
MT-359L – Microcontroller & Embedded Systems Lab

{read_distance();
PORTC |= 0X05; // IN1, IN2 , IN3 , IN4 pins setting

//temperature sensor code


get_temperature ();

if ((PINB & (1 << PINB0)))

{PINB = 0x00;
right();
PIND = 0x00; }
if ((PINB & (1 << PINB6)))

{PINB=0x00;
left();
PIND = 0x00; }
else
{ forward(); }}}
void read_distance()
{ int dis;
ADC_Init();
ADC_Control();
ADCSRA |= (1 << ADSC); //START CONVERSION
while((ADCSRA & (1 << ADIF)) == 0); //WAIT FOR THE COMPLETE CONVERSION
ADCSRA |= (1 << ADIF); //CLEAR THE ADIF FLAG
dis=ADC/2.1;
itoa(dis,value,10);
Send_String("Distance:");
Send_String(value);
_delay_us(200);
Send_data('0');
if(dis< 20){
Send_String("Obstacle Ahead!");
_delay_ms(500);
Send_data('0');
stop();}}

int get_temperature ()
{int Temp;
//ADC initialization
ADC_Init();
ADC_Control();
ADCSRA |= (1 << ADSC); //START CONVERSION
while((ADCSRA & (1 << ADIF)) == 0);//WAIT FOR THE COMPLETE CONVERSION
DIDR0 = (1 << ADC5D); //select the ADC pin
ADCSRA |= (1 << ADIF); //CLEAR THE ADIF FLAG
Temp=ADC/2.1;
itoa(Temp,value,10);
Send_data(value);
Send_String("Temperature :");
Send_String(value);
_delay_ms(200);
Send_data('0');
itoa(v,value,10);}
Page 35 of 37
RAHBER Line Following Robot

SLAVE CODE
* LINE FOLLOWER 842 SLAVE.c
*
* Created: 05-Jan-21 12:06:57 AM
* Author : SADIA - SAEED
*/
#include <avr/io.h>
#define F_CPU 1000000UL
#include <util/delay.h>
#include "MYLCD.h"
#define MISO 4

int main(void)

{
LCD_Init();
DDRC=0XFF;
DDRD=0XFF;

DDRB &= ~((1<<2)|(1<<3)|(1<<5)); // SCK, MOSI and SS as


inputs
DDRB |= (1<<4); // MISO as output

SPCR &= ~(1<<MSTR); // Set as slave


SPCR |= (1<<SPR0)|(1<<SPR1); // divide clock by 128
SPCR |= (1<<SPE); // Enable SPI , SPCR is
the SPI Control register

int s=1;
int a=1;
LCD_Data_string("distance:");
while (1)
{
if(s==11)
{ LCD_Cmd(0x01);
LCD_Data_string("TEMPERATURE:");
s=0;
}
if(a==8)
{ LCD_Cmd(0x01);
LCD_Data_string("distance:");
a=0;
}
while(!(SPSR &(1<<SPIF)));
LCD_Data(SPDR);
s++;
a++;

}}

Page 36 of 37
MT-359L – Microcontroller & Embedded Systems Lab

LCD HEADER FILE


#include <util/delay.h>
#define Lcd_Data PORTD
#define Lcd_control PORTC
////////////Defining Control Pins///////////////
#define RS PC0 // defining enable pin
#define RW PC1 // defining Read/Write pin
#define EN PC2 // defining register select pinvoid
LCD_Cmd(unsigned char cmd);
void LCD_Init(void);
void LCD_Data(unsigned char data);
void LCD_Cmd(unsigned char cmd);
////////////////////////////////////////////////////////////////////////////////////
/////////
void LCD_Init(void)
{
LCD_Cmd(0x38); //initialization of 16X2 LCD in 8bit mode
_delay_ms(1);
LCD_Cmd(0x01); //clear LCD
_delay_ms(1);
LCD_Cmd(0x0E); //cursor ON
_delay_ms(1);
LCD_Cmd(0x80); // ---8 go to first line and --0 is for 0th position
_delay_ms(1);
}
void LCD_Cmd(unsigned char cmd)
{

Lcd_control =(0<<RS)|(0<<RW)|(1<<EN); // making RS and RW as LOW and EN as


HIGH
Lcd_Data=cmd;
_delay_ms(1);
Lcd_control =(0<<RS)|(0<<RW)|(0<<EN); // making RS, RW , LOW and EN as LOW
_delay_ms(1);
}
void LCD_Data(unsigned char data)
{

Lcd_control = (1<<RS)|(0<<RW)|(1<<EN); // making RW as LOW and RS, EN


as HIGH
Lcd_Data= data;
_delay_ms(5);
Lcd_control = (1<<RS)|(0<<RW)|(0<<EN); // making EN and RW as LOW and
RS HIGH
_delay_ms(5); // give a delay to
get things executed
}
void LCD_Data_string(char *str) //take address vaue of the string in pionter
*str
{
int i=0;
while(str[i]!='\0') // loop will go on
till the NULL characters is soon in string
{
LCD_Data(str[i]); // sending data on
CD byte by byte
i++;
}
}
Page 37 of 37

You might also like