0% found this document useful (0 votes)
4 views

Edited Project 2nd April

This thesis focuses on the design and control of a DC motor using an Arduino Nano microcontroller, aimed at achieving precise speed control through techniques like Pulse Width Modulation (PWM) and Proportional-Integral-Derivative (PID) control. The project addresses the challenges of controlling DC motors in various applications, emphasizing the integration of feedback systems for real-time adjustments. It includes a comprehensive literature review, methodology, and results demonstrating the effectiveness of the proposed control strategies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Edited Project 2nd April

This thesis focuses on the design and control of a DC motor using an Arduino Nano microcontroller, aimed at achieving precise speed control through techniques like Pulse Width Modulation (PWM) and Proportional-Integral-Derivative (PID) control. The project addresses the challenges of controlling DC motors in various applications, emphasizing the integration of feedback systems for real-time adjustments. It includes a comprehensive literature review, methodology, and results demonstrating the effectiveness of the proposed control strategies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

UNIVERSITY OF JUBA

SCHOOL OF ENGINEERING AND ARCHITECTURE

DEPARTMENT OF ELECTRICAL ENGINEERING

DESIGN AND CONTROL OF DC MOTOR USING ARDUINO


NANO MICROCONTROLLER

THIS THESIS IS SUBMITTED IN PARTIAL FULFILLMENT


OF THE REQUIREMENT FOR THE AWARD OF BACHELOR
OF SCIENCE (BSC) HONOURS DEGREE IN ELECTRICAL
ENGINEERING

BY

AKOL AROL AKOL 17 – CEN – 022

GATBANY POUCH BIEL 18 - CEN – 059

SUPERVISED BY: DR. MARTINO OJWOK AJANGNAY

APRIL 2025
DECLARATION

We, the undersigned students declare that, this thesis is our original work and has not been
submitted elsewhere for consideration for the award of any degree. The information and
materials used from other sources are cited as they appear in the text.

By:

Signature Date

Akol Arol Akol ____________________ ________________

Gatbany Pouch Biel ____________________ ________________

Supervisor

Signature Date

Dr. Martino Ojwok ___________________ ___________________


DEDICATION

This project is dedicated to our parents who have never failed to give us financial and moral
support, during the time we developed our system and for teaching us that even the biggest task
can be accomplished if it is done one step as a time.

We dedicate this project to all the people who have worked hard to help us complete this project.

ii
ACKNOWLEDGEMENTS

To begin, we’d like to thank Dr. Martino Ojwok, our primary supervisor, for his tireless
guidance and support. His intellectual guidance and constructive critique put us on check during
the whole exercise. We are glad to have had an encounter with him as our supervisor and a
mentor for our project. His critical comments and genuine concerns were great in making this
project a success.

We also would like to appreciate all our lecturers for their time, effort and understanding in
helping us succeed in our studies. Their vast wisdom and wealth of experience have inspired us
throughout our studies. In addition, we’d like to express our gratitude to everyone in the
University of Juba. Thanks to their generosity and encouragement, our time spent studying there
has been truly rewarding. To conclude, we’d like to thanks God, our parents, our colleagues and
our friends. It would have been impossible to finish our studies without their unwavering support
over the past few years.
ABSTRACT

The precise control of DC motor speed is essential in various industrial and automation
systems. This project presents a comprehensive approach to designing and controlling the
speed of DC motor using an Arduino Nano microcontroller. The system integrates multiple
control techniques, including Pulse Width Modulation for speed regulation and Proportional-
Integral-Derivative control for enhanced accuracy and stability. A potentiometer is used as an
analog input to set the desired speed or position, while the Arduino Nano processes the input
and generates a PWM signal to drive the motor. The PID control algorithm is implemented to
minimize errors and improve dynamic response by continuously adjusting the PWM output
based on feedback from the motor's actual speed. The motor driver circuit, L298N, interfaces
the microcontroller with the DC motor, ensuring proper voltage and current levels. This
model demonstrates the effectiveness of combining PWM and PID methods for precise motor
control, offering a cost-effective and scalable solution for applications in robotics,
automation, and embedded systems.

Keywords: DC motor, Arduino Nano, PWM, PID control, potentiometer and motor driver.

iv
LIST OF ABBREVIATIONS AND ACRONYMS

DC Direct Current

PWM Pulse Width Modulation

PID: Proportional, Integral, Derivative

RPM Revolutions per minute

Kp Proportional Gain

Ki Integral Gain

Kd Derivative Gain

GSM Global System for Mobile Communication

EMF Electromotive Force

LED Light Emitting Diode

EVs Electric Vehicles

TTL Transistor -Transistor Logic

SPI Serial Peripheral Interface

CNC Computer Numerical Control

PCB Printed Circuit Board

USB Universal Serial Bus

r(t): is the desired set point

e(t): Error
TABLE OF CONTENTS
DECLARATION........................................................................................................................

DEDICATION...........................................................................................................................

ACKNOWLEDGEMENTS....................................................................................................

ABSTRACT..............................................................................................................................

LIST OF ABBREVIATIONS AND ACRONYMS.................................................................

LISTS OF FIGURES................................................................................................................

LIST OF TABLES....................................................................................................................

CHAPTER ONE.......................................................................................................................

INTRODUCTION.....................................................................................................................

1.1 Introduction....................................................................................................................

1.2 Problem Statement..............................................................................................................

1.3 Objectives.............................................................................................................................

1.3.1 Specific Objective.............................................................................................................

1.3.2 General Objectives...........................................................................................................

CHAPTER TWO......................................................................................................................

LITERATURE REVIEW.........................................................................................................

2.1 Speed Control Techniques..................................................................................................

2.1.1 Open-Loop Control..........................................................................................................

2.1.2 Closed-Loop Control........................................................................................................

2.1.3 Sensorless Control............................................................................................................

2.2: Arduino Integrated Environment.....................................................................................

2.3 Mathematical Model of Dc Motor.....................................................................................

2.3.1 Physical setup...................................................................................................................

2.3.2 Electrical System..............................................................................................................

2.3.3 Mechanical System...........................................................................................................

2.3.4 Transfer Function.............................................................................................................

vi
CHAPTER THREE..................................................................................................................

MATERIALS.............................................................................................................................

3.0 Introduction.........................................................................................................................

3.1 DC Motor.............................................................................................................................

3.1.1 Types of DC motors..........................................................................................................

3.1.1.2 Permanent magnet motors...........................................................................................

3.1.1.3 Series motors.................................................................................................................

3.1.1.4 Shunt motors.................................................................................................................

3.1.1.5 Compound motors.........................................................................................................

3.1.2 Application of DC motors..............................................................................................

3.1.3 Advantages of DC Motors.............................................................................................

3.1.4 Disadvantages of DC Motors:.......................................................................................

3.2 Arduino Nano.....................................................................................................................

3.2.1 Arduino nano pinout......................................................................................................

3.3. Arduino IDE.....................................................................................................................

3.4 L298N Motor driver Module............................................................................................

3.4.1 L298N Module Pinout Confguraiton............................................................................

3.5 Motor Encoder...................................................................................................................

3.5.1 Servo Motor Encoders...................................................................................................

3.5.2 Stepper Motor Encoders................................................................................................

3.6 Microcontroller..................................................................................................................

3.6.1 Microcontroller board...................................................................................................

3.7 Sensors................................................................................................................................

3.7.1 Hall effect sensor:...........................................................................................................

3.7.2 Current sensors..............................................................................................................

3.7.3 Temperature sensors......................................................................................................

3.8 Mini USB-cable.................................................................................................................


3.9 Breadboard........................................................................................................................

3.10 Jumper Wires..................................................................................................................

3.11 The process of developing with Arduino.......................................................................

3.11.1 Software application with Arduino.............................................................................

3.11.2 Serial Monitor...............................................................................................................

3.12 Methods of controlling the speed of a DC motor.........................................................

3.12.1 Use of a Potentiometer.................................................................................................

3.12.2 Pulse Width Modulation (PWM)................................................................................

3.12.2.1 Theory of Operation.................................................................................................

3.12.2.2 Terms used in PWM Theory....................................................................................

