full report
-
Upload
vinod-singh -
Category
Documents
-
view
368 -
download
3
Transcript of full report
ABSTRACT
D.C motor control is very common in robotic application. The developments of this
kind of project are widely used in most electronic devices nowadays. There are many
application that have been developed based on motor control in electronic field such as in
automation, Flexible Manufacturing System (FMS) and Computer Integrated Manufacturing
(CIM). The purpose of this project is to develop the Graphical User Interface of Motor
Control through MATLAB GUIDE, interface the MATLAB GUI with hardware via
communication port and control the stepper or dc motor through MATLAB GUI. By using
MATLAB GUIDE, it provides a set of tools which simplify the process of laying out and
programming GUIs and interface with PIC via serial communication port to control the
stepper motor. The PIC is used to control motor. As a result, the DC motor is able to be
controlled through MATLAB GUI and interface the MATLAB GUI with PIC via serial
communication port.
1
CHAPTER -1
INTRODUCTION
1.1 Overview
`The serial port found on the back of the most PC and it is extremely useful for robotics
work. Variety devices are configured to communicate via a serial port. This Project is focus on
designing the Graphical User Interface (GUI) through MATLAB to control the dc motor using
PIC. The PIC is a programmable interface devices or controller between PC (MATLAB GUI) and
the dc motor. The main contribution of this project is the interfacing of the MATLAB with PIC
and Graphical User Interface (GUI).The Peripheral Interface Controller (PIC) use in this project
is as controller device between Personal Computer and the dc motor to control dc motor. The
PIC is use because of wide availability and economical. Beside that PIC is a free development
tools and can perform many function without needed extra circuitry. The PIC is programmed
using the MPLAB Compiler. The MPLAB IDE software produces code that may be programmed
into a wide variety of PICmicro 2 microcontrollers having from 8 to 84 pins and various on-chip
features including A/D converters, hardware timers and serial ports. The purpose using
MATLAB in creating the GUI is because it already has Graphical User Interface Development
Environment (GUIDE) that provides a set of tools for creating GUI. These tools simplify the
process of laying out and programming GUIs. The GUI create in MATLAB with appropriate
coding will control the motor via serial port that interface with the PIC. There are many
advantage by using the motor, among that the dc motor has no adverse effect on power quality
and the speed is proportional to the magnetic flux.
2
1.2 ObjectiveAt the end of this Project:
i. Able to control motor through MATLAB GUI.
ii. Able to interface the MATLAB GUI with hardware using PIC.
The important part of this project is to interface the MATLAB GUI with the PIC. This part is
done if the PIC produces a signal. After that the motor can be control via MATLAB GUI.
1.3 Scope of ProjectThe scopes of this project are laying out the GUI in MATLAB GUIDE and create
programming for the GUI’s. Secondly Prepare the PIC circuitry and serial 3 connection
(DB9) circuit for interfacing part. And the third part is creating program for PIC using
MPLAB IDE to control the motor.
1.4 Problem StatementThe main objective in this project to interface the MATLAB GUI with the PIC. It is a
difficult part to develop the program for MATLAB and the PIC simultaneously to make the
interfacing part. By using the MPLAB IDE software to develop programming to control
motor, it can reduces the difficulty by comprises a list of statements that written in a
programming language like assembler, C, or BASIC. With this opportunity, the men in
charge do not have to take long time to written and troubleshoot the program.
3
CHAPTER -2
LITRATURE REVIEW
Matlab is matrix-based software for scientific and engineering numeric computation
and visualization. Matlab is chosen as the programming tool primarily a Graphical Use
because of simple GUIs, immediate graphics facilities, built-in functions, the possibility of
adding user-written functions, interactive mode of work, simple programming and its wide
availability on computing platforms. These factors make Matlab a powerful tool for research
and practical problem solving . Matlab implements GUI through GUIDE. A GUI is a user
interface program built with graphical objects such as buttons, text fields, sliders and menus.
In fact, these definitions are well known for almost all computer users. Applications that
provide GUIs are generally easier to learn and use since the person using the application does
not need to know what commands are available or how to use them. GUIs assure the
communication process between the user and the system’s inference engine . The serial port
of a PC is used to drive dc motors . The PC's serial port is a simple and inexpensive tool for
building computer controlled devices and projects. It is an 8-bit bidirectional interface
designed to transmit data synchronously using RS232 signal level. RS232 outputs can source
2.6 mA and sink 24 mA. Thus, small-size DC motors can be driven from a PC’s serial port
with a simple interface circuit containing a RS232 to TTL logic converter. Almost all
programming languages allow programmers to access serial port using some library
functions. Matlab program also has some useful library functions such as digitalio, addline,
4
CHAPTER-3
GUI
3.1 Graphical User Interface (GUI)
3.1.1 General Definition of GUIA graphical user interface (or GUI, often pronounced "gooey"), is a particular case
of user interface for interacting with a computer which employs graphical images and widgets
in addition to text to represent the information and actions available to the user . Usually the
actions are performed through direct manipulation of the graphical elements.The first
graphical user interface was designed by Xerox Corporation's Palo Alto Research Center in
the 1970s, but it was not until the 1980s and the emergence of the Apple Macintosh that
graphical user interfaces became popular. One reason for their slow acceptance was the fact
that they require considerable CPU power and a high-quality monitor, which until recently
were prohibitively expensive A graphical user interface (GUI) is a pictorial interface to a
program. A good GUI can make programs easier to use by providing them with a consistent
appearance and with intuitive controls like pushbuttons, list boxes, sliders, menus, and so
forth . A true GUI includes standard formats for representing text and graphics . The GUI
should behave in an understandable and predictable manner, so that a user knows what to
expect when he or she performs an action. For example, when a mouse click occurs on a
pushbutton, the GUI should initiate the action described on the label of the button. Many
DOS programs include some features of GUIs, such as menus, but are not graphics based.
Such interfaces are sometimes called graphical character-based user interfaces to distinguish
them from true GUIs .
3.1.2 MATLAB GUIA graphical user interface (GUI) is a graphical display that contains devices, or
components, that enable a user to perform interactive tasks. To perform these tasks, the user
of the GUI does not have to create a script or type commands at the command line. Often, the
user does not have to know the details of the task at hand. The GUI components can be
menus, toolbars, push buttons, radio buttons, list boxes, and sliders — just to name a few. In
5
MATLAB, a GUI can also display data in tabular form or as plots, and can group related
components .
3.1.3 Operation of GUIEach component, and the GUI itself, is associated with one or more userwritten
routines known as callbacks. The execution of each callback is triggered by a particular user
action such as, mouse click, pushbuttons, toggle buttons, lists, menus, text boxes, selection of
a menu item, or the cursor passing over a component and so forth . Clicking the button
triggers the execution of a callback. A mouse click or a key press is an event, and the
MATLAB program must respond to each event if the program is to perform its function. For
example, if a user clicks on a button, that event must cause the MATLAB code that
implements the function of the button to be executed. The code executed in response to an
event is known as a callback.This kind of programming is often referred to as event-driven
programming. The event in the example is a button click. In event-driven programming,
callback execution is asynchronous, controlled by form of user interactions with the GUI. The
writer of a callback has no control over the sequence of events that leads to its execution or,
when the callback does execute, what other callbacks might be running simultaneously .
Callbacks
• Routine that executes whenever you activate the uicontrol object
• Define this routine as a string that is a valid MATLAB expression or the
name of an M-file
• The expression executes in the MATLAB workspace.
3.1.4 A brief introduction of GUIDE
GUIDE, the MATLAB graphical user interface development environment, provides a
set of tools for creating graphical user interfaces (GUIs). These tools simplify the process of
laying out and programming GUIs .
• GUIDE is primarily a set of layout tools
• GUIDE also generates an M-file that contains code to handle the initialization and
launching of
6
the GUI – This M-file also provides a framework for the implementation of the callbacks -
the
functions that execute when users activate a component in the GUI.
3.1.4.1 Two Basic Task in Process of implementing a GUI
The two basic tasks in Process of implementing a GUI is first, laying out a GUI where
MATLAB implement GUIs as figure windows containing various styles of uicontrol (User
Interface) objects. The second task is programming the GUI, where each object must be
program to perform the intended action when activated by the user of GUI.
3.2.1 Development MATLAB GUI Using MATLAB GUIDEGUIDE, the MATLAB graphical user interface development environment, provides a
set of tools for creating graphical user interfaces (GUIs). These tools simplify the process of
laying out and programming GUIs.There are 5 steps in build the MATLAB GUI. First Use a
MATLAB tool called guide (GUI Development Environment) to layout the components that
show in figure 3.1. This tool allows a programmer to layout the GUI, selecting and aligning
the GUI components to be placed in it.
7
Figure 3.1 Matlab guide layout
Next is Use a MATLAB tool called the Property Inspector (built into guide) to give each
component a name (a "tag") and to set the characteristics of each component, such as its
color, the text it displays, and so on. After that, save the figure to a file. When the figure is
saved, two files will be created on disk with the same name but different extents. The fig file
contains the actual GUI that has been created, and the M-file contains the code to load the
figure and skeleton callbacks for each GUI element. These two files usually reside in the
same directory. They correspond to the tasks of laying out and programming the GUI. When
you lay out the GUI in the Layout Editor, your work is stored in the FIG-file. When you
program the GUI, your work is stored in the corresponding M-file.
8
Figure 3.2: Property inspector
9
Table 3.1: Basic MATLAB GUI Component
After laying out the GUI component and set the property, the GUI will belook like in figure
3.4 for example according to the user creativity.
10
Figure 3.3: Example GUI
And finally write code to implement the behavior associated with each callback function in
m-files show in figure 3.5. A callback is a function that writes and associates with a specific
GUI component or with the GUI figure. It controls GUI or component behavior by
performing some action in response to an event for its component. This kind of programming
is often called event-driven programming. This last step is the difficult one and has to make
an extra reading on how to write the coding before the GUI component can perform some
task that user desire.
11
Figure 3.4: Example M-files for GUI
3.2.2 Build MATLAB Programming
After layed out the GUI, it need to program its behavior. The code is to write controls
how the GUI responds to events such as button clicks, slider movement, menu item selection,
or the creation and deletion of components. This programming takes the form of a set of
functions, called callbacks, for each component and for the GUI figure itself. A callback is a
function that writes and associates with a specific GUI component or with the GUI figure. It
controls GUI or component behavior by performing some action in response to an event for
its component. This kind of programming is often called event-driven programming. The
GUI figure and each type of component have specific kinds of callbacks with which it can be
associated. The callbacks that are available for each component are defined as properties of
that component. Each kind of callback has a triggering mechanism or event that causes it to
be called. The kind of callback is shown in table.
Table 3.2: Kind of Callback
Callback Property Triggering Event Components
12
DeleteFcn Component deletion. Itcan be used to performcleanup operations justbefore the component orfigure is destroyed
Axes, figure, buttongroup,context menu, menu,panel,user interface
controls
KeyPressFcn Executes when the userpresses a keyboard keyand the callback’scomponent or figure hasfocus.
Figure, user interfacecontrols
ResizeFcn
SelectionChangeFcn
Executes when a userresizes a panel, buttongroup, or figure whosefigure. Resize property isset to On.Executes when a userselects a different radiobutton or toggle button ina button groupcomponent.
Button group, figure,Panel
Button group
WindowButtonDownFcn Executes when you pressa mouse button while thepointer is in the figurewindow.
Figure
13
WindowButtonMotionFc
n
Executes when you movethe pointer within thefigure window.
Figure
WindowButtonUpFcn Executes when yourelease a mouse
button
Figure
ButtonDownFcn Executes when the userpresses a mouse buttonwhile the pointer is on orwithin five pixels of acomponent or figure. Ifthe component is a userinterface control, itsEnable property must
be on
Axes, figure, buttongroup, panel, userinterface controls
Callback Component action.Executes, for example,when a user clicks a pushbutton or selects a
menu item
Context menu, menu, userinterface controls
CloseRequestFcn
CreateFcn
Executes before the figurecloses.Component creation. Itcan be use to initialize thecomponent when it iscreated. It executes
Figure
Axes, figure, buttongroup, context menu,menu,panel, user interfacecontrols
14
afterthe component or figure iscreated, but before it isdisplayed
CHAPTER-4
CALLBACK FUNCTIONS
4.1 GUIDE Callback Arguments
All callbacks in a GUIDE-generated GUI code file have the following standard input
arguments:
hObject — Handle of the object, e.g., the GUI component, for which the callback was
triggered. For a button groupSelectionChangeFcn callback, hObject is the handle of the
selected radio button or toggle button.
eventdata — Sequences of events triggered by user actions such as table selections emitted by
a component in the form of a MATLAB struct (or an empty matrix for components that do not
generate eventdata)
handles — A MATLAB struct that contains the handles of all the objects in the GUI, and may
also contain application-defined data.
4.1.1 Object Handle
The first argument is the handle of the component issuing the callback. Use it to obtain
relevant properties that the callback code uses and change them as necessary. For example,
theText = get(hObject,'String');
places the String property (which might be the contents of static text or name of a button) into the
local variabletheText. You can change the property by setting it, for example
set(hObject,'String',date)
This particular code changes the text of the object to display the current date.
15
4.1.2 Event DataEvent data is a stream of data describing user gestures, such as key presses, scroll wheel
movements, and mouse drags. The auto-generated callbacks of GUIDE GUIs can access event
data for Handle Graphics® and uicontrol and uitable object callbacks. The following ones receive
event data when triggered:
CellEditCallback in a uitable
CellSelectionCallback in a uitable
KeyPressFcn in uicontrols and figures
KeyReleaseFcn in a figure
SelectionChangeFcn in a uibuttongroup
WindowKeyPressFcn in a figure or any of its child objects
WindowKeyReleaseFcn in a figure or any of its child objects
WindowScrollWheelFcn in a figure
Event data is passed to GUIDE-generated callbacks as the second of three standard arguments.
For components that issue no event data the argument is empty. For those that provide event data,
the argument contains a structure, which varies in composition according to the component that
generates it and the type of event.
For example, the event data for a key-press provides information on the key(s) currently being
pressed. Here is a GUIDE-generated KeyPressFcn callback template:
% --- Executes on key press with focus on checkbox1 and none of its controls.
function checkbox1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to checkbox1 (see GCBO)
% eventdata structure with the following fields (see UICONTROL)
%Key: name of the key that was pressed, in lower case
%Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
The eventdata structure passed in has three fields, identifying the Character being pressed (such
as '='), the keyModifier (such as 'control'), and the Key name (spelled out, such as 'equals').
16
Components that provide event data use different structures with event-specific field names to
pass data. Callbacks with event data usually are repeatedly issued as long as the event persists or
sometimes at the beginning of an event and thereafter only when its values change.
4.1.3 Handles StructureGUIDE creates a handles structure that contains the handles of all the objects in the figure.
For a GUI that contains an edit text, a panel, a pop-up menu, and a push button,
the handles structure originally looks similar to this. GUIDE uses each component's Tag property
to name the structure element for its handle.
handles =
figure1: 160.0011
edit1: 9.0020
uipanel1: 8.0017
popupmenu1: 7.0018
pushbutton1: 161.0011
output: 160.0011GUIDE creates and maintains the handles structure as GUI data. It is passed as an input argument
to all callbacks and enables a GUI's callbacks to share property values and application data.
4.2 Changing Callbacks Assigned by GUIDEAs described in Callback Names and Signatures in GUIDE, GUIDE generates a name for
a callback by concatenates the component's Tag property (checkbox1) and its callback type.
Although you cannot change a callback's type, you can change its Tag, which will change the
callback's name the next time you save the GUI.
Change a component's Tag property to give its callbacks more meaningful names; for example,
you might change the Tag property from checkbox1 to warn before save. If possible, change
the Tag property before saving the GUI to cause GUIDE to automatically create callback
templates having names you prefer. However, if you decide to change a Tag property after saving
the GUI, GUIDE updates the following items according to the new Tag, provided that all
components have distinct tags:
The component's callback functions in the GUI code file
The value of the component's callback properties, which you can view in the Property
Inspector
17
References in the code file to the field of the handles structure that contains the component's
handle.
In the Property Inspector, replace the name string in the callback property with the new name.
For example, if the value of the callback property for a push button in mygui is
mygui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
the string pushbutton1_Callback is the name of the callback function. Change the name to the
desired name, for example, closethegui.
As necessary, update instances of the callback function name in the code file (for example,
to function closethegui in its function definition).
After you alter a callback signature, whenever you click its pencil-and-paper icon to go to the
function definition in the GUI code file, GUIDE presents a dialog box for you to confirm the
changes you made.
4.2.1 GUIDE Callback TemplatesGUIDE defines conventions for callback syntax and arguments and implements these
conventions in the callback templates it adds to the GUI code. Each template is like this one for
the Callback subfunction for a push button.
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
...
The first comment line describes the event that triggers execution of the callback. This is
followed by the function definition line. The remaining comments describe the input arguments.
Insert your code after the last comment.
18
Certain figure and GUI component callbacks provide event-specific data in
the eventdata argument. As an example, this is the template for a push
button KeyPressFcn callback.
% --- Executes on key press with focus on pushbutton1
function pushbutton1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata structure with the following fields (see UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s)(i.e., control, shift)
% pressed
% handles structure with handles and user data (see GUIDATA)
Callbacks that provide event data and the components to which they apply are listed in the
following table.
GUI Component
Callbacks with Event Data Property Reference Pages
Figure KeyPressFcn, KeyReleaseFcn,WindowKeyPressFcn,WindowKeyReleaseFcn,WindowScrollWheel
Figure Properties
User interface control (uicontrol)
KeyPressFcn Uicontrol Proper ties
Button group (uibuttongroup)
SelectionChangeFcn Uibuttongroup P roperties
Table (uitable)
CellEditCallback,CellSelectionCallback Uitable Properties
Note You can avoid automatic generation of the callback comment lines for new callbacks. In
19
the Preferences dialog box, select GUIDE and uncheck Add comments for newly generated callback functions.
4.2.2 Callback Names and Signatures in GUIDE
The previous callback example includes the following function definition:
function pushbutton1_Callback(hObject,eventdata,handles)
When GUIDE generates the template, it creates the callback name by appending an underscore
(_) and the name of the callback property to the component's Tag property. In the example
above, pushbutton1 is the Tag property for the push button, and Callback is one of the push
button's callback properties. The Tag property uniquely identifies a component within the GUI.
The first time you save the GUI after adding a component, GUIDE adds callbacks for that
component to the code file and generates the callback names using the current value of
the Tag property. If you change the default Tag for any component, make sure that you have not
duplicated any other component's Tag value before you save your GUI. GUIDE issues a warning
if it determines that duplicate tags exist.
4.2.3 Callback Function SignaturesA function signature itemizes a function's name, the number, order, and types of its
parameters, and any qualifiers that apply to the function. When you use the Property Inspector to
view a component of a GUI that you have saved at least once, you see that its Callback property
is already set. When GUIDE saves a GUI, it
Generates a callback signature and assigns it as the value of the Callback property
Adds to the GUI code file a template for the function to which the signature point
The component may have other callbacks, for example a CreateFcn or a DeleteFcn, which
GUIDE populates the same way. It is up to you to add code to the template to make a callback do
something.
For example, if you click the pencil-and-paper icon for a push button's Callback property in
the Property Inspector, GUIDE presents the GUI code file in the MATLAB Editor and positions
the cursor at the first line of the callback. When GUIDE defines the function in the file as:
function pushbutton1_Callback(hObject, eventdata, handles)
then the function signature for the Callback property, shown in the Property Inspector, is
@(hObject,eventdata)mygui('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
20
The syntax @(hObject,eventdata) indicates that this is an anonymous function. The signature
enables MATLAB to execute the right callback when the user clicks this push button by
providing the following information.
The name of the file in which the callback function resides ('mygui')
The name of the callback function within the file ('pushbutton1_Callback')
The argument list to pass to the callback function:
1. hObject — The handle of the component issuing the callback (a push button, in this case)
2. eventdata — A structure containing event data generated by the component (for push
buttons and other components that generate no event data, this argument contains an empty
matrix)
3. guidata(hObject) — The handles Structure for the GUI, used to communicate component
handles between callbacks
The following figure illustrates how these elements relate to one another.
21
CHAPTER-5
MATLAB CODING
5.1 PROGRAM USED IN MATLAB :
function varargout = main(varargin)
% MAIN M-file for main.fig
% MAIN, by itself, creates a new MAIN or raises the existing
% singleton*.
%
% H = MAIN returns the handle to a new MAIN or the handle to
% the existing singleton*.
%
% MAIN('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MAIN.M with the given input arguments.
%
% MAIN('Property','Value',...) creates a new MAIN or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before main_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to main_OpeningFcn via varargin.
22
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help main
% Last Modified by GUIDE v2.5 14-Mar-2011 16:13:22
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @main_OpeningFcn, ...
'gui_OutputFcn', @main_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before main is made visible.
function main_OpeningFcn(hObject, eventdata, handles, varargin)
23
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to main (see VARARGIN)
% Choose default command line output for main
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes main wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = main_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
FID=serial('COM1', 'BaudRate',9600);
fopen(FID);
24
fwrite(FID,'F');
fclose(FID);
delete(FID);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
FID=serial('COM1', 'BaudRate',9600);
fopen(FID);
fwrite(FID,'B');
fclose(FID);
delete(FID);
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
FID=serial('COM1', 'BaudRate',9600);
fopen(FID);
fwrite(FID,'S');
fclose(FID);
delete(FID);
5.2 MATLAB FUNCTIONS
25
5.2.1 serial
Create serial port object
Syntax
obj = serial('port')
obj = serial('port','PropertyName',PropertyValue,...)
Description
obj = serial('port') creates a serial port object associated with the serial port specified by port. If
port does not exist, or if it is in use, you will not be able to connect the serial port object to the
device.
Port object name will depend upon the platform that the serial port is on. insthwinfo ('serial')
provides a list of available serial ports. This list is an example of serial constructors on different
platforms:
Platform Serial Port Constructor
Linux and Linux 64 serial('/dev/ttyS0');
Mac OS X and Mac OS X 64 serial('/dev/tty.KeySerial1');
Solaris 64 serial('/dev/term/a');
Windows 32 and Windows 64 serial('com1');
obj = serial('port','PropertyName',PropertyValue,...) creates a serial port object with the specified
property names and property values. If an invalid property name or property value is specified, an
error is returned and the serial port object is not created.
Remarks
When you create a serial port object, these property values are automatically configured:
The Type property is given by serial.
The Name property is given by concatenating Serial with the port specified in the serial
function.
The Port property is given by the port specified in the serial function.
You can specify the property names and property values using any format supported by the set
function. For example, you can use property name/property value cell array pairs. Additionally,
26
you can specify property names without regard to case, and you can make use of property name
completion. For example, the following commands are all valid on a Windows platform.
s = serial('COM1','BaudRate',4800);
s = serial('COM1','baudrate',4800);
s = serial('COM1','BAUD',4800);.
Before you can communicate with the device, it must be connected to obj with the fopen
function. A connected serial port object has a Status property value of open. An error is returned
if you attempt a read or write operation while the object is not connected to the device. You can
connect only one serial port object to a given serial port.
Example
This example creates the serial port object s1 associated with the serial port COM1 on a Windows
platform.
s1 = serial('COM1');
The Type, Name, and Port properties are automatically configured.
get(s1,{'Type','Name','Port'})
ans =
'serial' 'Serial-COM1' 'COM1'
To specify properties during object creation
s2 = serial('COM2','BaudRate',1200,'DataBits',7);
5.2.2 fopen
Open file, or obtain information about open files
Syntax
27
fileID = fopen(filename)
fileID = fopen(filename, permission)
fileID = fopen(filename, permission, machineformat)
fileID = fopen(filename, permission, machineformat, encoding)
[fileID, message] = fopen(filename, ...)
fIDs = fopen('all')
[filename, permission, machineformat, encoding] = fopen(fileID)
Description
fileID = fopen(filename) opens the file filename for read access, and returns an integer file
identifier.
fileID = fopen(filename, permission) opens the file with the specified permission.
fileID = fopen(filename, permission, machineformat) specifies the order for reading or
writing bytes or bits in the file.
fileID = fopen(filename, permission, machineformat, encoding) specifies the character
encoding scheme associated with the file.
[fileID, message] = fopen(filename, ...) opens a file. If the operation fails, message is a
system-dependent error message. Otherwise, message is an empty string.
fIDs = fopen('all') returns a row vector containing the file identifiers of all open files.
[filename, permission, machineformat, encoding] = fopen(fileID) returns the file name,
permission, machine format, and encoding that a previous call to fopen used when it opened
the specified file. fopen does not read information from the file to determine these output
values. An invalid fileID returns empty strings for all output arguments.
Inputs
Filename String in single quotation marks that specifies the name of the file to
open. Can include a full or partial path.
On UNIX systems, if filename begins with '~/' or '~username/', the
28
fopen function expands the path to the current or specified user's
home directory, respectively.
If you open a file with read access and fopen cannot find filename in
the current folder, fopen searches along the MATLAB search path.
Otherwise, fopen creates a file in the current directory.
Permission String that describes the type of access for the file: read, write,
append, or update. Also specifies whether to open files in binary or
text mode.
To open files in binary mode, specify one of the following:
'r'Open file for reading (default).
'w' Open or create new file for writing. Discard existing contents, if any.
'a' Open or create new file for writing. Append data to the end of the file.
'r+' Open file for reading and writing.
'w+
'
Open or create new file for reading and writing. Discard existing
contents, if any.
'a+' Open or create new file for reading and writing. Append data to the
end of the file.
'A' Append without automatic flushing. (Used with tape drives.)
'W' Write without automatic flushing. (Used with tape drives.)
To read and write to the same file:
Open the file in update mode (with a permission that includes
a plus sign, '+').
Call fseek or frewind between read and write operations. For
example, do not call fread followed by fwrite, or fwrite
followed by fread, unless you call fseek or frewind between
them.
To open files in text mode, attach the letter 't' to the permission, such
as 'rt' or 'wt+'. For better performance, do not use text mode. The
29
following applies on Windows systems, in text mode:
Read operations that encounter a carriage return followed by a
newline character ('\r\n') remove the carriage return from the
input.
Write operations insert a carriage return before any newline
character in the output.
This additional processing is unnecessary for most cases. All
MATLAB import functions, and most text editors (including
Microsoft Word and WordPad), recognize both '\r\n' and '\n' as
newline sequences. However, when you create files for use in
Microsoft Notepad, end each line with '\r\n'. For an example, see
fprintf.
Machineformat String that specifies the order for reading or writing bytes or bits in
the file. Specify machineformat to:
Read a file created on a different system.
Read bits in a particular order.
Create a file for use on a different system.
Possible values are:
'n' or 'native'The byte ordering that your system uses
(default)
'b' or 'ieee-be' Big-endian ordering
'l' or 'ieee-le' Little-endian ordering
's' or 'ieee-be.l64' Big-endian ordering, 64-bit data type
'a' or 'ieee-le.l64' Little-endian ordering, 64-bit data type
Windows systems use little-endian ordering, and most UNIX systems
use big-endian ordering, for both bytes and bits. Solaris systems use
big-endian ordering for bytes, but little-endian ordering for bits.
Encoding String that specifies the character encoding scheme to use for
subsequent read and write operations, including fscanf, fprintf, fgetl,
30
fgets, fread, and fwrite.
Possible values are:
'Big5''ISO-8859-1' 'windows-932'
'EUC-JP' 'ISO-8859-2' 'windows-936'
'GBK' 'ISO-8859-3' 'windows-949'
'Shift_JIS' 'ISO-8859-4' 'windows-950'
'US-ASCII' 'ISO-8859-9' 'windows-1250'
'UTF-8' 'ISO-8859-13' 'windows-1251'
'ISO-8859-15' 'windows-1252'
'windows-1253'
'windows-1254'
'windows-1257'
Default: system-dependent
Outputs
fileID An integer that identifies the file for all subsequent low-level file I/O
operations. If fopen cannot open the file, fileID is -1.
MATLAB reserves file identifiers 0, 1, and 2 for standard input, standard
output (the screen), and standard error, respectively. When fopen
successfully opens a file, it returns a file identifier greater than or equal to
3.
message A system-dependent error message when fopen cannot open the specified
file. Otherwise, an empty string.
fIDs Row vector containing the identifiers for all open files, except the
identifiers reserved for standard input, output, and error. The number of
elements in the vector is equal to the number of open files.
filename Name of the file associated with the specified fileID.
permission The permission that fopen assigned to the file specified by fileID.
31
machineformat The value of machineformat that fopen used when it opened the file
specified by fileID.
encoding The character encoding scheme that fopen associated with the file specified
by fileID.
The value that fopen returns for encoding is a standard character encoding
scheme name. It is not always the same as the encoding argument that you
used in the call to fopen to open the file.
Examples
Open a file. Pass the file identifier, fid, to other file I/O functions to read data and close the file.
fid = fopen('fgetl.m');
tline = fgetl(fid);while ischar(tline) disp(tline); tline = fgetl(fid);end
fclose(fid);
Create a prompt to request the name of a file to open. If fopen cannot open the file, display the relevant error message.
fid = -1;msg = '';while fid < 0 disp(msg); filename = input('Open file: ', 's'); [fid,msg] = fopen(filename);end
Open a file to write Unicode® characters to a file using the Shift-JIS character encoding scheme:
32
fid = fopen('japanese_out.txt', 'w', 'n', 'Shift_JIS');
5.2.3 fwrite
Write data to binary file
Syntax
fwrite(fileID, A)fwrite(fileID, A, precision)fwrite(fileID, A, precision, skip)fwrite(fileID, A, precision, skip, machineformat)count = fwrite(...)
Description
fwrite(fileID, A) writes the elements of array A to a binary file in column order.
fwrite(fileID, A, precision) translates the values of A according to the form and size described by the precision.
fwrite(fileID, A, precision, skip) skips skip bytes before writing each value. If precision is bitn or ubitn, specify skip in bits.
fwrite(fileID, A, precision, skip, machineformat) writes data with the specified machineformat. The skip parameter is optional.
count = fwrite(...) returns the number of elements of A that fwrite successfully writes to the file.
Inputs
fileID One of the following:
An integer file identifier obtained from fopen. 1 for standard output (the screen). 2 for standard error.
A Numeric or character array.
precision String in single quotation marks that controls the form and size of the output. The following table shows possible values for precision.
Value Type Precision Bits (Bytes)
Integers, unsigned
uintuint8
32 (4)8 (1)
33
uint16uint32uint64ucharunsigned charushortulongubitn
16 (2)32 (4)64 (8)8 (1)8 (1)16 (2)system-dependent1 ≤ n ≤ 64
Integers, signed intint8int16int32int64integer*1integer*2integer*3integer*4scharsigned charshortlongbitn
32 (4)8 (1)16 (2)32 (4)64 (8)8 (1)16 (2)32 (4)64 (8)8 (1)8 (1)16 (2)system-dependent1 ≤ n ≤ 64
Floating-point numbers
singledoublefloatfloat32float64real*4real*8
32 (4)64 (8)32 (4)32 (4)64 (8)32 (4)64 (8)
Characters char*1char
8 (1)Depends on the encoding scheme associated with the file. Set encoding with fopen.
long and ulong are 32 bits on 32-bit systems, and 64 bits on 64-bit systems.
If you specify a precision of bitn or ubitn, and a value is out of range, fwrite sets all bits for that value.
Default: uint8
Skip Number of bytes to skip before writing each value. If you specify a precision of bitn or ubitn, specify skip in bits. Use this parameter to insert data into noncontiguous fields in fixed-length records.
Default: 0
34
machineformat String that specifies the order for writing bytes within the file. For bitn and ubitn precisions, specifies the order for writing bits within a byte. Use this parameter when you plan to read and write to the same file on different systems.
Possible values are:
'n' or 'native'The byte ordering that your system uses (default)
'b' or 'ieee-be' Big-endian ordering
'l' or 'ieee-le' Little-endian ordering
's' or 'ieee-be.l64' Big-endian ordering, 64-bit data type
'a' or 'ieee-le.l64' Little-endian ordering, 64-bit data typeWindows systems use little-endian ordering, and most UNIX systems use big-endian ordering, for both bytes and bits. Solaris systems use big-endian ordering for bytes, but little-endian ordering for bits.
Examples
Create a 100-byte binary file containing the 25 elements of the 5-by-5 magic square, stored as 4-
byte integers:
fid = fopen('magic5.bin', 'w');
fwrite(fid, magic(5), 'integer*4');
fclose(fid);
5.2.4 fclose
Close one or all open files
Syntax
fclose(fileID)
fclose('all')
status = fclose(...)
Description
fclose(fileID) closes an open file. fileID is an integer file identifier obtained from fopen.
35
fclose('all') closes all open files.
status = fclose(...) returns a status of 0 when the close operation is successful. Otherwise, it
returns -1.
5.2.5 delete (serial)
Remove serial port object from memory
Syntax
delete(obj)
Description
delete(obj) removes obj from memory, where obj is a serial port object or an array of serial port
objects.
Remarks
When you delete obj, it becomes an invalid object. Because you cannot connect an invalid serial
port object to the device, you should remove it from the workspace with the clear command. If
multiple references to obj exist in the workspace, then deleting one reference invalidates the
remaining references.
If obj is connected to the device, it has a Status property value of open. If you issue delete while
obj is connected, then the connection is automatically broken. You can also disconnect obj from
the device with the fclose function.
If you use the help command to display help for delete, then you need to supply the pathname
shown below.
help serial/delete
Example
This example creates the serial port object s on a Windows platform, connects s to the device,
writes and reads text data, disconnects s from the device, removes s from memory using delete,
and then removes s from the workspace using clear.
36
s = serial('COM1');
fopen(s)
fprintf(s,'*IDN?')
idn = fscanf(s);
fclose(s)
delete(s)
clear s
CHAPTER-6
EMBEDDED SYSTEM
6.1 What is Embedded System?
Embedded system employs a combination of software & hardware to perform a specific
function. It is a part of a larger system which may not be a “computer” Works in a reactive &
time constrained environment.
Any electronic system that uses a CPU chip, but that is not a general-purpose workstation,
desktop or laptop computer is known as embedded system. Such systems generally use
microprocessors; microcontroller or they may use custom-designed chips or both. They are
used in automobiles, planes, trains, space vehicles, machine tools, cameras, consumer and
office appliances, cell phones, PDAs and other handhelds as well as robots and toys. The uses
are endless, and billions of microprocessors are shipper every year for a myriad of
applications.
In embedded systems, the software is permanently set into a read-only memory such as a
ROM or flash memory chip, in contrast to a general-purpose computer that loads its programs
into RAM each time. Sometimes, single board and rack mounted general-purpose computers
are called "embedded computers" if used to count
37
Embedded System Applications :-
Consumer electronics, e.g., cameras, cell phones etc.
Consumer products, e.g. washers, microwave ovens etc.
Automobiles (anti-lock braking, engine control etc.)
Industrial process controller & defense applications.
Computer/Communication products, e.g. printers, FAX machines etc.
Medical Equipments.
ATMs
6.2 DIFFERENCE BETWEEN MICROPROCESSORS AND
MICROCONTROLLERS
A Microprocessor is a general purpose digital computer central processing unit(C.P.U)
popularly known as CPU on the chip. The Microprocessors contain no RAM, no ROM,
and no I/P O/P ports on the chip itself.
On the other hand a Microcontroller has a C.P.U(microprocessor) in addition to a fixed
amount of RAM, ROM, I/O ports and a timer all on a single chip.
In order to make a Microprocessor functional we must add RAM, ROM, I/O Ports and
timers externally to them,i.e any amount of external memory can be added to it.
But in controllers there is a fixed amount of memory which makes them ideal for many
applications.
The Microprocessors have many operational codes(opcodes) for moving data from
external memory to the C.P.U
Whereas Microcontrollers may have one or two operational codes.
6.3 DISADVANTAGES OF MICROPROCESSORS
OVER MICROCONTROLLERS
System designed using Microprocessors are bulky
They are expensive than Microcontrollers
We need to add some external devices such as PPI chip, Memory, Timer/counter chip,
Interrupt controller chip,etc. to make it functional.
38
6.3 TYPES OF MICROCONTROLLER ARCHITECTURE:
There are two types of Microcontroller architecture designed for embedded system
development. These are:
1)RISC- Reduced instruction set computer
2)CISC- Complex instruction set computer
6.3.1 DIFFERENCE BETWEEN CISC AND RISC:
CISC stands for Complex Instruction Set Computer. Most PC's use CPU based on this
architecture. For instance Intel and AMD CPU's are based on CISC architectures. Typically CISC
chips have a large amount of different and complex instructions. In common CISC chips are
relatively slow (compared to RISC chips) per instruction, but use little (less than RISC)
instructions. MCS-51 family microcontrollers based on CISC architecture.
RICS stands for Reduced Instruction Set Computer. The philosophy behind it is that almost no
one uses complex assembly language instructions as used by CISC, and people mostly use
compilers which never use complex instructions. Therefore fewer, simpler and faster instructions
would be better, than the large, complex and slower CISC instructions. However, more
instructions are needed to accomplish a task. Atmell’s AVR microcontroller based on RISC
architecture.
39
6.4 PIC MICROCONTROLLER
PIC 16 SERIES-PIC16F873
40
PIC is a family of Harvard architecture microcontrollers made by Microchip Technology,
derived from the PIC1640 originally developed by General Instrument's Microelectronics
Division. The name PIC initially referred to "Peripheral Interface Controller".PIC16F873 : This
powerful (200 nanosecond instruction execution) yet easy-to-program (only 35 single word
instructions) CMOS FLASH-based 8-bit microcontroller packs Microchip's powerful PIC®
architecture into an 28-pin package and is upwards compatible with the PIC16C5X, PIC12CXXX
and PIC16C7X devices. The PIC16F873A features 128 bytes of EEPROM data memory, self
programming, an ICD, 2 Comparators, 5 channels of 10-bit Analog-to-Digital (A/D) converter,
the synchronous serial port can be configured as either 3-wire Serial Peripheral Interface (SPI™)
or the 2-wire Inter-Integrated Circuit (I²C™) bus and a Universal Asynchronous Receiver
Transmitter (USART). All of these features make it ideal for more advanced level A/D
applications in automotive, industrial, appliances and consumer applications.
Parameter Name Value
Program Memory Type Flash
Program Memory (KB) 7
CPU Speed (MIPS) 5
RAM Bytes 192
Data EEPROM (bytes) 128
Digital Communication Peripherals 1-A/E/USART, 1-MSSP(SPI/I2C)
Capture/Compare/PWM Peripherals 2 CCP
Timers 2 x 8-bit, 1 x 16-bit
41
ADC 5 ch, 10-bit
Comparators 2
Temperature Range (C) -40 to 125
Operating Voltage Range (V) 2 to 5.5
Pin Count 28
It is available in different configurations viz 8bit,16 bit,32 bit with instructions set as given below
:
Under 8 bit comes-PIC10 xxxx, PIC12 xxxx, PIC16 xxxx, PIC18 xxxx.(12 bit instruction set)
Under 16 bit comes-PIC24H,DSPIC30,DSPIC33. (14 bit instruction set)
Under 32 bit comes-PIC32xxxx. (16 bit instruction set)
PICs are popular with developers and hobbyists alike due to their low cost, wide availability,
large user base, extensive collection of application notes, availability of low cost or free
development tools, and serial programming (and re-programming with flash memory) capability.
6.4.1Special Microcontroller Features:
• High performance RISC CPU.
• Only 35 single word instructions to learn.
• All single cycle instructions except for program branches which are two-cycle.
• Operating speed: DC - 20 MHz clock input DC - 200 ns instruction cycle.
• Up to 8K x 14 words of FLASH Program Memory, Up to 368 x 8 bytes of Data Memory
(RAM).
• Interrupt capability (up to 12 sources).
• Direct, Indirect and Relative Addressing modes.
• Processor read access to program memory.
• Power-on Reset (POR).
• Power-up Timer (PWRT) and Oscillator Start-up Timer (OST).
• Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation.
• Programmable code protection
42
• Power saving SLEEP mode
• Selectable oscillator options
• In-Circuit Serial Programming (ICSP) via two pins.
6.4.2 Peripheral Features:
• Timer0: 8-bit timer/counter with 8-bit prescaler.
• Timer1: 16-bit timer/counter with prescaler, can be incremented during SLEEP via external
crystal/clock.
• Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler.
• Two Capture, Compare, PWM modules
- Capture is 16-bit, max. resolution is 12.5 ns
- Compare is 16-bit, max. resolution is 200 ns
- PWM max. resolution is 10-bit.
• 8-bit, up to 8-channel Analog-to-Digital converter.
• Synchronous Serial Port (SSP) with SPI (Master mode) and I2C(Slave).
• Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI).
• Parallel Slave Port (PSP), 8-bits wide with external RD, WR and CS controls (40/44-pin only).
• Brown-out detection circuitry for Brown-out Reset (BOR).
6.4.3 CMOS Technology:
• Low power, high speed CMOS FLASH technology.
• Fully static design.
• Wide operating voltage range: 2.0V to 5.5V.
• High Sink/Source Current: 25 Ma.
• Industrial temperature range.
• Low power consumption:
- < 2 mA typical @ 5V, 4 MHz
6.5 PIN DIAGRAM
43
6.5.1 PIN DESCRIPTION
MCLR-(pin 1)
PIC16F7X devices have a noise filter in the MCLR Reset path. The filter will detect and
ignore small pulses. It should be noted that a WDT Reset does not drive MCLR pin low. The
behavior of the ESD protection on the MCLR pin has been altered from previous devices of this
family. Voltages applied to the pin that exceed its specification can result in both MCLR Resets
and excessive current beyond the device specification during the ESD event. For this reason,
Microchip recommends that the MCLR pin no longer be tied directly to VDD.
RESET
The PIC16F7X differentiates between various kinds of RESET:
Power-on Reset (POR)
MCLR Reset during normal operation
MCLR Reset during SLEEP
WDT Reset (during normal operation)
WDT Wake-up (during SLEEP)
Brown-out Reset (BOR)
Some registers are not affected in any RESET condion. Their status is unknown on POR and
unchanged on any other RESET. Most other registers are reset to a RESET state” on Power-on
44
Reset (POR), on the MCLR and WDT Reset, on MCLR Reset during LEEP, and Brown-out
Reset (BOR). They are not affected by a WDT Wake-up, which is viewed as the resumption of
normal operation. The TO and PD bits are set or cleared differently in different RESET
situations, as indicated
PORTA –(pin 2 to 7)and the TRISA Register-
PORTA is a 6-bit wide, bi-directional port. The corresponding data direction register is
TRISA. Setting a TRISA bit (= ‘1’) will make the corresponding PORTA pin an input (i.e., put
the corresponding output driver in a Hi-Impedance mode). Clearing a TRISA bit (= ‘0’) will
make the corresponding PORTA pin an output (i.e., put the contents of the output latch on the
selected pin).
Reading the PORTA register reads the status of the pins, whereas writing to it will write to the
port latch. All write operations are read-modify-write operations. Therefore, a write to a port
implies that the port pins are read, the value is modified and then written to the port data latch.
GND –(pin 8)
Provide Ground to it.
OSC1/CLKIN-(pin 9)
Oscillator crystal input/external clock source input
OSC2/CLKOUT-(pin 10)
Oscillator crystal output. Connects to crystal or resonator in Crystal Oscillator mode. In RC
mode, the OSC2 pin outputs CLKOUT which has 1/4 the frequency of OSC1, and denotes the
instruction cycle rate.
45
Oscillator:- CRYSTAL OSCILLATOR/CERAMIC RESONATORS In XT, LP or HS
modes, a crystal or ceramic resonator is connected to the OSC1/CLKIN and OSC2/CLKOUT
pins to establish oscillation. The PIC16F7X oscillator design requires the use of a parallel cut
crystal. Use of a series cut crystal may give a frequency out of the crystal manufacturers
specifications. When in HS mode, the device can accept an external clock source to drive the
OSC1/CLKIN pin.
6.5.2 OSCILLATOR TYPES
The PIC16F7X can be operated in four different oscillator modes:
LP Low Power Crystal
XT Crystal/Resonator
HS High Speed Crystal/Resonator
RC Resistor/Capacitor
PORTC and the TRISC Register(pin 11 to 18)
PORTC is an 8-bit wide, bi-directional port. The corresponding data direction register is
TRISC. Setting a TRISC bit (= ‘1’) will make the corresponding PORTC pin an input (i.e., put
the corresponding output driver in a Hi-Impedance mode). Clearing a TRISC bit (= ‘0’) will
make the corresponding PORTC pin an output (i.e., put the contents of the output latch on the
selected pin).PORTC is multiplexed with several peripheral functions PORTC pins have Schmitt
Trigger input buffers. When enabling peripheral functions, care should be taken in defining TRIS
bits for each PORTC pin.
Vss(pin 19)
Ground reference for logic and I/O pins
Vdd(pin 20)
Positive supply for logic and I/O pins
46
PORTB and the TRISB Register(pin 21 to 28)
PORTB is an 8-bit wide, bi-directional port. The corresponding data direction register is
TRISB. Setting a TRISB bit (= ‘1’) will make the corresponding PORTB pin an input (i.e., put
the corresponding output driver in a Hi-Impedance mode). Clearing a TRISB bit (= ‘0’) will
make the corresponding PORTB pin an output (i.e., put the contents of the output latch on the
selected pin).
Each of the PORTB pins has a weak internal pull-up. A single control bit can turn on all the pull-
ups. The weak pull-up is automatically turned off when the port pin is configured as an output.
The pull-ups are disabled on a Power-on Reset.
6.6 CORE ARCHITECTURE
Showing a typical microcontroller device and its different subunits
The PIC architecture is distinctively minimalist. It is characterized by the following features:
47
Separate code and data spaces (Harvard architecture)
A small number of fixed length instructions
Most instructions are single cycle execution (4 clock cycles), with single delay cycles
upon branches and skips
A single accumulator (W), the use of which (as source operand) is implied (i.e. is not
encoded in the opcode)
All RAM locations function as registers as both source and/or destination of math and
other functions.
A hardware stack for storing return addresses
A fairly small amount of addressable data space (typically 256 bytes), extended through
banking
Data space mapped CPU, port, and peripheral registers
The program counter is also mapped into the data space and writable (this is used to
implement indirect jumps).
Unlike most other CPUs, there is no distinction between memory space and register space
because the RAM serves the job of both memory and registers, and the RAM is usually just
referred to as the register file or simply as the registers
6.7 ELECTRICAL CHARACTERISTICS
Absolute Maximum Ratings :
Ambient temperature under bias...................................... .-55 to +125°C
Storage temperature.......................................................... -65°C to +150°C
Voltage on any pin with respect to VSS
(except VDD, MCLR. and RA4) ..................................... -0.3V to (VDD + 0.3V)
Voltage on VDD with respect to VSS............................... -0.3 to +6.5V
Voltage on MCLR with respect to VSS (Note2)..................0 to +13.5V
48
Voltage on RA4 with respect to Vss ..................................0 to +12V
Total power dissipation (Note 1)........................................1.0W
Maximum current out of VSS pin......................................300 mA
Maximum current into VDD pin .........................................250 mA
Input clamp current, IIK (VI < 0 or VI > VDD)................. ± 20 mA
Output clamp current, IOK (VO < 0 or VO > VDD).......... ± 20 mA
Maximum output current sunk by any I/O pin.......................25 mA
Maximum output current sourced by any I/O pin .................25 mA
Maximum current sunk by PORTA, PORTB,
and PORTE (combined)........................................................200 mA
Maximum current sourced by PORTA, PORTB,
and PORTE (combined) .......................................................200 mA
Maximum current sunk by PORTC
and PORTD (combined).......................................................200 mA
Maximum current sourced by PORTC
and PORTD (combined).......................................................200 mA
Note 1: Power dissipation is calculated as follows:
Pdis = VDD x {IDD - Σ IOH} + Σ {(VDD - VOH) x IOH} + Σ(VOl x IOL)
Note 2:
49
Voltage spikes below VSS at the MCLR pin, inducing currents greater than 80 mA, may cause
latch-up. Thus,a series resistor of 50-100Ω should be used when applying a “low” level to the
MCLR pin, rather than pulling this pin directly to VSS.
Note 3:
PORTD and PORTE are not implemented on the PIC16F73/76 devices.
6.7 PROGRAMMING OF PIC
COMPILER USED-
MPLAB IDE V.8
Introduction to MPLAB
MPLAB is a powerful, feature rich development tool for PIC. It is designed to provide the
programmer with the easiest possible solution for developing applications for embedded systems,
without compromising performance or control.
50
MPLAB IDE
PIC and C fit together well: PIC is the most popular 8-bit chip in the world, used in a wide variety
of applications, and C, prized for its efficiency, is the natural choice for developing embedded
systems. MPLAB IDE provides a successful match featuring highly advanced IDE, ANSI
compliant compiler, broad set of hardware libraries, comprehensive documentation, and plenty of
ready-to-run examples.
Features
MPLAB IDE allows you to quickly develop and deploy complex applications:
Write your C source code using the built-in Code Editor (Code and Parameter Assistants,
Syntax Highlighting, Auto Correct, Code Templates, and more…)
Use the included MPLAB libraries to dramatically speed up the development: data
acquisition, memory, displays, conversions, communications… Practically all P12, P16,
and P18 chips are supported.
Monitor your program structure, variables, and functions in the Code Explorer.
Generate commented, human-readable assembly, and standard HEX compatible with all
programmers.
Inspect program flow and debug executable logic with the integrated Debugger.
Get detailed reports and graphs: RAM and ROM map, code statistics, assembly listing,
calling tree, and more…
We have provided plenty of examples for you to expand, develop, and use as building
bricks in projects. Copy them entirely if you deem fit – that’s why we included them with
the compiler.
Projects
MPLAB organizes applications into projects, consisting of a single project file (extension
.ppc) and one or more source files (extension .c). You can compile source files only if they are
part of a project.
The project file carries the following information:
51
project name and optional description,
target device,
device flags (config word),
device clock,
.
6.8 PROGRAMMING AND INTERFACING
Advantages of C over Assembly language programming:
Knowledge of the processor instruction set is not required.
Details like register allocation and addressing of memory and data is managed by the
compiler.
Programs get a formal structure and can be divided into separate functions.
Programming and program test time is drastically reduced, this increases efficiency.
Keywords and operational functions can be used that come closer to how humans think.
The supplied and supported C libraries contain many standard routines such as numeric
conversions.
Reusable code: Existing program parts can be more easily included into new programs,
because of the comfortable modular program construction techniques.
The C language based on the ANSI standard is very portable. Existing programs can be
quickly adapted to other processors as needed.
I/O (Input/Output) Ports
It is possible with with a PIC to interact with the real world. This is done thourgh the use
of I/O ports. The PIC16F873 has 3 I/O ports, labeled "a", "b" and "c". We will use Port A for
analog input, though it has other uses. Ports B and C will be used for digital I/O. On the
schematic the pins are labeled RB0 through RB7, but the compiler refers to them as pin_B0
through pin_B7. Likewise for port C. The pins can be used for either input or output.
52
Your circuit has the pushbutton switch connected to RB0, and the LED's to pins RC0 through
RC7.
Digital Output
There are several functions that are used for output from the PIC. A full listing is in the
PCB manual. Four commonly used functions are:
Output_high(pin)
Sets the specified pin to a logic 1 (about 5 volts).
Output_low(pin)
Sets the specified pin to a logic 0 (about 0 volts)
Output_float(pin)
Sets the specified pin to a high-impedance (or tri-state) state. In this state
it is as if the pin has no connections to the chip. Current can neither go in
or out of the pin.
Output_bit(pin,value)
This function sets the specified pin to the specified value (which must be
0 or 1)
#include <16f8732a.H>
#define L293D_A P2_0 //Positive of motor
#define L293D_B P2_1 //Negative of motor
#define L293D_E P2_2 //Enable of L293D
// Function Prototypes
void rotate_f(void); //Forward run funtion
void rotate_b(void); //Backward run function
void breaks(void); //Motor stop function
void delay(void); //Some delay
void main(){ //Our main function
while(1){ //Infinite loop
rotate_f(); //Run forward
delay(); //Some delay
53
breaks(); //Stop
delay(); //Some delay
rotate_b(); //Run Backwards
delay(); //Some delay
breaks(); //Stop
delay(); //Some delay
} //Do this infinitely
}
void rotate_f(){
L293D_A = 1; //Make positive of motor 1
L293D_B = 0; //Make negative of motor 0
L293D_E = 1; //Enable L293D
}
void rotate_b(){
L293D_A = 0; //Make positive of motor 0
L293D_B = 1; //Make negative of motor 1
L293D_E = 1; //Enable L293D
}
void breaks(){
L293D_A = 0; //Make positive of motor 0
L293D_B = 0; //Make negative of motor 0
L293D_E = 0; //Disable L293D
}
void delay(){ //Some delay...
unsigned char i,j,k;
for(i=0;i<0x20;i++)
for(j=0;j<255;j++)
for(k=0;k<255;k++);
}
54
CHAPTER-7
HARDWARE INTERFACING
7.1 HYPERTERMINAL
HyperTerminal is a program that you can use to connect to other computers, Telnet sites,
bulletin board systems, online services, and host computers, using either modem, a null
modem cable or Ethernet connection. Though using HyperTerminal with a BBS to access
information on remote computers is a practice that has become less common with the
availability of the World Wide Web, HyperTerminal is still a useful means of configuring
and testing modem or examining your connection with other sites HyperTerminal records the
messages passed to and from the computer or service on the other end of connection. Therefore, it
can serve as a valuable troubleshooting tool when setting up and using modem.
To make sure that modem is connected properly or to view your modem's settings, you can send
commands through HyperTerminal and check the results. HyperTerminal has scroll
functionality that allows you to look at received text that has scrolled off the screen. we can use
HyperTerminal to transfer large files from a computer onto you r portable computer using a
seria l port rather than going through the process of setting up your portable computer on a
network . we can use HyperTerminal to help debug source code from a remote terminal. can
also use HyperTerminal to communicate with older character-based computers. HyperTerminal
is designed to be an easy-to-use tool and is not meant to replace other full-feature tools available
55
on the market. You can use HyperTermina l to perform the specific tasks described above, but
do not attempt to use HyperTerminal for more complex communication needs.
we can create and save multiple connections within HyperTerminal. Each connection can
have its own unique configuration, including phone number and port settings such as bits per
second, parity checks, and host TCP/IP address .As part of the connection configuration,
HyperTerminal also allows your computer to emulate a variety of terminal types, such as TTY,
ANSI and VTx terminals .The connection that is currently open within HyperTerminal is
displayed in the Hyperterminal title bar. we can only have one connection open per each
HyperTerminal session. we can, however, start multiple HyperTerminal sessions,opening a
newconnection for each session (provided each connection uses a different communication
port).When we first open HyperTerminal , you will be prompted to decide If you want
HyperTerminal to be your default telnet client. You also will be able to choose not to see this
dialog box again.
HyperTerminal cannot automatically provide you r login ID and password when you make
a connection . If you provide a password when using HyperTerminal for a Telnet session, be
aware that this password will be sent to the remote computer using plain text. We can use
HyperTerminal to send and receive text and data files to a remote computer. The status of the
transfer is displayed in the HyperTerminal window during the transfer. You can also capture the
status of a transferred file and send the information directly to a printer. we can send text files as
an alternative to keyboard input using Send Text File. This is useful , for example, when you
need to send a string of keyboard input to a remote computer for troubleshooting purposes, or
Need to send a lengthy keyboard input string as part of a connection sequence to a remote
computer or router.
7.2 TO SET HYPERTERMINAL CONNECTIONS
1. Start the HyperTerminal .exe program (hypertrm.exe). Click on START,
thenACCESSORIES, then COMMUNICATIONS, thenHYPERTERMINAL, then chose
the HyperTerminal entry that does not have an .ht extension.
56
2. This brings up this dialog. Enter a Name (like 'Direct-Com-1).
Chose an ICON - whatever wish.
Click OK
3. This dialog then appears. Click the selection arrow on the "Connect using" list box, and
select the COM port your modem is connected to - not the modem name.
When we select the COM port, the phone number to dial boxes are grayed.
4. The COM port properties box comes up. For 56k modems, make sure to set the Bits per second
to 57,600 or 115,200.
57
The other defaults shown here are correct.
Click OK.
5. we now get the HyperTerminal window where you are able to control your modem with
commands.
Type AT - you should get an OK back. we're ready to go!When we end the session, make sure to
say YES to save the settings. A new icon will be created in the HyperTerminal folder with your
session-name.ht. This is a shortcut to these settings. You can put a copy of this shortcut on your
desktop for easy access, and you never need to repeat these setup steps.
58
7.3 RS232
The RS-232 interface is the Electronic Industries Association (EIA) standard for the
interchange of serial binary data between two devices. It was initially developed by the EIA to
standardize the connection of computers with telephone line modems. The standard allows as
many as 20 signals to be defined, but gives complete freedom to the user. Three wires are
sufficient: send data, receive data, and signal ground. The remaining lines can be
hardwired on or off permanently. The signal transmission is bipolar, requiring two voltages,
from 5 to 25 volts, ofN opposite polarity. Communication Standards: The industry custom is to
use an asynchronous word consisting of: a start bit, seven or eight data bits, an optional parity
bit and one or two stop bits. The baud rate at which the word sent is device-dependent. The
baud rate is usually 150 times an integer power of 2, ranging from 0 to 7 (150, 300, 600 ,....,
19,200 ). Below 150 baud, many system-unique rates are used. The standard RS-232-C
connector has 25 pins, 21 pins which are used in the complete standard. Many of the
modem signal s are not needed when a computer terminal is connected directly to a
computer, and Figure 1 illustrates how some of the "spare" pins should be linked if not needed.
Figure 1 also illustrates the pin numbering used in the original DB-25 connector and that now
commonly used with a DB-9 connector normally used in modern computers Specifying
compliance to RS-232 only establishes that the signal levels in two devices will be
compatible and that if both devices use the suggested connector, they may be able to be
connected. Compliance to RS-232 does not imply that the devices will be able to
communicate or even acknowledge each other's presence.
59
60
Electrical Characteristics: The RS-232-C specifies the signaling rate between the DTE and DCE,
and a digital signal is used on all interchange circuits. The RS-232 standard specifies that logic
"1" is to be sent as a voltage in the range -15 to -5 V an d that logic "0" is to sent as a voltage
in the range +5 to +15 V. The standard specifies that voltages of at least 3 V in amplitude will
always be recognized correctly at the receiver according to their polarity , so that appreciable
attenuation along the line can be tolerated. The transfer rate is rated > 20 kbps and a distance of <
15m. Greater distance and data rates are possible with good design , but it is reasonable to
assume that these limits apply in practice as well as in theory. The load impedance of the
terminator side of the interface must be between 3000 and 7000 ohms, and not more than 250p
61
CHAPTER-8
DC MOTOR & ITS DRIVER
8.1 DC Motor interfacing with Microcontrollers
Whenever a robotics hobbyist talk about making a robot, the first thing comes to his mind
is making the robot move on the ground. And there are always two options in front of the
designer whether to use a DC motor or a stepper motor. When it comes to speed, weight, size,
cost... DC motors are always preffered over stepper motors. There are many things which you can
do with your DC motor when interfaced with a microcontroller. For example we can control the
speed of motor, we can control the direction of rotation, we can also do encoding of the rotation
made by DC motor i.e. keeping track of how many turns are made by our motors etc. So we can
see DC motors than a stepper motor. are no less In this part of tutorial we will learn to interfacing
a DC motor with a microcontroller. Usually H-bridge is preffered way of interfacing a DC
motor. These days many IC manufacturers have H-bridge motor drivers available in the market
like L293D is most used H-Bridge driver IC. H-bridge can also be made with the help of
trasistors and MOSFETs etc. rather of being cheap, they only increase the size of the design
board, which is somtimes not required so using a small 16 pin IC is preffered for this purpose.
8.2 Working Theory of H-Bridge
The name "H-Bridge" is derived from the actual shape of the switching circuit which
control the motoion of the motor. It is also known as "Full Bridge". Basically there are four
switching elements in the H-Bridge as shown in the figure below.
62
As we can see in the figure above there are four switching elements named as "High side left",
"High side right", "Low side right", "Low side left". When these switches are turned on in pairs
motor changes its direction accordingly. Like, if we switch on High side left and Low side right
then motor rotate in forward direction, as current flows from Power supply through the motor coil
goes to ground via switch low side right. This is shown in the figure below.
Similarly, when we switch on low side left and high side right, the current flows in opposite
direction and motor rotates in backward direction. This is the basic working of H-Bridge. We can
also make a small truth table according to the switching of H-Bridge explained above.
63
Truth Table
High Left High Right Low Left Low Right Description
On Off Off On Motor runs clockwise
Off On On Off Motor runs anti-clockwise
On On Off Off Motor stops or decelerates
Off Off On On Motor stops or decelerates
As already said, H-bridge can be made with the help of trasistors as well as MOSFETs, the only
thing is the power handling capacity of the circuit. If motors are needed to run with high current
then lot of dissipation is there. So head sinks are needed to cool the circuit.
8.2.2 BJT Based H-Bridge for DC motors:
A simple H-bridge can be made with the help of Power BJTs like TIP31 and TIP32. An
example and a working demo of this circuit is shown in the figure next.
64
8.2.3 L293D Dual H-Bridge Motor Driver
L293D is a dual H-Bridge motor driver, So with one IC we can interface two DC motors
which can be controlled in both clockwise and counter clockwise direction and if we have motor
with fix direction of motion the we can make use of all the four I/Os to connect up to four DC
motors. L293D has output current of 600mA and peak output current of 1.2A per channel.
Moreover for protection of circuit from back EMF ouput diodes are included within the IC. The
output supply (VCC2) has a wide range from 4.5V to 36V, which has made L293D a be the best
choice for dc motor driver A simple schematic for interfacing a DC motor using L293D is shown
below.
65
As we can see in the circuit, three pins are needed for interfacing a DC motor (A, B, Enable). If
we want the o/p to be enabled completely then you can connect Enable to VCC and only 2 pins
needed from controller to make the motor work.
As per the truth mentioned in the image above its fairly simple to program the microcontroller. Its
also clear from the truth table of BJT circuit and L293D the programming will be same for both
of them, just keeping in mind the allowed combinations of A and B.
8.3 Principles of operation of dc motor:
In any electric motor, operation is based on simple electromagnetism. A current-carrying
conductor generates a magnetic field; when this is then placed in an external magnetic field, it
will experience a force proportional to the current in the conductor, and to the strength of the
66
external magnetic field. As you are well aware of from playing with magnets as a kid, opposite
(North and South) polarities attract, while like polarities (North and North, South and South)
repel. The internal configuration of a DC motor is designed to harness the magnetic interaction
between a current-carrying conductor and an external magnetic field to generate rotational
motion.
Let's start by looking at a simple 2-pole DC electric motor (here red represents a magnet or
winding with a "North" polarization, while green represents a magnet or winding with a "South"
polarization).
Every DC motor has six basic parts -- axle, rotor (a.k.a., armature), stator, commutator, field
magnet(s), and brushes. In most common DC motors (and all that BEAMers will see), the
external magnetic field is produced by high-strength permanent magnets1. The stator is the
stationary part of the motor -- this includes the motor casing, as well as two or more permanent
magnet pole pieces. The rotor (together with the axle and attached commutator) rotate with
respect to the stator. The rotor consists of windings (generally on a core), the windings being
electrically connected to the commutator. The above diagram shows a common motor layout --
with the rotor inside the stator (field) magnets.
The geometry of the brushes, commutator contacts, and rotor windings are such that when power
is applied, the polarities of the energized winding and the stator magnet(s) are misaligned, and the
67
rotor will rotate until it is almost aligned with the stator's field magnets. As the rotor reaches
alignment, the brushes move to the next commutator contacts, and energize the next winding.
Given our example two-pole motor, the rotation reverses the direction of current through the rotor
winding, leading to a "flip" of the rotor's magnetic field, driving it to continue rotating.
In real life, though, DC motors will always have more than two poles (three is a very common
number). In particular, this avoids "dead spots" in the commutator. You can imagine how with
our example two-pole motor, if the rotor is exactly at the middle of its rotation (perfectly aligned
with the field magnets), it will get "stuck" there. Meanwhile, with a two-pole motor, there is a
moment where the commutator shorts out the power supply (i.e., both brushes touch both
commutator contacts simultaneously). This would be bad for the power supply, waste energy, and
damage motor components as well. Yet another disadvantage of such a simple motor is that it
would exhibit a high amount of torque "ripple" (the amount of torque it could produce is cyclic
with the position of the rotor).
So since most small DC motors are of a three-pole design, let's tinker with the workings of one
via an interactive animation (JavaScript required):
we'll notice a few things from this -- namely, one pole is fully energized at a time (but two others
are "partially" energized). As each brush transitions from one commutator contact to the next, one
coil's field will rapidly collapse, as the next coil's field will rapidly charge up (this occurs within a
68
few microsecond). We'll see more about the effects of this later, but in the meantime you can see
that this is a direct result of the coil windings' series wiring:
There's probably no better way to see how an average DC motor is put together, than by just
opening one up. Unfortunately this is tedious work, as well as requiring the destruction of a
perfectly good motor
69
70
CHAPTER-9
ADVANTAGES & DISADVANTAGES
9.1 The Advantages
The greatest advantage of DC motors may be speed control. Since speed is directly
proportional to armature voltage and inversely proportional to the magnetic flux produced by the
poles, adjusting the armature voltage and/or the field current will change the rotor speed .
Today, adjustable frequency drives can provide precise speed control for AC motors, but they do
so at the expense of power quality, as the solid-state switching devices in the drives produce a
rich harmonic spectrum. The DC motor has no adverse effects on power quality .
9.2 The drawbacks
• Power supply, initial cost, and maintenance requirements are the negatives associated with DC
motors
• Rectification must be provided for any DC motors supplied from the grid. It can also cause
power
quality problems.
• The construction of a DC motor is considerably more complicated and expensive than that of
an
AC motor, primarily due to the commutator, brushes, and armature windings. An induction
motor
requires no commutator or brushes, and most use cast squirrel-cage rotor bars instead of true
windings — two huge simplifications .
71
CHAPTER-10
CONCLUSION
MATLAB has evolved from a powerful matrix calculation application into a universal
programming tool used extensively within scientific and engineering communities both
commercial and academic. MATLAB versions 6.x and 7.x include functionality for
developing advanced graphical user interfaces, GUIs, and real-time animation and graphics.
GUI applications offer many advantages for users who wish to solve complex problems by
providing interactivity and visual feedback. Some common examples of application areas
where GUI development is desirable: .Image and Video Processing .Signal
Processing .Communications .Simulation of Complex Systems .Instrumentation and Data
Acquisition Interfaces .Control Systems .Financial Analysis .Animation of 2D or 3D
Graphical Data This text introduces you to the capabilities of MATLAB for GUI
development and covers the following areas in detail: .Handle Graphics programming and
low-level GUIs .High-level GUI development using GUIDE .The structure of GUIs including
event processing, callbacks, timers, and real-time animation of plots / data .Advanced GUI
architectures including multiple figure GUIs and image mapped interface controls
Instructional examples and exercises are provided throughout each chapter that offers a
hands-on approach to learning MATLAB GUI development. The M-file code for each
example and exercise solution is available for download on the web to help you quickly learn
how to develop your own GUIs!
72
CHAPTER-11
REFRENCES
http://www.mathworks.com/products/matlab/
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/peaks.html
http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?
objectId=5439&objectType=file
http://www.mathworks.com/access/helpdesk/help/techdoc/creating_guis/
creating_guis.html?BB=1
www.Wikipedia.org
www.ieee.com
http://www.wisc-online.com
http://www.8051projects.net/
http://www.solarbotics.net/
www.matpic.com
73