Download - Chapter 222 Labview
CHAPTER – 1
GENERAL OVERVIEW OF THE PROJECT
1.1 Introduction
Direct current (DC) motors have variable characteristics and are used
extensively in variable-speed drives. DC motor can provide a high
starting torque and it is also possible to obtain speed control over wide
range. Why do we need a speed motor controller? For example, if we
have a DC motor in a robot, if we just apply a constant power to each
motor on a robot, then the poor robot will never be able to maintain a
steady speed. It will go slower over carpet, faster over smooth flooring,
slower up hill, faster downhill, etc. So, it is important to make a controller
to control the speed of DC motor in desired speed.
DC motor plays a significant role in modern industrial. These are several
types of applications where the load on the DC motor varies over a speed
range. These applications may demand high-speed control accuracy and
good dynamic responses.
In home appliances, washers, dryers and compressors are good examples.
In automotive, fuel pump control, electronic steering control, engine
control and electric vehicle control are good examples of these. In
aerospace, there are a number of applications, like centrifuges, pumps,
robotic arm controls, gyroscope controls and so on.
By using NI LabVIEW as the motor controller, we can control a DC
motor for multiple purposes using only one software environment. We
can interface Arduino Uno with LabVIEW and use a DC motor driver
L293D as the sub controller, and an encoder of the motor as the sensor.
1.2 Objective of the Project
The main core of this project is to design a speed control system of DC
Motor by using PWM technique generated through Arduino. This system
will be able to control the DC motor speed at desired speed regardless the
changes of load. We can implement a low cost acquisition system
intended for control applications using the Arduino prototyping platform.
Arduino has become a popular open source single-board microcontroller
among electronic hobbyists, and it is gaining acceptance as a quick
prototyping tool for engineering and educational projects also. The
system meets the following requirements:
Suitable for educational purpose
Low cost: The components are affordable.
Easy to assembly due to the constitution of the
modules.
Able to run on different platforms: the overall system
can operate in different operating systems.
Open hardware and open source: This means that the
hardware and the software used has a public access. Anyone
can use it and improve it.
Suitable for control applications
Bidirectional: It is possible for data to be transmitted in both
directions via USB serial communication.
Wired / Wireless connection
Autonomous or dependent system
1.3 Organisation of the Project
The present report is organized in ten chapters. In general, all of them can
be read independently as self-contained entities. In first chapter, it discuss
about the objective and scope of this project as well as its application.
While
Chapter 2 will discuss more on theory and literature reviews that have
been done.
Chapter 3 will discuss about how to measure speed of DC motor and
speed controlling technique that can be used to control the speed of the
motor.
In Chapter 4 and Chapter 5 the discussion will be on L293D motor
driver and Encoder respectively.
Chapter 6 and Chapter 7 present the details of IR Sensors and PWM.
Chapter 8 and Chapter 9 deals with Arduino UNO and its interfacing
with LabVIEW.
Chapter 10 gives the conclusion of this project and future work that can
be done based on this work.
CHAPTER – 2
THEORY
This chapter will discuss about theory portion. It will discuss about
various hardware and software components used in the project. It will
also introduce the need of automation and Arduino platform.
A computer, using a control application done in LabVIEW, controls all
the system by cable or wireless. This control application display all the
data obtained from the acquisition system, and save it into a file
document in order to obtain a history of the measures.
In this project various sensors like Infrared sensors are used and there
data is gathered using Arduino microcontroller, control action can also be
done simultaneously like DC motor control using Pulse Width
Modulation as demonstrated further. Simple block to demonstrate is
shown in Figure 2.1 LabVIEW-Arduino Interaction with physical world.
Figure 2.1 LabVIEW-Arduino Interaction with physical world
2.1 Automation of DC Electrical Machines
In today’s world of changing technologies and the advent of
newness and innovations automation plays a major role.
Automation is in everything we see in the world today.
Automation is also present in things which are used in the day to
day life.
Similarly automation is also present in the field of electrical
engineering especially machines. In the discussion considered in
the report the automation of electrical machines mainly refers to
the automation of DC electrical machines that is DC motor, DC
generator, or the set of a motor generator which are tightly coupled
together.
The automation of DC electrical machines includes a same kit for
every test to be performed on the machines but only changing the
programming part.
The change in the programming part is done using very open and
compatible software called the LabVIEW (version 7.1) software
The DC motor can be controlled by using Arduino board (which
measures the speed ) and LabVIEW (which controls the speed)
2.2 Need for Automation
Automation is the use of control systems and information technologies
reducing the need for human intervention. In the scope of
industrialization, automation is a step beyond mechanization. Then it
provides the applications of automation in industries such as
manufacturing, agricultural, health care, distribution and logistics, cold
storage, retail, field service, government. Automation (including robotics,
industrial automation and computer numerical control), is the use of
control systems such as computers to control industrial machinery and
processes, replacing human operators. And also mechanization provides
human operators with machinery to assist them with the physical
requirements of work; automation greatly reduces the need for human
sensory and mental requirements as well. At first glance, automation
might appear to devalue labour through its replacement with less-
expensive machines; however, the overall effect of this on the workforce
as a whole remains unclear.
Today automation of the workforce is quite advanced, and continues to
advance increasingly more rapidly throughout the world and is
encroaching on ever more skilled jobs, yet during the same period the
general well-being and quality of life of most people in the world (where
political factors have not muddied the picture) have improved
dramatically. Automation is also being implemented in the manufacturing
industries where combining the wireless local area network (WLAN)
enabled handheld computers, bar code and thermal printing technologies
with applications from market-leading are done.
Advanced Automation is also used to streamline the entire
manufacturing processes. By creating a more seamless flow of
continuous, accurate documentation on materials, parts or machine
conditions, one will experience fewer errors and improve production.
Advanced Automation can help one error-proof one’s operations to
deliver better products faster, reduce waste, control costs and improve
customer service.
Hence, because of all these recompenses it can be confirmed that there is
a dire need for automation in any application, phase or any industry.
2.3 Data Acquisition System (DAQ) using Arduino
Considering small scale applications where accuracy and high speed is
not so important, industrial scale DAQ’s with high price tag is not
necessary. But instead a low cost micro controller like Atmel 328
(Arduino Uno) is enough to meet the requirement.
DC motor control using Pulse Width Modulation (PWM) signifies the
controllability of the Arduino hardware and LabVIEW software.
Graphical User Interface created by the LabVIEW is extremely pleasing
and user friendly. Various controls like PID controllers, analog and
digital filters etc. can be incorporated in the advance versions (PID block
is available in LabVIEW control system palette)
The control signals are fed into L293D motor IC which requires the
power required by the motor to run , the cycle can be varied from 0-100%
by controlling the user controlled interactive graphical data even the
motor direction is controlled from the front panel of the programme by
the user pc integrated with the system
Because the Arduino can't handle more than 40ma of current, you must
have an external power source to power it. This circuit enables you to use
a motor that is too big for the Arduino to handle, control direction of the
motor with a relay, and control the speed of the motor with a
potentiometer.
2.4 Basic Overview
The main overview of our project can be well explained with the help of
the figure shown below-
Figure 2.2 Basic Overview
Our Project is divided into two parts:
a) HARDWARE
b) SOFTWARE
The hardware part consist of following parts-
DC MOTOR
L293D DC MOTOR DRIVER
ENCODER
IR SENSOR
ARDUINO BOARD (FOR PWM GENERATION)
The software part consist of-
LAPTOP WITH LABVIEW SOFTWARE INSTALLED
The main challenge of our project is creating an interface control system
for motor operations, from small-scale models to large industrial
applications. Now we will try to explain components and software that
has been used in our project in the following chapters.
2.5 About LabVIEW
Lab VIEW is a graphical programming environment used by millions of
engineers and scientists to develop sophisticated measurement, test, and
control systems using intuitive graphical icons and wires that resemble a
flowchart. It offers unrivalled integration with thousands of hardware
devices and provides hundreds of built-in libraries for advanced analysis
and data visualization – all for creating virtual instrumentation. The
LabVIEW platform is scalable across multiple targets and OSs, and, since
its introduction in 1986, it has become an industry leader. The
programming that is done in this Lab VIEW software is mainly Graphical
Programming that is Program with drag-and-drop, graphical function
blocks instead of writing lines of text. The representation is mainly
Dataflow Representation which is easily developed, maintain, and
understand code with an intuitive flowchart representation.
Lab VIEW is the centre piece of graphical system design and provides
engineers and scientists with the tools you need to create and deploy
measurement and control systems. We can get more done in less time
with LAB VIEW through its unique graphical programming environment;
built-in engineering-specific libraries of software functions and hardware
interfaces; and data analysis, visualization, and sharing features. We can
bring your vision to life with Lab VIEW. Through a world-class
ecosystem of partners and technology alliances, a global and active user
community, and consistent annual releases, you can have the confidence
to continually innovate. Lab VIEW makes complex control simple and
accessible.
Lab VIEW makes me better because code reuse saves time and effort
because one of the most efficient ways to shorten development time is
through code reuse. By taking advantage of existing code, whether it has
already been written or is part of a resource library, developers and
domain experts can focus on their applications rather than committing
valuable time and resources to programming. Lab VIEW is an ideal
platform for prototyping, designing, and deploying high-quality products
to market fast. We can use one development environment to quickly
iterate on your embedded hardware and software designs and then reuse
the best parts in a final product.
Lab VIEW removes the need to abstract those into procedural code. Our
whiteboard diagram becomes your code. Also, we have all of the
functions at your fingertips to easily deal with the complex web of
sensors, multiple-linked actuators, and dynamic real-time control.
LabVIEW reduces the time to test these products by helping you develop
a flexible and efficient system that synchronizes multiple measurements
and analysis within your software. This results in faster inspection times
across I/O. The Lab VIEW development environment provides the ability
to build programs graphically by using intuitive icons and wires that
resemble a flowchart. Because Lab VIEW requires us to base the
structure of the program around the flow of data, we are encouraged to
think in terms of the problem you need to solve as well as conceptualize
our application in a parallel view and not sequential.
CHAPTER – 3
DC MOTOR
The input is electrical energy (from the supply source), and the output is
mechanical energy (to the load).
DC motors consist of one set of coils, called armature winding, inside
another set of coils or a set of permanent magnets, called the stator.
Applying a voltage to the coils produces a torque in the armature,
resulting in motion.
3.1 Constructional Features
A DC motor relies on the fact that like magnet poles repels and unlike
magnetic poles attracts each other. A coil of wire with a current running
through it generates a electromagnetic field aligned with the centre of the
coil. By switching the current on or off in a coil its magnet field can be
switched on or off or by switching the direction of the current in the coil
the direction of the generated magnetic field can be switched 180°.
A simple DC motor typically has a stationary set of magnets in the stator
and an armature with a series of two or more windings of wire wrapped in
insulated stack slots around iron pole pieces (called stack teeth) with the
ends of the wires terminating on a commutator. The armature includes the
mounting bearings that keep it in the centre of the motor and the power
shaft of the motor and the commutator connections. The winding in the
armature continues to loop all the way around the armature and uses
either single or parallel conductors (wires), and can circle several times
around the stack teeth. The total amount of current sent to the coil, the
coil's size and what it's wrapped around dictate the strength of the
electromagnetic field created.
The sequence of turning a particular coil on or off dictates what direction
the effective electromagnetic fields are pointed. By turning on and off
coils in sequence a rotating magnetic field can be created. These rotating
magnetic fields interact with the magnetic fields of the magnets
(permanent or electromagnets) in the stationary part of the motor (stator)
to create a force on the armature which causes it to rotate. In some DC
motor designs the stator fields use electromagnets to create their magnetic
fields which allow greater control over the motor. At high power levels,
DC motors are almost always cooled using forced air.
Figure 3.1 DC Motor
3.2 Basic principle of operation
If electrical energy is supplied to a conductor lying perpendicular to a
magnetic field, the interaction of current flowing in the conductor and the
magnetic field will produce mechanical force (and therefore, mechanical
energy).
3.3 Commutation Action
The commutator allows each armature coil to be activated in turn. The
current in the coil is typically supplied via two brushes that make moving
contact with the commutator. Now, some brushless DC motors have
electronics that switch the DC current to each coil on and off and have no
brushes to wear out or create sparks.
Different number of stator and armature fields as well as how they are
connected provide different inherent speed/torque regulation
characteristics. The speed of a DC motor can be controlled by changing
the voltage applied to the armature. The introduction of variable
resistance in the armature circuit or field circuit allowed speed control.
Modern DC motors are often controlled by power electronics systems
which adjust the voltage by "chopping" the DC current into on and off
cycles which have an effective lower voltage.
Since the series-wound DC motor develops its highest torque at low
speed, it is often used in traction applications such as electric
locomotives, and trams. The DC motor was the mainstay of electric
traction drives on both electric and diesel-electric locomotives, street-
cars/trams and diesel electric drilling rigs for many years. The
introduction of DC motors and an electrical grid system to run machinery
starting in the 1870s started a new second Industrial Revolution. DC
motors can operate directly from rechargeable batteries, providing the
motive power for the first electric vehicles and today's hybrid cars and
electric cars as well as driving a host of cordless tools. Today DC motors
are still found in applications as small as toys and disk drives, or in large
sizes to operate steel rolling mills and paper machines.
If external power is applied to a DC motor it acts as a DC generator, a
dynamo. This feature is used to slow down and recharge batteries on
hybrid car and electric cars or to return electricity back to the electric grid
used on a street car or electric powered train line when they slow down.
This process is called regenerative braking on hybrid and electric cars. In
diesel electric locomotives they also use their DC motors as generators to
slow down but dissipate the energy in resistor stacks. Newer designs are
adding large battery packs to recapture some of this energy.
Figure 3.2
The above figure shows the workings of a brushed electric motor with a
two-pole rotor (armature) and permanent magnet stator. "N" and "S"
designate polarities on the inside face of the magnets; the outside faces
have opposite polarities. The + and -signs show where the DC current is
applied to the commutator which supplies current to the armature coils.
Figure 3.3
3.4 Speed Measurement of DC Motor
To start with this project, we need a device that will measure the speed of
the motor shaft. There are several methods which can use to measure the
speed of motor. Here, we will only discuss about speed measurement by
using tachometer and encoder.
3.4.1 Speed Measurement of DC Motor using Tachometer
Tachometer is an instrument that measure speed motor based on concept
of back EMF induced in motor when it is running. The EMF is voltages
appear on the commutator segments caused by rotated in the magnetic
field by some external force.
The magnitude of the EMF is given by [3.1],
EMF = KE φ N [3.1]
Where, KE = a constant based on motor construction
φ = magnetic flux
N = speed of motor (in rpm)
The actual relationship between motor speed and EMF follows and is
derived from Equation [3.2],
N= EMF/ KE φ [3.2]
Thus, the motor speed is directly proportional to the EMF voltage ad
inversely proportional to the field flux. For permanent magnet DC motor,
when the EMF measured is increases, the speed of the motor is also
increases with the gain. So, the speed of motor can be measured by
measuring the back EMF using tachometer.
3.4.2 Speed Measurement of DC Motor using Encoder
The best way to measure speed is to fit an optical encoder. This shines a
beam of light from a transmitter across a small space and detects it with a
receiver the other end. If a disc is placed in the space, which has slots cut
into it, then the signal will only be picked up when a slot is between the
transmitter and receiver. As shown in below figure a a disk with number
of slot is placed between a photo transmitter like Infrared LED and photo
detector like photodiode or phototransistor.
The output of photo detector is then given to squaring circuit. This will
have an output which swings to +5v when the light is blocked, and about
0.5 volts when light is allowed to pass through the slots in the disc.
Figure 3.4 Encoder Wheel
The frequency of the output waveform is given by,
= (N * Rpm)/ 60 [3.3]
Where, = frequency of output waveform
Rpm = speed in revolutions per minutes
N = number of slots at disc
So, from Equation 3.3, the speed of DC motor in rpm is given by,
Rpm = * 60 / N [3.4]
3.5 Speed Controlling of DC Motor
For precise speed control of servo system, closed-loop control is
normally used. The speed, which is sensed by analog sensing
devices (e.g., tachometer), is compared with the reference speed
to generate the error signal and to vary the armature voltage of
the motor. There are several controllers that can used to control
the speed of the motor such as by using thyristor, phase-locked-
loop control, chopper circuit, Fuzzy Logic Controller, PWM
technique and etc. Here Speed Control through PWM technique
is discussed.
3.5.1 Speed Control of DC motor using PWM technique
Figure 3.5 Simple Motor Circuit
Let us consider a simple circuit that connects a battery as power supply
through a switch MOSFET (Metal-Oxide-Semiconductor Field Effect
Transistor) as shown in Figure 3.5. When the switch is closed, the motor
sees 12 Volts, and when it is open it sees 0 Volts. If the switch is open for
the same amount of time as it is closed, the motor will see an average of 6
Volts, and will run more slowly accordingly.
This on-off switching is performed by power MOSFETs. A MOSFET
(Metal-Oxide-Semiconductor Field Effect Transistor) is a device that can
turn very large currents on and off under the control of a low signal level
voltage.
The average of voltage that supply to DC motor is given by,
= ( /T ) * [3.5]
Where, = average voltage supply to DC motor
= time ON of switches
T = period of PWM
( /T ) = DC, duty cycle
Figure 3.6 PWM signal and average voltage
As the amount of time that the voltage is on increases compared with the
amount of time that it is off, the average speed of the motor increases and
vice versa.
The time that it takes a motor to speed up and slow down under switching
conditions is depends on the inertia of the rotor (basically how heavy it
is), and how much friction and load torque there is.
If the supply voltage is switched fast enough, it won’t have time to
change speed much, and the speed will be quite steady. This is the
principle of switch mode speed control.
Thus the speed is set by PWM – Pulse Width Modulation.
CHAPTER – 4
L293D MOTOR DRIVER
Now we will discuss the dc motor driver L293D which is basically
driving the dc motor either in clockwise direction or anticlockwise
direction according to the logics which had been provided by the
microcontroller connected to that driver.
Generally, even the simplest robot requires a motor to rotate a wheel or
performs particular action. Since motors require more current then the
microcontroller pin can typically generate, you need some type of a
switch (Transistors, MOSFET, Relay etc.,) which can accept a small
current, amplify it and generate a larger current, which further drives a
motor. This entire process is done by what is known as a motor driver.
Figure 4.1
Motor driver is basically a current amplifier which takes a low-current
signal from the microcontroller and gives out a proportionally higher
current signal which can control and drive a motor. In most cases, a
transistor can act as a switch and perform this task which drives the motor
in a single direction.
Turning a motor ON and OFF requires only one switch to control a single
motor in a single direction. What if we want your motor to reverse its
direction? The simple answer is to reverse its polarity. This can be
achieved by using four switches that are arranged in an intelligent manner
such that the circuit not only drives the motor, but also controls its
direction. Out of many, one of the most common and clever design is a
H-bridge circuit where transistors are arranged in a shape that resembles
the English alphabet "H”.
4.1 H-Bridge Circuit
Figure 4.2 H-Bridge Circuit
As we can see in the image, the circuit has four switches A, B, C and D.
Turning these switches ON and OFF can drive a motor in different ways.
1. Turning on Switches A and D makes the motor rotate clockwise
2. Turning on Switches B and C makes the motor rotate anticlockwise
3. Turning on Switches A and B will stop the motor (Brakes)
4. Turning off all the switches gives the motor a free wheel drive
5. Lastly turning on A & C at the same time or B & D at the same
time shorts your entire circuit. So, do not attempt this.
An H-bridge motor driver IC is used to control the motor. L293D is a 16-
bit IC, with 2-channel motor control or in other words, we can control
and move two motors using this IC both in clockwise and anti-clockwise
direction. Each channel has a separate enable pin, 2 input pins, 2 ground
pins, and 2 output pins.
We will use only one channel. There is one supply voltage pin and a logic
reference voltage pin. Output-1 and output-2 will be plugged to positive
and negative terminal of the DC motor.
Figure 4.3 L293D Driver IC
H-bridges can be built from scratch using relays, MOSFETs, field effect
transistors (FET), bi-polar junction transistors (BJT), etc. But if our
current requirement is not too high and all we need is a single package
which does the job of driving a small DC motor in two directions, then all
we need is a L293D IC. This single inexpensive package can interface not
one, but two DC motors. L293, L293B and few other versions also does
the same job, but pick the L293D version as this one has an inbuilt fly
back diode which protects the driving transistors from voltage spikes that
occur when the motor coil is turned off.
The L293 and L293D are quadruple high-current half-H drivers. The
L293 is designed to provide bidirectional drive currents of up to 1 A at
voltages from 4.5 V to 36 V. The L293D is designed to provide
bidirectional drive currents of up to 600-mA at voltages from 4.5 V to 36
V. Both devices are designed to drive inductive loads such as relays,
solenoids, dc and bipolar stepping motors, as well as other high-
current/high-voltage loads in positive-supply applications.
All inputs are TTL compatible. Each output is a complete totem-pole
drive circuit, with a Darlington transistor sink and a pseudo-Darlington
source. Drivers are enabled in pairs, with drivers 1 and 2 enabled by
1,2EN and drivers 3 and 4 enabled by 3,4EN.When an enable input is
high, the associated drivers are enabled and their outputs are active and in
phase with their inputs. When the enable input is low, those drivers are
disabled and their outputs are off and in the high-impedance state. With
the proper data inputs, each pair of drivers forms a full-H (or bridge)
reversible drive suitable for solenoid or motor applications. On the L293,
external high-speed output clamp diodes should be used for inductive
transient suppression. A VCC1 terminal, separate from VCC2, is
provided for the logic inputs to minimize device power dissipation.
The L293and L293D is characterized for operation from 0°C to 70°C.
4.2 Pin Configuration of L293D DC Motor Driver
Figure 4.4 Pin Diagram
4.3 Pin Description
Enable pins: These are pin no. 1 and pin no. 9. Pin no. 1 is used
to enable Half-H driver 1 and 2 (H bridge on Left side). Pin no. 9 is
used to enable H-bridge driver 3and 4. (H Bridge on right side).
The concept is simple, if you want to use a particular H bridge you
have to give a high logic to corresponding enable pins along with
the power supply to the IC. This pin can also be used to control
speed of the motor using PWM technique.
VCC1 (Pin 16): Power supply pin. Connect it to 5V supply.
VCC2 (Pin 8): Power supply for motor. Apply +ve voltage to it
as per motor rating. If you want to drive your motor at 12V, apply
12V on this pin. It is also possible to drive motor directly on a
battery, other than the one used for supplying power to the circuit,
just connect +ve terminal of that battery to VCC2 pin and make
GND of both the batteries common. (MAX voltage at this pin is
36V).
GND (Pins 4, 5, 12, 13): Connect them to common GND of
circuit.
Inputs (Pins 2, 7, 10, 15): These are input pins through which
control signals are given by microcontrollers or other circuits/ICs.
For example, if on pin 2 (Input of 1st half H driver) we give Logic
1 (5V), we will get a voltage equal to VCC2 on corresponding
output pin of 1st half H driver i.e. pin no. 3. Similarly for Logic 0
(0V) on Pin 2, 0V on Pin 3 appears.
Outputs (Pin 3, 6, 11, 14): Outputs pins. According to input
signal output signal comes.
4.4 L293D Driver Circuit
Figure 4.5 Driver Circuit
OPERATION OF L293d DC MOTOR DRIVER:
CLOCKWISE ROTATION :
INPUT 2 is made low and a PWM signal is generated on INPUT 1 pin.
ANTICLOCKWISE DIRECTION :
INPUT 2 is made high and a PWM is generated on INPUT1 PIN.
There are 2 enable pins on L293dD IC : Pin 1 and pin 9 for being able to
drive the motor. It is like a switch.
For driving the motor with left H-bridge we need to enable pin 1 high and
for right H-bridge you need to make pin 9 high.
Pin 16,Vcc-5 volts supply, for pin 1 and 2 to make them high.
4.5 L293D Logic Table
Let a motor is connected on left side output pins (pin 3, 6)
For rotating the motor in clockwise direction the input pins has to be
provided with logic 1angd logic 0
• Pin 2=logic1 and Pin 7=logic 0 (clockwise direction).
• Pin 2=logic0 and Pin 7=logic 1(anticlockwise direction).
• Pin 2=logic0 and Pin 7=logic 0 (idle).
• Pin 2=logic1 and Pin 7=logic 1 (idle).
Vcc=5 volts for its internal operation.
Vss (V) supply=9 volts.
The maximum Vss motor supply = 36 volts.
Maximum current=600 mA (0.6 amperes).
1A 2A 1Y 2Y Motor 1
Logic 0 Logic 0 0 0 Stop
Logic 1 Logic 0 12 V 0 Clockwise
Logic 0 Logic 1 0 12 V Anticlockwise
Logic 1 Logic 1 12 V 12 V Brake
Table 4.1 Logic Table
This is how the device driver L293D device driver works and how we
have connected the device driver is explained in this chapter in detail.
This driver is also very helpful in our project and it basically provides the
platform that how the speed of dc motor can be controlled in a very
simple way.
CHAPTER – 5
ENCODER
5.1 What is encoder?
An encoder is a device which converts a mechanical information of a
shaft or position into an electrical signal
Figure 5.1
5.2 How is this accomplished?
As the code disc rotates, it shutters light from the LED and is received
and transmitted as square\sine waveforms
Figure 5.2
4.3 Types of Encoder
Rotary
Linear
Now let’s see the difference between them-
ROTARY LINEAR
Convert angular position into Analog or
Digital signal
Convert linear movement to Analog or
Digital signal
Encodes for rotary motion and measuring
angle, speed or velocity
Encodes for measuring distance travelled,
positioning, location.
Table 5.1 Difference between Rotary and Linear Encoder
A shafted rotary encoder is built so that the rotor portion of the encoder is
a short shaft that is usually attached through a flexible coupling to the
shafts of various motion control equipment. The body of the shafted
rotary encoder is commonly fixed by a rigid mounting bracket.
Rotary encoders are used in many applications that require precise shaft
unlimited rotation—including industrial controls, robotics, special
purpose photographic lenses, computer input devices (such as optic
mechanical mice and trackballs), controlled stress rheometers, and
rotating radar platforms.
Figure 5.3
Rotary Encoders are basically of two types
Absolute, and
Incremental (relative).
The output of absolute encoders indicates the current position of the shaft,
making them angle transducers. The output of incremental encoders
provides information about the motion of the shaft, which is typically
further processed elsewhere into information such as speed, distance, and
position.
4.4 Absolute Rotary Encoder
An "absolute" encoder maintains position information when power is
removed from the system. The position of the encoder is available
immediately on applying power. The relationship between the encoder
value and the physical position of the controlled machinery is set at
assembly; the system does not need to return to a calibration point to
maintain position accuracy.
An absolute encoder has multiple code rings with various binary
weightings which provide a data word representing the absolute position
of the encoder within one revolution. This type of encoder is often
referred to as a parallel absolute encoder.
4.4.1 Construction
Digital absolute encoders produce a unique digital code for each distinct
angle of the shaft. They come in two basic types: optical and mechanical
Mechanical absolute encoders: A metal disc containing a set of
concentric rings of openings is fixed to an insulating disc, which is rigidly
fixed to the shaft. A row of sliding contacts is fixed to a stationary object
so that each contact wipes against the metal disc at a different distance
from the shaft. As the disc rotates with the shaft, some of the contacts
touch metal, while others fall in the gaps where the metal has been cut
out. The metal sheet is connected to a source of electric current, and each
contact is connected to a separate electrical sensor. The metal pattern is
designed so that each possible position of the axle creates a unique binary
code in which some of the contacts are connected to the current source
(i.e. switched on) and others are not (i.e. switched off).
Because brush-type contacts are susceptible to wear, encoders using
contacts are not common; they can be found in low-speed applications
such as manual volume or tuning controls in a radio receiver.
Optical absolute encoders : The optical encoder's disc is made of glass
or plastic with transparent and opaque areas. A light source and photo
detector array reads the optical pattern that results from the disc's
position at any one time.This code can be read by a controlling device,
such as a microprocessor or microcontroller to determine the angle of the
shaft.
The absolute analog type produces a unique dual analog code that can be
translated into an absolute angle of the shaft.
4.5 Incremental Rotary Encoder
An incremental rotary encoder provides cyclical outputs (only) when the
encoder is rotated. They can be either mechanical or optical. The
mechanical type requires debouncing and is typically used as digital
potentiometers on equipment including consumer devices. Most modern
home and car stereos use mechanical rotary encoders for volume control.
Due to the fact the mechanical switches require debouncing, the
mechanical type are limited in the rotational speeds they can handle. The
incremental rotary encoder is the most widely used of all rotary encoders
due to its low cost and ability to provide signals that can be easily
interpreted to provide motion related information such as velocity.
The fact that incremental encoders use only two sensors does not
compromise their accuracy. One can find in the market incremental
encoders with up to 10,000 counts per revolution, or more.
There can be an optional third output: reference or "index", which
happens once every turn. This is used when there is the need of an
absolute reference, such as positioning systems. The index output is
usually labelled Z.
The optical type is used when higher speeds are encountered or a higher
degree of precision is required.
Incremental encoders are used to track motion and can be used to
determine position and velocity. This can be either linear or rotary
motion. Because the direction can be determined, very accurate
measurements can be made.
Figure 5.4 Incremental Encoder
4.6 DC Motor with Encoder
Figure 5.5
We are using a dc motor on which encoder is mounted and the
connections are made by connecting the wires to the Arduino board.
Colour of wire Function
Brown Motor power
(connected to one
Motor Terminal)
Blue Motor power
(connected to other
Motor Terminal)
Green Encoder ground
Black Encoder Vcc (5 volts)
Red Encoder A output
Purple Encoder B output
Table 5.2 Wire Functions
CHAPTER – 6
INFRARED SENSORS
6.1 Introduction
An infrared sensor is an electronic instrument that is used
to sense certain characteristics of its surroundings by either
emitting and/or detecting infrared radiation. It is also
capable of measuring heat of an object and detecting
motion. Infrared waves are not visible to the human eye.
In the electromagnetic spectrum, infrared radiation is the
region having wavelengths longer than visible light
wavelengths, but shorter than microwaves. The infrared
region is approximately demarcated from 0.75 to 1000µm.
The wavelength region from 0.75 to 3µm is termed as
near infrared, the region from 3 to 6µm is termed mid-
infrared, and the region higher than 6µm is termed as far
infrared.
Infrared technology is found in many of our everyday
products. For example, TV has an IR detector for
interpreting the signal from the remote control. Key
benefits of infrared sensors include low power
requirements, simple circuitry, and their portable feature.
A wheel speed sensor used with an IR sensor is a type of
tachometer which measures speed with the help of optical
properties. It is a sender device used for reading the speed
of a vehicle's wheel rotation this wheel is embedded over
the shaft of motor and an aluminium strip is places over its
outer surface and when the wheel rotates then the IR
sensor senses the light emitted from this strip and counts
the number of pulses which is nothing but the speed of
motor.
6.2 Types of Infra-Red Sensors
Infra-red sensors are broadly classified into two types:
Thermal infrared sensors – These use infrared energy as heat.
Their photo sensitivity is independent of wavelength. Thermal
detectors do not require cooling; however, they have slow response
times and low detection capability. They have been used
extensively for sensing and detecting purpose.
Figure 6.1 Thermal Infrared Sensor
Quantum infrared sensors – These provide higher detection
performance and faster response speed. Their photo sensitivity is
dependent on wavelength. Quantum detectors have to be cooled so
as to obtain accurate measurements. The only exception is for
detectors that are used in the near infrared region. These sensors
are mainly used for speed detection and control.
6.3 Working Principle
A typical system for detecting infrared radiation using infrared
sensors includes the infrared source such as blackbody radiators,
tungsten lamps, and silicon carbide. In case of active IR sensors,
the sources are infrared lasers and LEDs of specific IR wavelength
Next is the transmission medium used for infrared transmission,
which includes vacuum, the atmosphere, and optical fibers.
Figure 6.2 Basic Design of IR Sensor
Thirdly, optical components such as optical lenses made from
quartz, CaF2, Ge and Si, polyethylene Fresnel lenses, and Al or Au
mirrors, are used to converge or focus infrared radiation.
Likewise, to limit spectral response, band-pass filters are ideal.
Finally, the infrared detector completes the system for detecting
infrared radiation. The output from the detector is usually very
small, and hence pre-amplifiers coupled with circuitry are added
to further process the received signals.
6.4 Applications
The following are the key application areas of infrared sensors:
Tracking and art history
Climatology, meteorology, and astronomy
Thermography, communications, and alcohol testing
Heating, hyper spectral imaging, and night vision
Biological systems, photo bio modulation, and plant health
Gas detectors/gas leak detection
Water and steel analysis, flame detection
Anaesthesiology testing and spectroscopy
Petroleum exploration and underground solution
CHAPTER – 7
PULSE WIDTH MODULATION
Pulse Width Modulation, or PWM, is a technique for getting analog
results with digital means. Digital control is used to create a square wave,
a signal switched between on and off. This on-off pattern can simulate
voltages in between full on (5 Volts) and off (0 Volts) by changing the
portion of the time the signal spends on versus the time that the signal
spends off. The duration of "on time" is called the pulse width. To get
varying analog values, we change, or modulate, that pulse width. If we
repeat this on-off pattern fast enough with an LED for example, the result
is as if the signal is a steady voltage between 0 and 5v controlling the
brightness of the LED.
PWM has several uses:
Dimming an LED
Providing an analog output; if the digital output is filtered,
It will provide an analog voltage between 0% and 100%.
Generating audio signals.
Providing variable speed control for motors.
Generating a modulated signal, for example to drive an infrared
LED for a remote control.
Figure 7.1 PWM Generation
7.1 Principle
Pulse-width modulation uses a rectangular pulse wave whose pulse width
is modulated resulting in the variation of the average value of the
waveform. If we consider a pulse waveform f(t), with period T, low value
y_{min}, a high value y_{max} and a duty cycle D, the average value of
the waveform is given by:
∫ ( )
As f(t) is a pulse wave, its value is y_{max} for 0<t<D. T and y_{min}
for D.T <t<T. The above expression then becomes:
(∫
∫
)
= ( )
= + (1 - D)
This latter expression can be fairly simplified in many cases where
y_{min}=0 as =D. y_{max}. From this, it is obvious that the average
value of the signal ( ) is directly dependent on the duty cycle D.
A simple method to generate the PWM pulse train corresponding to a
given signal is the intersective PWM: the signal (sine wave) is compared
with a saw tooth waveform. When the latter is less than the former, the
PWM signal (magenta) is in high state (1). Otherwise it is in the low state
(0). When the value of the reference signal is more than the modulation
waveform, the PWM signal (magenta) is in the high state, otherwise it is
in the low state.
7.2 Applications of PWM :
Telecommunications: In telecommunications, PWM is a form of
signal modulation where the widths of the pulses correspond to
specific data values encoded at one end and decoded at the other.
Pulses of various lengths (the information itself) will be sent at
regular intervals (the carrier frequency of the modulation).
Figure 7.2
Voltage regulation: PWM is also used in efficient voltage
regulators. By switching voltage to the load with the appropriate
duty cycle, the output will approximate a voltage at the desired
level. The switching noise is usually filtered with an inductor and a
capacitor.
One method measures the output voltage. When it is lower than the
desired voltage, it turns on the switch. When the output voltage is
above the desired voltage, it turns off the switch.
Audio effects and amplification: PWM is sometimes used in
sound (music) synthesis, in particular subtractive synthesis, as it
gives a sound effect similar to chorus or slightly detuned oscillators
played together. (In fact, PWM is equivalent to the difference of
two saw tooth waves with one of them inverted.) The ratio between
the high and low level is typically modulated with a low frequency
oscillator. In addition, varying the duty cycle of a pulse waveform
in a subtractive-synthesis instrument creates useful tumbrel
variations. Some synthesizers have a duty-cycle trimmer for their
square-wave outputs, and that trimmer can be set by ear; the 50%
point (true square wave) was distinctive, because even-numbered
harmonics essentially disappear at 50%. Pulse waves, usually 50%,
25%, and 12.5%, make up the soundtracks of classic video games.
A new class of audio amplifiers based on the PWM principle is
becoming popular. Called "Class-D amplifiers", they produce a
PWM equivalent of the analog input signal which is fed to the
loudspeaker via a suitable filter network to block the carrier and
recover the original audio. These amplifiers are characterized by
very good efficiency figures (≥ 90%) and compact size/light weight
for large power outputs. For a few decades, industrial and military
PWM amplifiers have been in common use, often for driving servo
motors. Field-gradient coils in MRI machines are driven by
relatively high-power PWM amplifiers.
Electrical: SPWM (Sine–triangle pulse width modulation) signals
are used in micro-inverter design (used in solar or wind power
applications). These switching signals are fed to the FETs that are
used in the device. The device's efficiency depends on the
harmonic content of the PWM signal. There is much research on
eliminating unwanted harmonics and improving the fundamental
strength, some of which involves using a modified carrier signal
instead of a classic saw tooth signal in order to decrease power
losses and improve efficiency. Another common application is in
robotics where PWM signals are used to control the speed of the
robot by controlling the motors.
7.3 Modes of Operation
The different modes of operation are given as following :
Normal mode
Clear timer on compare(CTC) match mode
Phase correct PWM mode
Fast PWM mode
7.3.1 Normal Mode
The simplest mode of operation is the Normal mode (WGM01:0).In this
mode the counting direction is always up(incrementing),and no counter
clear is performed. The counter simply overruns when it passes its
maximum bit value(TOP=0xFF) and then restarts from the
bottom(0x00).In normal operation the timer/Counter Overflow
Flag(TOV0) will be set in the same timer clock cycle as the TCNT0
becomes zero. The TOV0 Flag in the case behaves like a ninth bit, except
that it is only set, not cleared. However, combined with the Timer
Overflow interrupt that automatically clears the TOv0 flag, the timer
resolution can be increased by software. The output compare unit can be
used to generate interrupts at some given time. Using the output compare
to generate waveforms in Normal mode is not recommended, since this
will occupy too much of the CPU time.
7.3.2 CTC Mode
In Clear Timer on compare or CTC mode (WGM01:0=2), the OCRO
register is used to manipulate the counter resolution. In CTC mode the
counter is cleared to zero when the counter value(TCNT0) matches the
OCR0.The ORC0 defines the top value for the counter, hence also its
resolution. This mode allows greater control of the Compare Match
output frequency. It also simplifies the operation of counting external
events. The counter value (TCNT0) increases until a Compare Match
occurs between TCNT0 and OCR0 and then counter (TCNT0) is cleared.
An interrupt can be generated each time the counter value reaches the
TOP value by using the OCF0 flag. If the interrupt is enabled, the
interrupt handler routine can be used for updating the TOP value.
However, changing TOP to a value close to BOTTOM when the counter
is running with none or a low presale value must be done with care since
the CTC modes does not have the double buffering feature. If the new
value written to ORC0 is lower than the current value of TCNT0, the
counter will miss the Compare Match. The counter will then have to
count to its maximum value (0xFF) and wrap around starting at 0x00
before the Compare Match can occur. For generating a waveform output
in CTC mode, the OC0 output can be set to toggle its logical level on
each Compare Match by setting the Compare Output mode bits to toggle
mode(COM01:0=1).The OC0 value will not be visible on the port pin
unless the data direction for the pin is set to output. The waveform
generated will have maximum frequency of fOC0=f_I/O/2 when OCR0 is
set to zero (0x00).
7.3.3 Fast PWM Mode
The fast PWM mode provides high frequency PWM wave for generation
options. The fast PWM differs from other PWM options by its single
slope operation. The counter counts from BOTTOM to maximum the
starts from bottom .In non-inverting compare output mode; the output
compare (OC0) is cleared on the compare match between TCNT0 and
OCR0, and set at BOTTOM.
In inverting compare output mode, the output is set on compare match
and cleared at BOTTOM. Due to single slope operation, the operating
frequency of fast PWM can be twice as high as phase correct PWM mode
that uses dual slope operation. This high frequency makes the fast PWM
well suited for power regulation, rectification and DAQ applications.
High frequency allows physically small sized external components (coils,
capacitors), and therefore reduces total system cost. In fast PWM mode,
the counter is incremented until the counter value matches the MAX
value. The counter is then cleared at the following timer clock cycle.
The Timer/Counter overflow flag(TOV0) is set each time the counter
reaches MAX. If the interrupt enabled, the interrupt handler routine can
be used for updating the compare value. In fast PWM mode, the compare
unit allows generation of PWM waveforms on the OC0 pin. Setting the
COM01:0 bits to two will produce a non-inverted PWM and an inverted
PWM output can be generated by setting the COM01:0 to three. The
actual OC0 value only be visible on the port pin is set as output. The
PWM waveform is generated by setting (or clearing) the OC0 register at
the Compare Match between OCR0 and TCNT0 and clearing (or setting)
the OC0 Register at the timer clock cycle the counter is cleared (changes
from MAX to BOTTOM.
7.3.4 Phase Correct PWM
The phase correct PWM mode (WGM01:0) provides a high resolution
phase correct PWM waveform generation option. The phase correct
PWM mode is based on a dual slope operation. The counter counts
repeatedly from BOTTOM to MAX and then from MAX to BOTTOM.
In non-inverting Compare output mode, the output compare (OC0) is
cleared on the compare match between TCNT0 and OCR0 while up-
counting, and set on the compare match while down-counting. In
inverting Output compare mode, the operation is inverted. The dual slope
operation has lower maximum operation frequency than single slope
operation. However, due to the symmetric feature of the dual-slope PWM
modes, these modes are preferred for motor control applications.
CHAPTER – 8
ARDUINO UNO
The Arduino Uno is a microcontroller board based on the ATmega328. It
has 14 digital input/output pins (of which 6 can be used as PWM
outputs), 6 analog inputs, a 16 MHz ceramic resonator, a USB
connection, a power jack, an ICSP header, and a reset button. It contains
everything needed to support the microcontroller; simply connect it to a
computer with a USB cable or power it with a AC-to-DC adapter or
battery to get started.
The Uno differs from all preceding boards in that it does not use the FTDI
USB-to-serial driver chip. Instead, it features the Atmega16U2
(Atmega8U2 up to version R2) programmed as a USB-to-serial converter.
"Uno" means one in Italian and is named to mark the upcoming release
of Arduino 1.0. The Uno and version 1.0 will be the reference versions of
Arduino, moving forward. The Uno is the latest in a series of USB
Arduino boards.
Figure 8.1 Arduino Uno R3 Front Side
8.1 Summary
Microcontroller ATmega328
Operating Voltage 5V
Input Voltage
(recommended)
7-12V
Input Voltage (limits) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6
DC Current per I/O Pin 40 mA
DC Current for 3.3V Pin 50 mA
Flash Memory 32 KB (ATmega328) of which 0.5 KB used by boot loader
SRAM 2 KB (ATmega328)
EEPROM 1 KB (ATmega328)
Clock Speed 16 MHz
8.2 Power
The Arduino Uno can be powered via the USB connection or with an
external power supply. The power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter
(wall-wart) or battery. The adapter can be connected by plugging a
2.1mm center-positive plug into the board's power jack. Leads from a
battery can be inserted in the Gnd and Vin pin headers of the POWER
connector.
The board can operate on an external supply of 6 to 20 volts. If supplied
with less than 7V, however, the 5V pin may supply less than five volts
and the board may be unstable. If using more than 12V, the voltage
regulator may overheat and damage the board. The recommended range is
7 to 12 volts.
The power pins are as follows:
VIN - The input voltage to the Arduino board when it's using an
external power source (as opposed to 5 volts from the USB
connection or other regulated power source). You can supply
voltage through this pin, or, if supplying voltage via the power
jack, access it through this pin.
5V - This pin outputs a regulated 5V from the regulator on the
board. The board can be supplied with power either from the DC
power jack (7 - 12V), the USB connector (5V), or the VIN pin of
the board (7-12V). Supplying voltage via the 5V or 3.3V pins
bypasses the regulator, and can damage your board. We don't
advise it.
3V3 - A 3.3 volt supply generated by the on-board regulator.
Maximum current draw is 50 mA.
GND - Ground pins.
IOREF - This pin on the Arduino board provides the voltage
reference with which the microcontroller operates. A properly
configured shield can read the IOREF pin voltage and select the
appropriate power source or enable voltage translators on the
outputs for working with the 5V or 3.3V.
8.3 Memory
The ATmega328 has 32 KB (with 0.5 KB used for the bootloader). It also
has 2 KB of SRAM and 1 KB of EEPROM (which can be read and
written with the EEPROM library).
8.4 Input and Output
Each of the 14 digital pins on the Uno can be used as an input or output,
using pinMode(), digitalWrite(), and digitalRead() functions. They
operate at 5 volts. Each pin can provide or receive a maximum of 40 mA
and has an internal pull-up resistor (disconnected by default) of 20-50
kohms. In addition, some pins have specialized functions:
Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX)
TTL serial data. These pins are connected to the corresponding
pins of the ATmega8U2 USB-to-TTL Serial chip.
External Interrupts: 2 and 3. These pins can be configured to
trigger an interrupt on a low value, a rising or falling edge, or a
change in value.
PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the
analogWrite() function.
SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins
support SPI communication using the SPI library.
LED: 13. There is a built-in LED connected to digital pin 13.
When the pin is HIGH value, the LED is on, when the pin is LOW,
it's off.
The Uno has 6 analog inputs, labelled A0 through A5, each of which
provide 10 bits of resolution (i.e. 1024 different values). By default they
measure from ground to 5 volts, though is it possible to change the upper
end of their range using the AREF pin and the analogReference()
function. Additionally, some pins have specialized functionality:
TWI: A4 or SDA pin and A5 or SCL pin. Support TWI
communication using the Wire library.
There are a couple of other pins on the board:
AREF: Reference voltage for the analog inputs. Used with
analogReference().
Reset: Bring this line LOW to reset the microcontroller. Typically
used to add a reset button to shields which block the one on the
board.
8.5 Communication
The Arduino Uno has a number of facilities for communicating with a
computer, another Arduino, or other microcontrollers. The ATmega328
provides UART TTL (5V) serial communication, which is available on
digital pins 0 (RX) and 1 (TX). An ATmega16U2 on the board channels
this serial communication over USB and appears as a virtual com port to
software on the computer. The '16U2 firmware uses the standard USB
COM drivers, and no external driver is needed. However, on Windows, a
.inf file is required. The Arduino software includes a serial monitor which
allows simple textual data to be sent to and from the Arduino board. The
RX and TX LEDs on the board will flash when data is being transmitted
via the USB-to-serial chip and USB connection to the computer (but not
for serial communication on pins 0 and 1).
A Software Serial library allows for serial communication on any of the
Uno's digital pins.
The ATmega328 also supports I2C (TWI) and SPI communication. The
Arduino software includes a Wire library to simplify use of the I2C bus
8.6 Programming
The Arduino Uno can be programmed with the Arduino software
(download). Select "Arduino Uno from the Tools > Board menu
(according to the microcontroller on your board).
The ATmega328 on the Arduino Uno comes preburned with a bootloader
that allows you to upload new code to it without the use of an external
hardware programmer. It communicates using the original STK500
protocol (reference, C header files).
We can also bypass the bootloader and program the microcontroller
through the ICSP (In-Circuit Serial Programming) header.
The ATmega16U2 (or 8U2 in the rev1 and rev2 boards) firmware source
code is available. The ATmega16U2/8U2 is loaded with a DFU
bootloader, which can be activated by:
On Rev1 boards: connecting the solder jumper on the back of the
board (near the map of Italy) and then resetting the 8U2.
On Rev2 or later boards: there is a resistor that pulling the
8U2/16U2 HWB line to ground, making it easier to put into DFU
mode.
We can then use Atmel's FLIP software (Windows) or the DFU
programmer (Mac OS X and Linux) to load a new firmware. Or we can
use the ISP header with an external programmer (overwriting the DFU
bootloader).
8.7 USB Overcurrent Protection
The Arduino Uno has a resettable polyfuse that protects your computer's
USB ports from shorts and overcurrent. Although most computers
provide their own internal protection, the fuse provides an extra layer of
protection. If more than 500 mA is applied to the USB port, the fuse will
automatically break the connection until the short or overload is removed.
8.8 Physical Characteristics
The maximum length and width of the Uno PCB are 2.7 and 2.1 inches
respectively, with the USB connector and power jack extending beyond
the former dimension. Four screw holes allow the board to be attached to
a surface or case. Note that the distance between digital pins 7 and 8 is
160 mil (0.16"), not an even multiple of the 100 mil spacing of the other
pins.
CHAPTER – 9
PWM GENERATION USING ARDUINO
9.1 Secrets of Arduino PWM
Pulse-width modulation (PWM) can be implemented on the Arduino in
several ways. This article explains simple PWM techniques, as well as
how to use the PWM registers directly for more control over the duty
cycle and frequency. This article focuses on the Arduino models, which
use the ATmega168 or ATmega328.
Briefly, a PWM signal is a digital square wave, where the frequency is
constant, but that fraction of the time the signal is on (the duty cycle) can
be varied between 0 and 100%.
Figure 9.1 PWM generation with different duty cycle
9.2 Simple Pulse Width Modulation with analogWrite
The Arduino's programming language makes PWM easy to use; simply
call analogWrite(pin, dutyCycle), where dutyCycle is a value from 0 to
255, and pin is one of the PWM pins (3, 5, 6, 9, 10, or 11). The
analogWrite function provides a simple interface to the hardware PWM,
but doesn't provide any control over frequency. (Note that despite the
function name, the output is a digital signal, often referred to as a square
wave.)
Probably 99% of the users can stop here, and just use analogWrite, but
there are other options that provide more flexibility.
9.3 Bit-banging Pulse Width Modulation
We can "manually" implement PWM on any pin by repeatedly turning
the pin on and off for the desired times. e.g.
void setup()
{
pinMode(13, OUTPUT);
}
void loop()
{
digitalWrite(13, HIGH);
delayMicroseconds(100); // Approximately 10% duty cycle @1KHz
digitalWrite(13, LOW);
delayMicroseconds(1000 - 100);
}
This technique has the advantage that it can use any digital output pin. In
addition, we have full control the duty cycle and frequency.
One major disadvantage is that any interrupts will affect the timing,
which can cause considerable jitter unless you disable interrupts.
A second disadvantage is we can't leave the output running while
the processor does something else.
Finally, it's difficult to determine the appropriate constants for a particular
duty cycle and frequency unless you either carefully count cycles, or
tweak the values while watching an oscilloscope.
9.4 Using the ATmega PWM registers directly
The ATmega328P chip has three PWM timers, controlling 6 PWM
outputs. By manipulating the chip's timer registers directly, you can
obtain more control than the analogWrite function provides.
9.5 The Atmega 328 timers:
The ATmega328P has three timers known as Timer 0, Timer 1, and
Timer 2. Each timer has two output compare registers that control the
PWM width for the timer's two outputs: when the timer reaches the
compare register value, the corresponding output is toggled. The two
outputs for each timer will normally have the same frequency, but can
have different duty cycles (depending on the respective output compare
register).
Each of the timers has a prescaler that generates the timer clock by
dividing the system clock by a prescale factor such as 1, 8, 64, 256, or
1024. The Arduino has a system clock of 16MHz and the timer clock
frequency will be the system clock frequency divided by the prescale
factor. Note that Timer 2 has a different set of prescale values from the
other timers.
The timers are complicated by several different modes. The main PWM
modes are "Fast PWM" and "Phase-correct PWM", which will be
described below. The timer can either run from 0 to 255, or from 0 to a
fixed value. (The 16-bit Timer 1 has additional modes to supports timer
values up to 16 bits.) Each output can also be inverted.
The timers can also generate interrupts on overflow and/or match against
either output compare register, but that's beyond the scope of this article.
Timer Registers Several registers are used to control each timer. The
Timer/Counter Control Registers TCCRnA and TCCRnB hold the main
control bits for the timer. (Note that TCCRnA and TCCRnB do not
correspond to the outputs A and B.) These registers hold several groups
of bits:
Waveform Generation Mode bits (WGM): these control the overall
mode of the timer.(These bits are split between TCCRnA and
TCCRnB.)
Clock Select bits (CS): these control the clock prescaler
Compare Match Output A Mode bits (COMnA): these
enable/disable/invert output A
Compare Match Output B Mode bits (COMnB): these
enable/disable/invert output B
The Output Compare Registers OCRnA and OCRnB set the levels at
which outputs A and B will be affected. When the timer value matches
the register value, the corresponding output will be modified as specified
by the mode.
The bits are slightly different for each timer. Timer 1 is a 16-bit timer and
has additional modes. Timer 2 has different prescaler values.
9.6 Fast PWM
In the simplest PWM mode, the timer repeatedly counts from 0 to 255.
The output turns on when the timer is at 0, and turns off when the timer
matches the output compare register. The higher the value in the output
compare register, the higher the duty cycle. This mode is known as Fast
PWM Mode. There are two outputs for two particular values of OCRnA
and OCRnB. Note that both outputs have the same frequncy, matching
the frequency of a complete timer cycle.
9.7 Fast PWM Mode
The following code fragment sets up fast PWM on pins 3 and 11 (Timer
2). To summarize the register settings, setting the waveform generation
mode bits WGM to 011 selects fast PWM. Setting the COM2A bits and
COM2B bits to 10 provides non-inverted PWM for outputs A and B.
Setting the CS bits to 100 sets the prescaler to divide the clock by 64.
(Since the bits are different for the different timers, consult the datasheet
for the right values.) The output compare registers are arbitrarily set to
180 and 50 to control the PWM duty cycle of outputs A and B. (Of
course, you can modify the registers directly instead of using pinMode,
but you do need to set the pins to output.)
pinMode(3, OUTPUT);
pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) |
_BV(WGM20);
TCCR2B = _BV(CS22);
OCR2A = 180;
OCR2B = 50;
On the Arduino, these values yield:
Output A frequency: 16 MHz / 64 / 256 = 976.5625Hz
Output A duty cycle: (180+1) / 256 = 70.7%
Output B frequency: 16 MHz / 64 / 256 = 976.5625Hz
Output B duty cycle: (50+1) / 256 = 19.9%
The output frequency is the 16MHz system clock frequency, divided by
the prescaler value (64), divided by the 256 cycles it takes for the timer to
wrap around. Note that fast PWM holds the output high one cycle longer
than the compare register value.
9.8 Phase-Correct PWM
The second PWM mode is called phase-correct PWM. In this mode, the
timer counts from 0 to 255 and then back down to 0. The output turns off
as the timer hits the output compare register value on the way up, and
turns back on as the timer hits the output compare register value on the
way down. The result is a more symmetrical output. The output
frequency will be approximately half of the value for fast PWM mode,
because the timer runs both up and down.
Example:
The following code fragment sets up phase-correct PWM on pins 3 and
11 (Timer 2). The waveform generation mode bits WGM are set to to 001
for phase-correct PWM. The other bits are the same as for fast PWM.
pinMode(3, OUTPUT);
pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
TCCR2B = _BV(CS22);
OCR2A = 180;
OCR2B = 50;
On the Arduin, these values yield:
Output A frequency: 16 MHz / 64 / 255 / 2 = 490.196Hz
Output A duty cycle: 180 / 255 = 70.6%
Output B frequency: 16 MHz / 64 / 255 / 2 = 490.196Hz
Output B duty cycle: 50 / 255 = 19.6%
Phase-correct PWM divides the frequency by two compared to fast
PWM, because the timer goes both up and down. Somewhat surprisingly,
the frequency is divided by 255 instead of 256, and the duty cycle
calculations do not add one as for fast PWM. See the explanation below
under "Off-by-one".
CHAPTER – 10
CONCLUSION AND FUTURE SCOPE
With the very basic concept of PWM, H-bridge and ARDUINO, the
direction and the speed of the motor can be controlled. It is practical and
highly feasible method according to economic point of view, reliability
and accuracy. It is programmable one therefore it can control various
motors.
The speed sensing is done using encoder and proximity IR sensor and the
controlling is done using LabVIEW interface for ARDUINO (LIFA).
The thesis provides a cost effective means of employing powerful
programming tool for various applications using prototyping board
ARDUINO. The potential of this method will be extended for various
other engineering applications in the near future.
10.1 Applications
Because the hardware required is low cost and general user
protocols potential applications is limited to the user.
In educational institutions this apparatus can be modified to
function as a Remote Virtual Lab.
Small scale industries can employ this method of control if
accuracy and speed is of less importance (since Arduino
microcontroller has certain limitations over speed i.e. clock
frequency)
In a large scale farming for collecting data from hundreds of
sensors like temperature and humidity sensors and then taking
collective decision over a period of time for control action like
sprinkler operation, can be implemented effectively and
economically using Arduino and LabVIEW.
Easy to assemble because of its constitution of modules and hence
it is able to run on different platforms and therefore it has a lot of
scope in the home automation system
It is possible to control the motor in both the directions so the data
can be transmitted in serial / parallel form using USB so it has its
application in wireless telecommunication networks.
10.2 Future Scope
Arduino is a type of special purpose microprocessor that has replaced
many hardware components such as timers and drum sequencers used
in relay logic. So with the help of this type of controller for DC machines
various industrial needs could be fulfilled which requires feedback and
control action.
The DC motor controller which has been developed is an extensive tool
for the automation system which is practiced in practically type of
manufacturing and assembly process. Some of the larger processes
include electrical power generation, oil refining, chemicals, steel mills,
plastics, cement plants, fertilizer plants, pulp and paper mills, automobile
and truck assembly, aircraft production, glass manufacturing, natural
gas separation plants.