3.12.3 Proportional Integral Derivative (PID)......................................................................

CHAPTER FOUR...................................................................................................................

RESULTS AND DISCUSSION..............................................................................................

4.1 Introduction.......................................................................................................................

4.2 Hardware needed and their roles....................................................................................

4.2.1 Arduino Nano.................................................................................................................

4.2.2. DC Motor with encoder................................................................................................

4.2.3. L298N Motor Driver.....................................................................................................

4.2.4 Potentiometer.................................................................................................................

4.2.5. Power Supply.................................................................................................................

4.2.6. Breadboard and connecting wires...............................................................................

4.3 Setup...................................................................................................................................

4.3.1 Controlling the speed of DC motor using Potentiometer...........................................

4.3.1.1 Uploading the Code:...................................................................................................

4.3.2 Controlling the speed of dc motor using Pulse Width Modulation...........................

4.3.2.1 Programming the code on Arduino Nano.................................................................

4.3.3 Controlling the speed of DC Motor using Proportional Integral Derivative............

viii
4.3.3.1 Designing the code on the Arduino IDE....................................................................

4.4 Results...........................................................................................................................

4.4.1 Open Loop Control........................................................................................................

4.4.2 Closed Loop Control......................................................................................................

4.4.3 Discussion........................................................................................................................

4.5 Challenges Faced...............................................................................................................

CHAPTER FIVE.....................................................................................................................

CONCLUSION AND RECOMMENDATIONS...................................................................

5.1 Conclusion..........................................................................................................................

5.2 Recommendations.............................................................................................................

Appendices...............................................................................................................................
LISTS OF FIGURES

Figure 3.1: DC motor......................................................................................................................8


Figure 3.2: Showing Arduino nano...............................................................................................12
Figure 3.3: Motor Driver...............................................................................................................13
Figure 3.4: Servo motor encoder...................................................................................................15
Figure 3.5: Stepper Motor Encoders..........................................................................................15
Figure 3.6: Arduino Sketch Software outlook..............................................................................18
Figure 3.7: Potentiometer..............................................................................................................19
Figure 3.8: Pulse Width modulation.............................................................................................21
Figure 3.9: PID block diagram......................................................................................................23
Figure 3.10: Closed Loop System with PID Controller................................................................24
Figure 3.11: Schematic diagram of the wiring..............................................................................25
Figure 4.1: Components Required to Build a PID Enabled Encoder Motor Controller...............27
Figure 4.2: DC motor control result before entering PID values.................................................36
Figure 4.3: DC motor speed control after inputting the PID values..............................................36

x
LIST OF TABLES

Table 3.1: showing the L298N Module Pinout Confguraiton.......................................................14


Chapter One: Introduction

CHAPTER ONE

INTRODUCTION

1.1Introduction

Control is one of the most fundamental factors that enables us to use devices to their
maximum potential and with the highest accuracy, where we can achieve high efficiency,
total control of the dc motor, and improved precision. This project will therefore focus on
designing and controlling of speed of DC motors using Arduino Microcontroller.

DC motors were the first form of motors widely used, as they could be powered from existing
direct-current lighting power distribution systems. A DC motor's speed can be controlled over
a wide range, using either a variable supply voltage or by changing the strength of current in
its field windings. Small DC motors are used in tools, toys, and appliances. The Universal
motor can operate on direct current but is a lightweight brushed motor used for portable
power tools and appliances. Larger DC motors are currently used in propulsion of electric
vehicles, elevator and hoists, and in drives for steel rolling mills. [1]

1.2 Problem Statement

DC motors are widely used in various applications due to their simplicity and effectiveness in
converting electrical energy into mechanical energy. Due to this, the demand of dc motors
has increased rapidly necessitating more development in the field of control.

However, controlling the speed and behavior of these motors can be challenging, especially
in applications requiring precise control.

The objective of this project is to implement a speed control mechanism using an Arduino
microcontroller, which will enable real-time adjustments to the motor's speed based on
feedback from sensors or user inputs. Additionally, the project aims to develop a model for a
DC motor that can effectively predict its performance characteristics, including speed, torque,
and response to input voltage changes.

1
University of Juba-School of Engineering & Architecture

1.3 Objectives

Objectives are divided into two categories; specific and general objectives.

1.3.1 Specific Objective

To design and control the speed of DC motor using Arduino microcontroller

1.3.2 General Objectives

To program an Arduino to produce pulse width modulation (PWM)

To Learn PID theory & implementation.

To Study encoder-based feedback systems

2
Chapter Two: Literature Review

CHAPTER TWO

LITERATURE REVIEW

2.1 Speed Control Techniques

Several techniques have been explored for controlling the speed of DC motors using the
Arduino Nano:

2.1.1 Open-Loop Control

Kumar et al. (2019) [2] ) implemented a PWM-based speed control system using an
Arduino Nano and an L298N motor driver. The system allowed for manual speed adjustment
via a potentiometer connected to an analog input of the Arduino.

The Arduino Nano generated a PWM signal with a variable duty cycle, which is fed to a
motor driver L298N. The duty cycle determined the average voltage applied to the motor,
thus controlling its speed. The system provided smooth speed control, but the speed varied
with changes in load.

2.1.2 Closed-Loop Control

Singh and Patel (2020) [3] developed a closed-loop speed control system using an
Arduino Nano, an L298N motor driver, and an optical encoder. A PID controller was
implemented in the Arduino firmware to maintain the desired speed.

In close loop control, an encoder is attached to the motor shaft to provide real-time speed
feedback. The Arduino Nano reads the encoder pulses and adjusts the PWM signal to
maintain the desired speed. By doing so, the system achieved precise speed control with
minimal error, even under varying load conditions.

Rahman et al. (2021 [4]) demonstrated the effectiveness of PID control in maintaining motor
speed under varying load conditions. PID Control: A Proportional-Integral-Derivative (PID)
controller is implemented on the Arduino Nano to achieve precise speed control. The PID

3
University of Juba-School of Engineering & Architecture

algorithm adjusts the PWM duty cycle based on the error between the desired and actual
speed and the system achieved high accuracy and stability.

2.1.3 Sensorless Control

Gupta et al. (2018) [5] implemented a sensorless speed control using back EMF
measurement, achieving reasonable accuracy but with limitations at low speeds. This was
done through back EMF Measurement:

The back electromotive force (EMF) of the motor is proportional to its speed. The Arduino
Nano measures the back EMF during the off periods of the PWM signal and uses it to
estimate the motor speed.

2.2: Arduino Integrated Environment

Programming the Arduino Nano is facilitated through the Arduino Integrated


Development Environment (IDE), which provides a user-friendly interface and a rich library
of code examples to help users get started quickly (Arduino, n.d.). This environment supports
a wide range of libraries that extend the Nano's functionality, allowing for the integration of
various shields and modules for enhanced capabilities, such as wireless communication and
motor control.

Banzi & Shiloh, 2014 [6], in this paper powering the Arduino Nano is simple; it can be
connected via USB or powered through an external source, with a recommended voltage
range of 7 to 12 volts (Arduino, n.d.). This flexibility is ideal for both stationary and portable
projects. The board also includes an onboard LED connected to pin 13, which serves as a
useful tool for debugging and monitoring the program's execution

2.3 Mathematical Model of Dc Motor

2.3.1 Physical setup

A common actuator in control systems is the DC motor. It directly provides rotary


motion and, coupled with wheels or drums and cables, can provide translational motion. The
electric equivalent circuit of the armature and the free-body diagram of the rotor are shown in
the following figure.

4
Chapter Two: Literature Review

2.3.2 Electrical System

The armature circuit can be modelled using Kirchhoff's voltage law

di a
V a =R i a + L +e (2.1)
dt b

Where;

R is the Armature resistance

L is the Armature inductance

e b is the Back EMF

2.3.3 Mechanical System

The mechanical system is governed by Newton's second law for rotation:


J + βω=T e −T L
dt
(2.2)

Where:

Tₑ is the Electromagnetic torque (proportional to current via torque constant Kt)

5
University of Juba-School of Engineering & Architecture

J is the total moment of inertia (motor + load)

Β is the viscous friction coefficient

TL is the Load torque

The generated voltage e b, is relative to angular velocity ω

e b=K b ω
(2.3)

The motor torque T e is related to the armature current, i a , by a torque constant K t ;

T e =K t i a
(2.4)

2.3.4 Transfer Function

Applying the Laplace transform, the above modelling equations can be expressed in terms of
the Laplace variable s.

V a ( s )=R I a ( s ) + LS I a ( s ) + E b (s ) (2.5)

Eb ( s ) =K b ω(s) (2.6)

JS ω ( s )+ βω ( s )=T e (s)−T L (2.7)

T e (s)−K t i a (s ) (2.8)

Substitute equation (2) into (1)

V a ( s )=¿ (2.9)

Substitute equation (3) into equation (4)

( JS+ β ) ω ( s )=K t i a ( s ) −TL (2.10)

From equation (5), get the value of I a ( s )

6
Chapter Two: Literature Review

V a ( s )−K b ω(s)
I a ( s )= (2.11)
R + LS

From equation (6), get the value of ω ( s )

K t i a ( s ) −TL
ω ( s )= (2.12)
( JS + β )

where;

Vₐ is the Applied armature voltage (input)

iₐ is the Armature current

Eb is the back EMF (electromotive force)

ω is the Angular velocity of the motor shaft (output)

Tₑ is the Electromagnetic torque produced by the motor

TL is the Load torque (disturbance input)

J is the Moment of inertia of the motor and load

β is the Damping coefficient (friction)

7
Chapter Three: Materials

CHAPTER THREE

MATERIALS

3.0 Introduction

This chapter will give detailed description on the components used in design and
speed control of dc motors using Arduino nano microcontroller.

3.1 DC Motor

A direct current (DC) motor is a fairly simple electric motor that uses electricity and a
magnetic field to produce torque, which causes it to turn. At its most simple, it requires two
magnets of opposite polarity and an electric coil, which acts as an electromagnet. The
repellent and attractive electromagnetic forces of the magnets provide the torque that causes
the motor to turn anyone who has ever played with magnets knows that they are polarized,
With a positive and a negative side. The attraction between opposite poles and the repulsion
of similar poles can easily be felt, even with relatively weak magnets. A DC motor uses these
properties to convert electricity into motion. As the magnets within the motor attract and
repel one another, the motor turns [7]

Figure 3.1: DC motor

A DC motor is powered by direct current, which converts electrical energy into mechanical
energy. This mechanical energy causes rotational movement within the motor, helping to
power a vast majority of industry applications [8]

8
Chapter Three: Materials

3.1.1 Types of DC motors

3.1.1.2 Permanent magnet motors

The permanent magnet motor uses a magnet to supply field flux, permanent magnet
DC motors have excellent starting torque capability with good speed regulation, a
disadvantage of permanent magnet DC motors is they are limited to the amount of load they
can drive, these motors can be found on low power applications.

3.1.1.3 Series motors

In a series DC motor, the field is connected in series with the armature, the field is
wound with a few turns of large wire because it must carry the full armature current. A
characteristic of series motors is the motor develops a large amount of starting torque.
However, speed varies widely between no load and full load. Series motors cannot be used
where a constant speed is required under varying loads. Additionally, the speed of a series
motor with no load increases to the point where the motor can become damaged, some load
must always be connected to a series-connected motor. Series-connected motors generally are
not suitable for use on most variable speed drive applications.

3.1.1.4 Shunt motors

In a shunt motor the field is connected in parallel (shunt) with the armature windings,
the shunt-connected motor offers good speed regulation, The field winding can be separately
excited or connected to the same source as the armature. An advantage to a separately excited
shunt field is the ability of a variable speed drive to provide independent control of the
armature and field, the shunt-connected motor offers simplified control for reversing. This is
especially beneficial in regenerative drives

3.1.1.5 Compound motors

Compound motors have a field connected in series with the armature and a separately excited
shunt field, the series field provides better starting torque and the shunt field provides better
speed regulation, however the series field can cause control problems in variable speed drive
applications and is generally not used in four quadrant drives.
9
University of Juba-School of Engineering & Architecture

3.1.2 Application of DC motors

DC motors are widely used in various applications due to their simplicity, reliability, and ease
of control. Here are some common applications:

Electric Vehicles: DC motors are extensively used in electric vehicles (EVs) for propulsion.
They provide high torque at low speeds, which is essential for vehicle acceleration. The speed
and torque can be easily controlled, making them suitable for applications in cars, bikes, and
scooters [9].

Robotics: In robotics, DC motors are used to drive wheels, robotic arms, and other
mechanisms. Their ability to provide precise control over speed and position makes them
ideal for applications in automated systems. [10]

Industrial Machinery: DC motors are commonly found in industrial applications such as


conveyor systems, pumps, and fans. They are favored for their ability to provide variable
speed control, which is crucial for processes that require different operational speeds. [11]

Home Appliances: Many household appliances, such as vacuum cleaners, washing


machines, and hair dryers, utilize DC motors. Their compact size and efficiency make them
suitable for these applications. [12].

3.1.3 Advantages of DC Motors

Speed Control: One of the primary advantages of DC motors is their ability to provide
precise speed control. By adjusting the voltage and current supplied to the motor, users can
easily vary the speed, making them ideal for applications where speed regulation is crucial.

High Starting Torque: DC motors are capable of producing high starting torque, which
makes them suitable for applications that require a significant amount of torque to start
moving, such as electric vehicles and cranes.

Simplicity of Design: The construction of DC motors is relatively simple, which can lead to
lower manufacturing costs and easier maintenance. This simplicity also allows for
straightforward integration into various systems.

10
Chapter Three: Materials

Reversibility: DC motors can be easily reversed by changing the direction of the current
flow, providing flexibility in applications that require bidirectional operation.

3.1.4 Disadvantages of DC Motors:

Maintenance Requirements: DC motors require regular maintenance, such as brush


replacement and commutator servicing. This can lead to increased downtime and additional
operational costs.

Heat Generation: DC motors tend to generate more heat during operation, especially under
heavy load conditions. This can necessitate additional cooling measures and can affect the
motor's lifespan.

Commutation Issues: The commutation process in DC motors can lead to issues such as
sparking and electrical noise, which may interfere with sensitive electronic equipment.

Power Supply Dependency: DC motors require a DC power supply, which can limit their
use in applications where AC power is more readily available or where energy efficiency is a
concern.

3.2 Arduino Nano

It is a small, complete, flexible and breadboard friendly microcontroller board-based


om ATmega328p. The board features a total of 30 pins, including 14 digital input/output pins
and 6 analog inputs, which enable it to interact with a wide array of sensors and devices
(Arduino, n.d.). The digital pins can be configured as either inputs or outputs, while the
analog pins can read voltages ranging from 0 to 5 volts, making it suitable for applications
that require precise data collection [13].

Programming the Nano is facilitated through the Arduino Integrated Development


Environment (IDE), which provides a user-friendly interface and a rich library of code
examples to help users get started quickly (Arduino, n.d.). This environment supports a wide
range of libraries that extend the Nano's functionality, allowing for the integration of various
shields and modules for enhanced capabilities, such as wireless communication and motor
control [13]
11
University of Juba-School of Engineering & Architecture

Figure 3.2: Showing Arduino nano

3.2.1 Arduino nano pinout

Power pin (Vin, 3.3V, 5V, GND)

 Vin is the input voltage of the board and it is used when an external power source is used
from 7V to 12V
 5V is the regulated power supply voltage of the nano board and it is used to give the
supply to the board as well as the components.
 3.3V is the minimum voltage which is generated from the voltage regulator on the board.
 GND is the ground pin of the board
 RST Pin (Reset); This pin is sued to reset the microcontroller
 Analog pins (A0-A7): These pins are used to calculate the analog voltage of the board
within the range of 0V to 5V
 Digital Pins (D0-D13); These pins are used as an input otherwise outputs pins (0V & 5V)
 Serial Pins (Tx, Rx): These pins are used to transmit and receive TTL serial data
 PWM (3,5,6,9,11): These pins are used to provide 8-bit of PWM output
 SPI (10, 11, 12 & 13); These pins are used for supporting SPI communication
 Inbuilt LED (13): This pin is used to activate the LED

12
Chapter Three: Materials

3.3. Arduino IDE

Integrated Development Environment is an open-source software used to write and


upload code to Arduino boards. It is designed for writing, compiling, and uploading code to
almost all Arduino modules. The IDE supports the programming languages C and C++ and is
suitable for different operating systems such as Windows, Mac OS X, and Linux.

3.4 L298N Motor driver Module

The L298N Motor Driver Module is a high-power motor driver for driving DC and
stepper motors. This module consists of a L298 motor driver IC and a 78M05 5V regulator.
L28N Module can control up to 4 DC Motors or 2 DC motors with directional and sped
control. It uses a L298N PWM system, which can control voltage using square wave pusles.
The wider the pulses, the faster the motor will rotoate. However, the exact pulse width will
vary depending on the type of motor being used.

Figure 3.3: Motor Driver

13
University of Juba-School of Engineering & Architecture

3.4.1 L298N Module Pinout Confguraiton

Table 1: showing the L298N Module Pinout Confguraiton

Pin Name Description

IN1 & IN2 Motor A input pins. Used to control the spinning direction of motor A

IN3 & IN4 Motor B input pins. Used to control the spinning direction of motor B

ENA Enbales PWM signal for motor B

ENB Enables PWM signal for motor B

OUT1 & OUT2 Output pins of Motor A

OUT3 & OUT4 Output pins of motor B

12 12v input from Dc power source

5V Supplies power for the switching logic circuitry inside l298N IC

GND Ground pin

3.5 Motor Encoder

Motor encoders are rotary encoders that measure the position and speed of a motor's
shaft. They provide feedback to the motor control system, allowing it to adjust the motor's
speed and position in real-time

3.5.1 Servo Motor Encoders

A servo motor encoder is a tool that gauges the speed and location of a servo motor's
rotation. It is made up of a rotating disc with parallel, uniformly spaced slots or lines that
block a light beam and generate electrical signals that represent the location and speed of the
motor.

14
Chapter Three: Materials

Servo motor encoders come in two primary categories: incremental and absolute. Absolute
encoders offer encoders provide information on changes in position and speed with respect to
a reference point information on the precise location of the motor shaft.

In conclusion, servo motor encoders are crucial parts for precise positioning and control of
servo motors in a variety of applications, including CNC machines, robotics, and automation.
[14]

Figure 3.4: Servo motor encoder

In conclusion, servo motor encoders are crucial parts for precise positioning and control of
servo motors in a variety of applications, including CNC machines, robotics, and automation.

3.5.2 Stepper Motor Encoders

Devices called stepper motor encoders are employed to gauge the speed and position
of a stepper motor. As stepper motors lack internal encoders, unlike servo motors, external
encoders must be used to give exact feedback and closed-loop control.

By giving feedback on the location, speed, and direction of the stepper motor, stepper motor
encoders enable precise control of its motions. They are frequently utilized in systems for
automation, machine tools, and robotics.

It's vital to remember that using stepper motor encoders makes the control system more
complex and expensive. Yet, they can offer important advantages in terms of performance,
accuracy, and dependability, particularly in high-precision applications.

15
University of Juba-School of Engineering & Architecture

Figure 3.5: Stepper Motor Encoders

3.6 Microcontroller

A microcontroller is a compact integrated circuit designed to govern a specific


operation in an embedded system. It is a self-contained system that incorporates a processor
core, memory and programmable input/output peripherals a single chip.

A typical microcontroller includes a processor, memory and input/output peripherals on a


single chip.

3.6.1 Microcontroller board

It is a printed circuit board (PCB) with circuitry and hardware designed to facilitate
experimentation with a certain microcontrollers’ boards feature. Our focus on this project will
be on Arduino nano microcontroller.

3.7 Sensors

In the context of speed control of a DC motor using the Arduino Nano microcontroller,
several sensors can be employed to provide feedback and enhance the performance of the
control system. Each sensor plays a critical role in ensuring accurate speed regulation and
responsiveness.

3.7.1 Hall effect sensor:

It can detect the position of a magnetic field. When placed near the motor's rotor, it can
provide information about the rotor's position, which is essential for implementing closed-
loop control strategies [15]. The Arduino Nano can utilize this data to adjust the PWM (Pulse
Width Modulation) signals sent to the motor driver, thereby controlling the speed more
effectively.

3.7.2 Current sensors

Current sensors such as the ACS712, are also valuable in this application. These sensors
measure the current flowing through the motor, allowing the Arduino Nano to monitor the

16
Chapter Three: Materials

load on the motor (ACS712, n.d.). By analyzing the current draw, the microcontroller can
make intelligent adjustments to avoid overloading the motor and ensure stable operation.

3.7.3 Temperature sensors

Current sensors like the LM35 can be utilized to monitor the motor's operating temperature.
Overheating can lead to reduced performance and potential damage, so having temperature
feedback allows the Arduino Nano to implement protective measures, such as reducing the
motor speed or shutting it down if necessary [16].

3.8 Mini USB-cable

The mini-USB -cable is used to transfer the program from the computer to the Arduino nano
board.

3.9 Breadboard

It is a solderless construction base used for developing an electronic circuit and wiring for
projects with microcontroller boards like Arduino.

A breadboard is helpful in building circuits without any soldering. Certain contacts are
connected with each other. Therefore, it is possible to connect many cables with each other
without soldering or screwing them together. The image below shows in color, which
contacts are connected.

3.10 Jumper Wires

A jump wire is a short electrical wire with a solid tip at each end (or only "tinned"
often without it), typically used to interconnect the components in a breadboard. A jump wire
(also referred to as a jumper wire or jumper) is an electrical wire, or group of wire, with a
connector or pin at each end (or often without, simply "tinned") that is usually used without
soldering to interconnect the components of a breadboard or other prototype or test circuit,
internally or with other devices or components. In the slots given in a breadboard, the header
connector of a circuit board, or a piece of test equipment, individual jump wires are fitted by
inserting their "end connectors." Disclosed is an enhanced arrangement of jump wire for a
printed circuit board. The arrangement requires at least one jump wire with its opposite ends
17
University of Juba-School of Engineering & Architecture

bent in the same direction to face each other, and at least one slot given on the printed circuit
board's upper surface. The slot has holes created at its opposite ends to permit the opposite
ends of the jump wire to be inserted. By inserting the opposite ends into the reverse through
holes, bending the opposite ends, and then welding these bent ends to a printed circuit pattern
shaped on the lower or rear surface of the printed circuit board, the jump wire can be
mounted 18 and installed in the slot. This arrangement allows the mounting density of
components and devices to be increased without fear of short-circuiting on the printed circuit
board.

3.11 The process of developing with Arduino

Figure 3.6: Arduino Sketch Software outlook

The development process for Arduino involves using the Arduino development environment,
which is a user-friendly software application designed to facilitate the writing and uploading
of code to an Arduino board. The environment is made up of various tools that work in
tandem to simplify the process, making it accessible to individuals with varying levels of
experience.

3.11.1 Software application with Arduino

3.11.2 Serial Monitor

The Serial Monitor is a useful tool in the Arduino development environment that can
help with debugging by showing any serial information being transmitted by the Arduino

18
Chapter Three: Materials

board. When the Serial Monitor is opened, a new window will display real-time data being
sent and received by the board.

This feature is particularly useful for identifying and troubleshooting any issues with your
code or circuitry during the development process. The Serial Monitor can be used to view
sensor readings, debug communication protocols, and troubleshoot any other issues that may
arise.

3.12 Methods of controlling the speed of a DC motor

3.12.1 Use of a Potentiometer

When a potentiometer is connected to the Arduino Nano, it is typically wired as a


voltage divider. The middle pin of the potentiometer is connected to an analog input pin on
the Arduino, while the other two pins are connected to the power supply and ground. As the
user turns the knob of the potentiometer, the resistance changes, altering the voltage that the
Arduino reads from the analog input.

The Arduino Nano continuously reads the voltage level from the potentiometer, which ranges
from 0 to 5 volts. This analog value is then mapped to a suitable PWM (Pulse Width
Modulation) value that corresponds to the desired speed of the DC motor. The mapping
process converts the analog input into a range suitable for controlling the motor's speed
(Arduino, n.d.). For example, a voltage of 0 volts might correspond to a PWM value of 0%
(motor stopped), while 5 volts might correspond to a PWM value of 100% (motor running at
full speed).

Once the PWM value is determined, the Arduino sends a signal to the motor driver circuit,
which regulates the power delivered to the DC motor based on the PWM input. By adjusting
the potentiometer, the user can smoothly control the speed of the motor, allowing for precise
operation in various applications, such as robotics, conveyor systems, or any project requiring
variable speed control.

Specifications:

 Resistance: 10K ohms.

19
University of Juba-School of Engineering & Architecture

 Adjustable via a rotating knob

Figure 3.7: Potentiometer

3.12.2 Pulse Width Modulation (PWM)

PWM is a modulation technique used to encode a message into a pulsing signal. The
average value of voltage fed to the load is controlled by turning the switch between supply
and load on and off at a fast rate. The longer the switch is on compared to the off periods, the
higher the total power supplied to the load.

Pulse width modulation control works by switching the power supplied to the motor on and
off very rapidly. The DC voltage is converted to a square wave signal, alternating between
fully on (nearly 12v) and zero, giving the motor a series of power “kicks”. Pulse width
modulation technique (PWM) is a technique for speed control which can overcome the
problem of poor starting performance of a motor.

3.12.2.1 Theory of Operation

A DC motor's speed is controlled by varying the voltage applied to it. However, directly
varying the voltage is not efficient or practical in many cases. Instead, we use Pulse Width
Modulation (PWM) to control the effective voltage supplied to the motor.

The Arduino digital pins either gives us 5V (when turned HIGH) or 0V (when turned LOW)
and the output is a square wave signal.

3.12.2.2 Terms used in PWM Theory

TON (On Time): It is the time when the signal is high.

20
Chapter Three: Materials

TOFF (Off Time): It is the time when the signal is low. Period: It is the sum of on time and off
time.

Duty Cycle: It is the percentage of time when the signal was high during the time of period.

T on
Duty cylce= × 100 (2.13)
T on+ T off

So, at 50% duty cycle and 1Hz frequency, the speed will be high for half a second and will be
low for the other half second. If we increase the frequency to 50Hz (50 times ON and OFF
per second), then the speed will be reduced to half its maximum speed.

The power applied to the motor can be controlled by varying the width of these applied
pulses and thereby varying the average DC voltage applied to the motor’s terminals. By
changing or modulating the timing of these pulses the speed of the motor can be controlled,
ie, the longer the pulse is “ON”, the faster the motor will rotate and likewise, the shorter the
pulse is “ON” the slower the motor will rotate.

When the duty cycle is 0%, the motor will stop completely because there is no voltage
difference. When the duty cycle is 50%, the motor will rotate at half the speed of the
maximum speed because the voltage is half the full voltage. When PWM is in 100%
condition, the motor rotates with maximum speed because of the continuous output of PWM.
In other words, the wider the pulse width, the more average voltage applied to the motor
terminals, the stronger the magnetic flux inside the armature windings and the faster the
motor will rotate and this is shown below. [17]

The Arduino Nano has specific pins (e.g., D3, D5, D6, D9, D10, D11) that support PWM
output. These pins can generate a PWM signal with a resolution of 8 bits (values from 0 to
255).

21
University of Juba-School of Engineering & Architecture

Figure 3.8: Pulse Width modulation

3.12.3 Proportional Integral Derivative (PID)

In the processing industries, different control strategies are used nowadays, according to their
needs and in a practical way, insufficient permanent precision, instability, too high a response
time, too great an overrun, with regard to the specifications of a specification. It is therefore
often necessary to integrate an organ called a corrector (Regulator) into the loop, the
objective of which is to improve the performance of the system. It is the control mechanism
that uses the information from the measurements of the controlled variable to manipulate a
variable in order to obtain the desired result. The controller is driven by the error between the
actual process output and the setpoint [18].

PID (Proportional–Integral– Derivative) controllers are universal controllers used in various


industrial processes. The popularity of PID controllers results from their good performance
over a wide range of conditions due to the simplicity of the PID, which allows engineers to
operate them directly. To implement the PID controller, three parameters must be set in the
controlled process which include proportional gain, integral gain, and derivative gain. [19]

Proportional-integral-derivative (PID) controllers are widely used in industrial control


systems because of the reduced number of parameters to be tuned. They provide control
signals that are proportional to the error between the reference signal and the actual output
(proportional action), to the integral of the error (integral action), and to the derivative of the
error (derivative action) namely [20].

[ ]
t
1 d
U ( t )=K p e ( t ) + ∫ e ( t ) dt +T d e (t) (2.14)
Ti 0 dt

22
Chapter Three: Materials

Where u(t) and e(t) denote the control and the error signals respectively, and K p, Ti and Td are
the parameters to be tuned. The corresponding transfer function is given as;

[
K(s) = kp 1+
1
T i (s )
+T d (s)
] (2.15)

These functions have been enough to the most control processes. Because the structure of
PID controller is simple, it is the most extensive control method to be used in industry so far.
The PID controller is mainly to adjust an appropriate proportional gain (Kp), integral gain
(KI), and differential gain (KD) to achieve the optimal control performance.

PID controllers have many types of uses, including controlling robotics, temperature,
speed, and positioning.

Figure 3.9: PID block diagram.

The error signal e (t) is the input to the PID controller

de
u=Kpe+ Kd + Ki ∫ edt
dt
(2.16)

Where;

Kp represents the Proportional Gain,

Ki represents the integral Gain,

Kd represents the derivative Gain

23
University of Juba-School of Engineering & Architecture

PID controller functions with closed-loop system. Variable (e) specifies tracking
error, difference among desired output (r) and actual output (y). Error signal (e) is
provided to PID controller, and controller evaluates derivative and integral of error
signal with time [24], then processed to calculate a new process input. This input will
try to adjust the measured process value back to the desired set point. [21]

The alternative to a closed loop control scheme such as the PID controller is an open
loop controller (no feedback) that is in many cases not satisfactory, and is often
impossible due to the system properties. By adding feedback from the system output,
performance can be improved

Figure 3.10: Closed Loop System with PID Controller.

The basic idea is that the controller reads the system state by a sensor then it subtracts
the measurement from a desired reference to generate the error value. [22] The error
will be managed in three ways, to:

Handle the present, through the proportional term

Recover from the past, using the integral term

Anticipate the future, through the derivative term.

Proportional-Integral-Derivative (PID) controller is the most common type of


feedback control. The PID controller uses all the three components P, I, and D.

24
Chapter Three: Materials

A proportional (P) controller uses only proportional action to correct deviations from
desired parameter value while acting on the error signal generated by the controller
output.

Proportional-Integral (PI) controller also uses the integral action to maintain closed-
loop performance for extended time periods at steady-state conditions. As a result, it
is very stable, but it may cause system overshoot due to its delayed corrective action.

Proportional-Derivative (PD) controller uses the derivative action to correct


deviations from desired parameter value measured by the rate of change of process
variable, i.e., error signal generated by the controller output. [23]

Figure 3.11: Schematic diagram of the wiring

25
University of Juba-School of Engineering & Architecture

26
Chapter Four: Results and Discussion

CHAPTER FOUR

RESULTS AND DISCUSSION

4.1 Introduction

This chapter will involve vivid methodology used in the project followed by the
results and finally the discussion of the results

4.2 Hardware needed and their roles

4.2.1 Arduino Nano

The microcontroller that reads the potentiometer input and generates the PWM signal for
speed control.

4.2.2. DC Motor with encoder

The motor whose speed needs to be controlled and provides feedback also

4.2.3. L298N Motor Driver

Acts as an interface between the Arduino and the motor. It amplifies the control signals from
the Arduino to drive the motor.

4.2.4 Potentiometer

Provides an analog input to the Arduino. By rotating the potentiometer, the user can vary the
voltage at the analog input pin, which is then used to control the motor speed.

4.2.5. Power Supply

The Arduino Nano can be powered via USB, but the motor and L298N require an external
power source (e.g., a 9V battery or 12V adapter) because motors typically draw more current
than the Arduino can supply.

26
Chapter Four: Results and Discussion

4.2.6. Breadboard and connecting wires

Figure 4.12: Components Required to Build a PID Enabled Encoder Motor Controller

4.3 Setup

4.3.1 Controlling the speed of DC motor using Potentiometer

Connect the Motor Driver (L298N) to the Arduino Nano

Connect the 5V from the motor driver to the 5V of the Arduino nano inside a breadboard

Connect the GND from the motor driver to the GND on the Arduino Nano inside breadboard

Connect the +12V from the motor driver to the Vin of the Arduino Nano inside a breadboard

Connect the `IN3` and `IN4` pins of the L298N motor driver to digital pins (D3 and D4) on
the Arduino Nano.

Connect the motor terminals to the output terminals OUT3 and OUT4 of the L298N motor
driver.

Connect the right end of the potentiometer to 5V, the left one end to GND, and the middle pin
(wiper) to an analog input pin (A0) on the Arduino Nano.

Power the motor driver and the motor with an external power source, 9V battery.

27
University of Juba-School of Engineering & Architecture

Arduino Motor Control Code Explanation

motorPin1=3 - Assigns digital pin 3 to control one side of the motor while
motorPin2=4 – which assigns digital pin 4 to control the other side of the motor. The
potentiometerPin= A0 assigns analog pin A0 to read the potentiometer value

In the setup Function, void setup (), Serial.begin(9600) which initializes serial
communication at 9600 baud rate for debugging/monitoring is used.

pinMode(motorPin1, OUTPUT) configures motorPin1 (digital pin 3) as an output pin


to control the motor while pinMode (motorPin2, OUTPUT) configures motorPin2 (digital pin
4) as an output pin while digitalWrite (motorPin2, LOW) sets motorPin2 to LOW

pinMode(potentiometerPin,INPUT) Configures the potentiometer pin as an input in


the Loop Function, void loop() int s=analogRead(potentiometerPin) reads the analog value
from the potentiometer (range 0-1024) and stores it in variable s.

int z=map(s,0,1024,0,255) is used to map the potentiometer reading (0-1023) to a


PWM range (0-255) suitable for motor speed control

Serial.println(z) prints the mapped PWM value to the serial monitor for debugging
while analogWrite(motorPin1,z) writes the PWM signal to motorPin1 to control motor speed
and since motorPin2 is held LOW, this creates a voltage difference that makes the motor spin
in one direction

4.3.1.1 Uploading the Code:

Connect the Arduino Nano to the computer via USB and upload the code using the
Arduino IDE after verifying the code. Then manually rotate the potentiometer observing the
motor speed changing accordingly.

28
Chapter Four: Results and Discussion

4.3.2 Controlling the speed of dc motor using Pulse Width Modulation

Connect the 5V from the motor driver to the 5V of the Arduino nano inside a
breadboard

Connect the GND from the motor driver to the GND on the Arduino Nano inside
breadboard

Connect the +12V from the motor driver to the Vin of the Arduino Nano inside a
breadboard

Connect the `IN3` and `IN4` pins of the L298N motor driver to digital pins (D3 and
D4) on the Arduino Nano.

Connect the motor terminals to the output terminals OUT3 and OUT4 of the L298N
motor driver.

Connect the ENA pin of the motor driver to the D9 on the Arduino nano

Power the motor driver and the motor with an external power source, 9V battery.

4.3.2.1 Programming the code on Arduino Nano

int motorPin1=3; // IN1 - Controls motor direction (connected to H-bridge input 1)

int motorPin2=4; // IN2 - Controls motor direction (connected to H-bridge input 2)

int enablePin=9; // ENA - PWM pin for speed control (enable pin of H-bridge)

motorPin1 and motorPin2 control the motor's direction by setting different IGH/LOW

combinations

enablePin controls the motor speed using PWM (Pulse Width Modulation)

Setup Function

29
University of Juba-School of Engineering & Architecture

void setup() {

pinMode(motorPin1,OUTPUT); // Set motorPin1 as output

pinMode(motorPin2,OUTPUT); // Set motorPin2 as output

pinMode(enablePin, OUTPUT); // Set enablePin as output

Initializes all motor control pins as digital outputs.

Main Loop

The loop contains 4 distinct phases:

Phase 1: Rotate Forward with Increasing Speed

digitalWrite(motorPin1, HIGH); // Set direction forward

digitalWrite(motorPin2, LOW);

for(int pwmValue=0; pwmValue <=255; pwmValue++){

analogWrite(enablePin, pwmValue); // Gradually increase speed

Serial.println(pwmValue); // Print current speed to serial

delay(100); // Small delay between speed steps

Sets motor direction forward (HIGH on pin1, LOW on pin2)

Gradually increases speed from 0 to max (PWM values 0-255)

Prints current speed to serial monitor

Each step has a 100ms delay

Phase 2: Stop Motor Briefly

analogWrite(enablePin,0); // Stop motor (PWM = 0)

delay(50); // Short pause

30
Chapter Four: Results and Discussion

Sets speed to 0 (stops motor)

Waits 50ms before changing direction

Phase 3: Rotate Backward with Decreasing Speed

digitalWrite(motorPin1, LOW); // Set direction backward

digitalWrite(motorPin2, HIGH);

for(int pwmValue=255; pwmValue >=0; pwmValue--){

analogWrite(enablePin, pwmValue); // Gradually decrease speed

delay(100); // Small delay between speed steps

Sets motor direction backward (LOW on pin1, HIGH on pin2)

Gradually decreases speed from max to 0 (PWM values 255-0)

Each step has a 100ms delay

Phase 4: Stop Motor Briefly Again

analogWrite(enablePin,0); // Stop motor (PWM = 0)

delay (50); // Short pause

Sets speed to 0 again


Waits 50ms before repeating the cycle

4.3.3 Controlling the speed of DC Motor using Proportional Integral Derivative

The sensor used is a magnetic incremental encoder directly attached to the motor
shaft. This encoder has a disc with magnetic poles and two inductive sensors mounted in
quadrature, generating square signals shifted by a quarter of a period as the disc rotates.

The detection of rising and/or falling edges allows determining the number of pulses per
revolution or the motor's rotation direction.

31
University of Juba-School of Engineering & Architecture

The calculation of the error and the control voltage will be done by the Arduino board. To
drive the 12V DC motor, a power interface board in the form of an H-bridge, built around an
L298, will be used. [24]

The encoder works by observing changes in the magnetic field generated by a magnet
attached to the motor shaft. The engine rotates the encoder outputs periodically. If we select
encoder Pin A before encoder Pin B, the encoded DC motor will rotate clockwise (CW). On
the other hand, if we select the Pin B encoder before the Pin A encoder, the encoded DC
motor will rotate in a counterclockwise direction (CCW).

The ground pin (Black Wire) of the encoder connects to Arduino GND while the red and
white wires on the encoder connects to the output terminals OUT3 and OUT4 of the L298N
motor driver.

The encoder A (Yellow) connects to pin D2 of Arduino. Pin D2 from Arduino will record
each time there is an ascending digital signal from Encoder A. The B encoder (Green Wire)
connects to pin D3 of Arduino. The signal that is read from pin D3 on Arduino.

The VCC pin (Blue Wire) of the motor connects to the 5V pin in Arduino. This pin is
responsible for providing power to the encoder program.

4.3.3.1 Designing the code on the Arduino IDE

Motor Driver: Controls the motor using:

PWM (Pin 5): Speed control (0-255)

IN1 (Pin 7) & IN2 (Pin 6): Direction control (HIGH/LOW combinations)

Encoder:

ENCA (Pin 2, Yellow): Tracks motor rotation (interrupt-based)

ENCB (Pin 3, Green): Determines direction (forward/backward)

Setup Phase (setup())

Serial Monitor Starts at 9600 baud (for debugging & plotting).

32
Chapter Four: Results and Discussion

Encoder Pins Configured:

ENCA triggers an interrupt on every rising edge (each time the motor moves).

ENCB tells us direction (forward or backward).

 Serial Plotter Headers:

Serial.println("Target_Velocity,Velocity_Motor_A");

This helps the Serial Plotter label the graphs properly.

Main Loop (loop())

Step 1: Set a Moving Target (Sine Wave)

float targetVel = 100 * sin(millis() / 1000.0); // Oscillates between -100 and 100

The target speed changes smoothly like a wave (1-second cycle).

Step 2: PID Control (Proportional-Integral-Derivative)

The PID controller adjusts motor power to match the target speed.

Proportional (P) Term (kp):

If the motor is too slow, it speeds up; if too fast, it slows down.

Derivative (D) Term (kd):

Helps dampen oscillations (like shock absorbers in a car).

Integral (I) Term (ki):

Fixes small, persistent errors (e.g., motor struggles at low speeds).

Step 3: Measure Actual Speed

Encoder Position → Velocity:

velocity = (pos - prevPos) / deltaT; // Speed = change in position / time


33
University of Juba-School of Engineering & Architecture

The encoder counts "ticks" per second which are converted to speed.

Step 4: Calculate Motor Power & Direction

PID Output (u) determines how much power to send:

float u = kp * e + kd * dedt + ki * eintegral;

Direction is set based on whether u is positive or negative:

if (u < 0) dir = -1; // Reverse

else dir = 1; // Forward

 PWM Constrained to 0-255 (Arduino’s max analog output).

Step 5: Send Data to Serial Plotter

Serial.print(targetVel); // Target speed (sine wave)

Serial.print(","); // Separator

Serial.println(velocity); // Actual motor speed

Serial Plotter graphs both speeds in real-time:

Blue Line (Target_Velocity): Smooth sine wave.

Orange Line (Velocity_Motor_A): Motor’s actual speed (should follow the


blue line closely).

Encoder Interrupt (readEncoder())

Triggered every time ENCA rises (motor moves).

Checks ENCB to determine direction:

if (digitalRead(ENCB) > 0) posi++; // Forward

else posi--; // Backward

34
Chapter Four: Results and Discussion

volatile keyword ensures no misreads during interrupts.

Motor Control (setMotor())

Sets speed (pwmVal) and direction (dir):

Forward: IN1 = HIGH, IN2 = LOW

Reverse: IN1 = LOW, IN2 = HIGH

Stop: IN1 = LOW, IN2 = LOW

analogWrite(PWM, pwmVal) adjusts speed.

4.4 Results

4.4.1 Open Loop Control

In the open loop control using potentiometer and PWM, motor speed varied
proportionally with potentiometer position.

The response time was fast especially with PWM adjustments while there was no overshoot
since there was no feedback.

4.4.2 Closed Loop Control

Controlling the Speed of a DC Motor using PWM allows precise adjustment for
optimal performance. Feedback mechanisms, such as encoders, ensure desired speed is
maintained by comparing it with the actual speed.

Before entering the values of Kp (proportional gain), Ki (integral gain), and Kd (derivative
gain), it was important to consider the desired performance and characteristics of the
motor. These parameters determine how the controller responds to changes in speed, errors,
and disturbances. By tuning these values appropriately, the motor's speed control system can
achieve stability, responsiveness, and optimal performance.

35
University of Juba-School of Engineering & Architecture

Figure 4.13: DC motor control result before entering PID values

By observing the motor's speed control system without PID parameters, we gathered
valuable insights such as response time, steady-state error, and sensitivity to disturbances.
This information served as a baseline for evaluating the effectiveness of the PID tuning

process.

Figure 4.14: DC motor speed control after inputting the PID values

36
Chapter Four: Results and Discussion

Before entering PID values, the engine speed control system presents some
limitations. I experienced slower response time, higher steady state error, and difficulty
maintaining the desired speed under various conditions. However, after entering appropriate
PID values (Kp, Ki, and Kd), remarkable improvements in system performance can be
observe

After tuning the PID parameters, the motors demonstrate faster response time,
reduced steady- state error, and improved ability to maintain the required speed under
different conditions. The control system becomes more robust and adaptive, effectively
compensating for disturbances and achieving better stability.

Optimal PID parameters found:

Kp = 2.5

Ki = 0.8

Kd = 0.3

4.4.3 Discussion

The open-loop system showed poor load regulation as expected. Without feedback, the
controller couldn't compensate for speed variations caused by changing loads. This method is
only suitable for applications where precise speed control isn't required and loads remain
constant.

The PID controller significantly improved speed regulation under varying loads. The integral
term eliminated steady-state error, while the derivative term helped reduce overshoot during
setpoint changes. Tuning was critical, excessive integral gain caused oscillations, while too
much derivative gain made the system sluggish.

4.5 Challenges Faced

Manually connecting the components was tedious and sometimes the results wouldn’t
be satisfactory.

37
University of Juba-School of Engineering & Architecture

Power Supply fluctuations, the battery had to be re-charged continuously


Encoder Noise in form of mechanical vibrations caused false encoder readings,
leading to unstable PID control.
Finding optimal Kp, Ki, Kd values required trial and error due to PID tuning
difficulty

38
Chapter Five: Conclusion and Recommendations

CHAPTER FIVE

CONCLUSION AND RECOMMENDATIONS

5.1 Conclusion

In conclusion, this project has successfully tackled the position and speed control of a
DC motor equipped with an encoder, using the L298 driver and Arduino nano. Thanks to the
methodology described in the previous chapters, we have achieved significant results and
made valuable contributions to the field of automation and robotics.

The project began with introduction of the topic itself then complete understanding of the
hardware components involved, including DC motors, encoders and the L298 motor driver.
By integrating these elements with Arduino nano, we were able to develop a robust control
system capable of precise, reproducible movements.

The modelling and control techniques implemented in this project proved effective in
achieving the desired performance. The mathematical models derived in Chapter 2 provided a
solid basis for the development of the control algorithms. Through careful tuning and testing,
we were able to achieve precise position control and accurate speed regulation.

This project paves the way for various applications in the fields of automation and robotics.
Precise control of motor position and speed can be exploited in industrial automation, robotic
arm control, numerically controlled machines, etc. The control system developed can be
enhanced and adapted to different motor configurations and applications.

In conclusion, this project has provided a complete solution for controlling the speed of a DC
motor with potentiometer, PWM and an encoder using the L298 driver and Arduino. Overall,
PID control is a critical tool in maximizing the capabilities of DC motors, resulting in
efficient and reliable operation in various applications.

39
University of Juba-School of Engineering & Architecture

5.2 Recommendations

This project opens up several promising avenues for future research and development
in the field of DC motor position and speed control with encoders using the L298 driver and
Arduino. Here are some potential avenues to explore:

Manually mounting the components each and every time together which was the
challenge and it can be improved by using a Printed Circuit Board (PCB) which is a
flat board made of insulating material (like fiberglass or plastic) with thin layers
of copper traces that connect electronic components without messy wires.

Optical Encoder with Higher PPR (e.g., 500 PPR) compared to our 210RPM for more
precise speed feedback.

Use a Moving Average Filter on encoder readings to reduce noise

Advanced control techniques: Further research can be carried out into advanced
control techniques such as adaptive control, neural networks or machine learning
algorithms to improve system performance, robustness and adaptability to different
operating conditions.

[1] Karapidakis, John Syllignakis & E. S., Automatic Speed control of a DC Motor using

40
Chapter Five: Conclusion and Recommendations

Arduino, for laboratory Applications, Hellenic Mediterannean University.

[2] Kumar, A., Sharma, R., & Singh, P., ''PWM - Based Speed Control of DC Motor Using
Arduino Nano.'', International Journal of Engineering Research & Technology (IJERT),
8(5), 123-127, 2019.

[3] Singh, R., & Patel, S. , ''Closed - Loop Speed Control of DC Mootr Using Arduino
Nano and PID Controller.'', Journal of Electrical Engineering 15(3), 45-52, 2020.

[4] Rahman, M., Islam, M., & Hossain, M., Implementation of PID Controller for DC
Motor Speed Control Using Arduino Nano., International Journal of Advanced Research
in Electrical, Electronics and Instrumentation Engineering, 10(2), 89-95, 2021.

[5] Gupta, S., Yadav, V., & Tiwari, R., Sensorless Speed Control of DC motor using Back
EMF Measurement with Arduino Nano., International Journal of Innovative Research,
in Science, Engineering and Technology, 7(4), 345-350, (2018).

[6] M, Banzi M. & Shiloh, Getting Started with Arduino, Maker Media, Inc, 2014.

[7] Iqbal, K., 'PI, PD, and PD, Mar 5, 2021.

[8] Arnett, B. R., The History of DC Motors, 10 August 2020.

[9] Dixon, J, ''Electric Vehicle Tecnhology Explained, Wiley, 2010.

[10] Siciliano, B., et al., Springer handbook of Robotics,'', Springer, 2008.

[11] Mohan, N., Electric Machines, A Modern Approach, Wiley 2012.

[12] Ahmed, M. R., Electric Motors and Drives: Fundamentals, Types and Applications,",
Elsevier, 2010)..

[13] Banzi, M., & Shiloh, M., Getting started with Arduino, Maker Media, lnc., 2014.

[14] B.B. & Eddie Smigiel, Discover the constitution of servomotors, Strasbourg, 2019.

[15] - Mohammed, S. M., Ramesh, P., & Kumar, R., Design of DC Motor Speed Control
System using Hall Effect Sensor, Journal of Electrical Engineering and Automation,
2(1), 15-20., 2020.

[16] - Rao, P. S., Bala, M. R., & Reddy, R., Temperature Sensor Based Motor Control
41
University of Juba-School of Engineering & Architecture

Application., International Journal of Engineering Research and Applications, 3(4), 102-


107., 2013.

[17] Https://www.electronics-tutorials.ws/blog/pulse-width-modulation.html.

[18] B. W. Bequette, ., Process control: modeling, design, and simulation, Prentice Hall
Professional, 2003.

[19] Hote, U. Pande and Y. V, "Real time Design of PID Controller for Process Control
System, International Conference on Smart Technologies in Computing, Electrical and
Electronics (ICSTCEE), 2020.

[20] P. Meshram and R. G. Kanojiya, Tuning of PID controller using Ziegler-Nichols


method for speed control of DC motor, 2012.

[21] Farouk Zouari, et.al.,, “Ädaptive Internal Model Control of a DC Motor Drive System
Using Dynamic Neural Network", Journal of Software.

[22] Kaya, Ibrahim, ''IMC based automatic tuning method for PID controllers in a smith
Predictor configuration, Science Direct, 2004.

[23] ]https://plcynergy.com/pid-controller/.

[24] https://www.informatique-et-electronique.fr/index.php/electronique-tutos/
asservissementde-position-d-un-moteur-a-courant-continu.

[25] B. C. &. G. F. Kuo, Automatic Control Systems, John Wiley & Sons, 2009 .

[26] W. L. Zha J. Z., Dynamic Simulation of Double Closed Loop Speed-adjustment System
for DC Motor, [J]. Digital Technology and Application, 2022.

[27] Dejan, Arduino DC Motor Control Tutorial - L298N/PWM H-Bridge., 2017.

[28] Dejan, Arduino DC Motor Control Tutorial – L298N | PWM H-Bridge, [Online].
Available: https : / / howtomechatronics . com / tutorials /, 2017.

42
Chapter Five: Conclusion and Recommendations

43
Appendices

Appendices
int motorPin1=3;
int motorPin2=4;
int potentiometerPin=A0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(motorPin1,OUTPUT); // Motor Pin 1
pinMode(motorPin2,OUTPUT); //Motor Pin 2/ digitalWrite(4,LOW);
//Normally low in this pin
digitalWrite(motorPin2, LOW);
pinMode(potentiometerPin,INPUT);
}

void loop() {
// put your main; code here, to run repeatedly:
int s=analogRead(potentiometerPin);
int z=map(s,0,1024,0,255);
Serial.println(z);
analogWrite(motorPin1,z);
}

44
Appendices

int motorPin1=3; //IN1


int motorPin2=4; //IN2
int enablePin=9; //ENA (PWM)

void setup() {
// put your setup code here, to run once:
pinMode(motorPin1,OUTPUT); // Motor Pin1
pinMode(motorPin2,OUTPUT); // Motor pin2
pinMode(enablePin, OUTPUT); //Enable A
}

void loop() {
// put your main code here, to run repeatedly:
Serial.begin(9600);
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
for(int pwmValue=0; pwmValue <=255; pwmValue++){
analogWrite(enablePin, pwmValue); //set the speed of the motor ;
Serial.println(pwmValue);
delay(100); //wait for 1000 milliseconds
}

//Stop the motor


analogWrite(enablePin,0); //sets speeed to 0
delay(50); //wait for 1000 milliseconds

//Rotate in the opposite direction with PWM


digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
for(int pwmValue=255; pwmValue >=0; pwmValue--){

45
University of Juba-School of Engineering & Architecture

analogWrite(enablePin, pwmValue); //set the speed of the motor


delay(100); //wait for 1000 milliseconds
}

//Stop the motor


analogWrite(enablePin,0); //sets speeed to 0
delay(50); //wait for 1000 milliseconds

46
Appendices

#include <util/atomic.h>

#define ENCA 2 // Encoder A (Yellow)


#define ENCB 3 // Encoder B (Green)
#define PWM 5 // PWM pin
#define IN2 6 // Motor control pin 2
#define IN1 7 // Motor control pin 1

volatile int posi = 0; // Current encoder position


long prevT = 0; // Previous time measurement
float velocity = 0; // Calculated velocity
float prevPos = 0; // Previous position for velocity calculation
float eprev = 0; // Previous error
float eintegral = 0; // Integral term

void setup() {
Serial.begin(9600);
pinMode(ENCA, INPUT);
pinMode(ENCB, INPUT);
attachInterrupt(digitalPinToInterrupt(ENCA), readEncoder, RISING);

// Print headers for Serial Plotter


Serial.println("Target_Velocity,Velocity_Motor_A");
}

void loop() {
// Set target velocity (RPM or arbitrary units)
// Using sine wave for demonstration (range -100 to 100)
float targetVel = 100 * sin(millis() / 1000.0); // 1 second period

47
University of Juba-School of Engineering & Architecture

// PID constants - tune these for your motor


float kp = 2.5; // Proportional gain
float kd = 0.8; // Derivative gain
float ki = 0.3; // Integral gain

// Calculate time difference


long currT = micros();
float deltaT = ((float)(currT - prevT)) / 1.0e6; // Convert to seconds
prevT = currT;

// Read position atomically


int pos = 0;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
pos = posi;
}

// Calculate velocity (change in position / time)


velocity = (pos - prevPos) / deltaT;
prevPos = pos;

// Calculate error (difference between target and actual velocity)


float e = targetVel - velocity;

// Calculate derivative of error


float dedt = (e - eprev) / deltaT;

// Calculate integral term (with anti-windup)


eintegral = eintegral + e * deltaT;
if (eintegral > 255) eintegral = 255;
if (eintegral < -255) eintegral = -255;

48
Appendices

// PID control signal


float u = kp * e + kd * dedt + ki * eintegral;

// Motor power (constrain to 0-255)


float pwr = fabs(u);
if (pwr > 255) pwr = 255;

// Motor direction
int dir = 1;
if (u < 0) dir = -1;

// Signal the motor


setMotor(dir, pwr, PWM, IN1, IN2);

// Store previous error


eprev = e;

// Print data for Serial Plotter with labels


Serial.print(targetVel); // Target velocity
Serial.print(","); // Comma separator
Serial.println(velocity); // Actual velocity

// Small delay to prevent Serial buffer overflow


delay(10);
}

void setMotor(int dir, int pwmVal, int pwm, int in1, int in2) {
analogWrite(pwm, pwmVal);
if (dir == 1) {
digitalWrite(in1, HIGH);

49
University of Juba-School of Engineering & Architecture

digitalWrite(in2, LOW);
} else if (dir == -1) {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
} else {
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
}

void readEncoder() {
int b = digitalRead(ENCB);
if (b > 0) {
posi++;
} else {
posi--;
}

50

You might also like