Vous êtes sur la page 1sur 36

1 | P a g e

OPTIKA

Image Guided Robot Tutorial
Contents:
1. MATLAB
Beginning with the basics
o Constructing a simple matrix
o Colon operator
o Trigonometric functions
o Inverse trigonometric functions
Operators
o Relational operators
o Logical operators
Important commands
Control statements
o For loop
o While loop
o If-else loop
o Switch-case
Making m-file

2. KNOW YOUR HARDWARE

3. IMAGE PROCESSING BASICS

4. IMAGE PROCESSING AND ROBOTICS
Image acquisition
Isolating the area of interest
Noise removal
Commanding the robot



2 | P a g e

Lets begin!!!

The purpose of this tutorial is to present basics of MATLAB. We do not assume any prior
knowledge of this package. At the later part of this tutorial we will discuss some basic concepts
of image processing and interfacing with parallel and serial ports.
Our aim is to design a vision based robot. A webcam or camera serves as an eye for the robot
and sends feedback to system. This camera can be onboard or overhead depending upon the
nature of task to be performed.

Above shown figure is the basic control system of any autonomous robot. One key point to
note is that Image Processing has huge computational requirements, and it is not possible to
run an image processing code directly on a small microcontroller. Hence, for our purpose, the
simplest approach would be to run the code on a computer, which has a webcam connected to
it to take the images, and the robot is controlled by the computer via serial or parallel port.
MATLAB

MATLAB stands for MATrix LABoratory. MATLAB is an interactive system whose basic data
element is an array (matrix) that does not require dimensioning. Hence, an image (or any other
data like sound, etc.) can be converted to a matrix and then various operations can be
performed on it to get the desired results and values.
Image processing is quite a vast field to deal with. We can identify colors, intensity, edges,
texture or pattern in an image. In this tutorial we will focus on some basic concepts only.


3 | P a g e

Beginning from the basic:

Component of MATLAB 2009 window are:



There are 4 main windows:
Command window: This is the main window where you write the commands, as well as see the
outputs. In other words, here is your interaction with the software.
Command History: As the name suggests, it shows the list of the commands recently used in
chronological order. Hence, you can double click on a command to execute it again.


4 | P a g e

Current directory: It is the default directory (folder) for saving your files. All the files which you
make (like m-files, as discussed later) are saved here and can be accessed from here directly.
The location of the current directory is shown in the toolbar at the top. You can change it by
changing the address here.
Workspace: It displays the list of the variables defined by you in the current session of MATLAB.
The Menu bar and Toolbar:



The toolbar has buttons for common operations like cut, copy, paste, undo, redo. The most
important button here is the HELP button.
Lets start by typing something in command window, say a simple addition

In above snap shot a and b variables have been assigned values 1 and 3 respectively. One
important thing that you can notice is the use of ; (semicolon operator) while assigning value
for b. semicolon operator does not return any value. Similarly a is added to b and assigned
to variable c and so on. One special feature of MATLAB is variable declaration is not required.


5 | P a g e

All the values are stored in form of a matrix so we can say that a, b, c and are all a matrix of
dimension 1X1. Similarly we can also create a matrix with mxn dimensions. Everything in
MATLAB is also stored as matrix, even images.
Constructing a simple matrix:
To start a new row, terminate the current row with a semicolon:
A = [row
1
; row
2
; ...; row
n
]
This example constructs a 3 row, 5 column (or 3-by-5) matrix of numbers. Note that all rows
must have the same number of elements:
A = [12 62 93 -8 22; 16 2 87 43 91; -4 17 -72 95 6]
A =
12 62 93 -8 22
16 2 87 43 91
-4 17 -72 95 6
We refer to a particular element of the matrix by giving its indices in parenthesis ().
>>A(2,1)
Ans=
16
To call a given row
>>A(2,:)
Ans
16 2 87 43 91

Similarly we can get a column
For above matrix now try the command
>>A(:,2:3)
and see what you get.


6 | P a g e

The colon operator (:) :
The colon is one of the most useful operators in MATLAB. It can create vectors, subscript arrays,
and specify for iterations. In a very crude language, we can say that the colon (:) means
throughout the range.

j:k is the same as [j,j+1,...,k]
j:i:k is the same as [j,j+i,j+2i, ...,k]
A(:,j) is the jth column of A
A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k)
A(:) is all the elements of A, regarded as a single column
Some important functions
Trigonometric functions:
For angle in radians-

>> sin(1)
ans =
0.8415

For angle in degrees-

>> sind(30)
ans =
0.5000

Inverse trigonometric functions:

>> asin(1)
ans =
1.5708
>> asind(.5)
ans =
30.0000

Similarly we have cos(), cosd(), acos(), tan(),etc.


7 | P a g e


Operators:

Relational operators:
== equal to
~= not equal to
< less than
greater than
<= less than or equal to
>= greater than or equal to
Logical operators :
& AND
| OR
~ NOT
xor EXCLUSIVE OR

Some important commands
who- It lists the variables in the current workspace.
whos -WHOS is a long form of WHO. It lists all the variables in the current workspace,
together with information about their size, bytes, class, etc.
clc -Clears the command window and homes the cursor
clear- Removes all variables from the workspace.
size- Size of array.
length(): Returns the length of a vector. For an array, it returns the size of the longest
dimension.
min(): Returns smallest elements in an array.
Syntax: C = min(A)
If A is a matrix, min(A) treats the columns of A as vectors, returning a row vector
containing the minimum element from each column.
Similarly we have max() function.


>


8 | P a g e

sort(): Sorts array elements in ascending or descending order
Syntax:
B=sort(A, mode)
where value of mode can be
'ascend' : Ascending order (default)
'descend' : Descending order
plot(): Creates a 2-D line plot.
zeros(): Create array/matrix of all zeros.
B = zeros(n) returns an n-by-n matrix of zeros.
B = zeros(m,n) returns an m-by-n matrix of zeros.

Control statements
To control the flow of commands, the makers of MATLAB supplied four devices a programmer
can use while writing his/her computer code

The for loops
The while loops
The if-else-end constructions
The switch-case constructions


FOR loop
Syntax of the for loop is shown below

for k = array
commands
end

The commands between the for and end statements are executed for all values stored in the
array.

WHILE loop
Syntax of the while loop is

while expression


9 | P a g e

statements
end

This loop is used when the programmer does not know the number of repetitions are needed.

IF expression
Syntax of the IF expression is

if expression
commands
end

This construction is used if there is one alternative only.
Two alternatives require the construction

if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end.

If there are several alternatives one should use the following construction

if expression1
commands (evaluated if expression 1 is true)
elseif expression 2
commands (evaluated if expression 2 is true)
elseif
...
else
commands (executed if all previous expressions evaluate to false)
end

SWITCH-CASE expression
Syntax of the switch-case construction is

switch expression (scalar or string)
case value1 (executes if expression evaluates to value1)


10 | P a g e

commands
case value2 (executes if expression evaluates to value2)
commands
otherwise
statements
end

MAKING M-FILES
It is a provision in MATLAB where you can execute multiple commands using a single
statement. Here the group of commands is stored as a MATLAB file (extension .m).
Go to File->New->Blank M-file

MATLAB editor window opens where you can write the statements which you want to execute
and save the file. M FILE



Just by giving the name of the m file, set of instruction written in m file will be executed in a
program.


11 | P a g e

KNOWING YOUR HARDWARE
In actual practice we need to take images continuously from the current environment
using a webcam and then process them. Hence, the Image Acquisition toolbox of MATLAB
provides support in this regard. To start with working in real time, you must have a functional
USB webcam connected to your PC and its driver installed. MATLAB has built-in adaptors for
accessing these devices. An adaptor is software that MATLAB uses to communicate with an
image acquisition device. You can check if the support is available for your camera in MATLAB
by typing the following:
>> imaqhwinfo % stands for image acquisition hardware info
>> cam=imaqhwinfo;
>> cam.InstalledAdaptors
When we tried this command on our computer we got following results


To get more information about the device, type
>>caminfo = imaqhwinfo('winvideo',1)


12 | P a g e



Most probably you would have 'winvideo' installed and use that. If it is not available, use
whichever adapter is shown by imaqhwinfo.
If you are using a laptop, you may also have a webcam in it. So note down the DeviceName
shown as above. If it is not the USB webcam, then probably DeviceID = 2 should work. Hence,
type
>>caminfo = imaqhwinfo('winvideo',2)

From now onwards, I will refer Adapter by winvideo and DeviceID by 1. You must check
yourself what is available on your system and change the commands described further
accordingly. Note down the supported formats by your camera as
>>caminfo = imaqhwinfo('winvideo',1);

>>caminfo.SupportedFormats


13 | P a g e



As you can see, there are 5 supported formats in my camera. The numbers (160x120,
176x144.) denote the size of the image to be captured by the camera.
Previewing video
You can preview the video captured by the camera by defining an object (say by the name vid)
and associate it with the device.
>>vid=videoinput('winvideo',1, 'YUY2_160x120')
Or
>>vid=videoinput('winvideo',1, 'RGB24_160x120') % depends on availability
It should give information somewhat like this


14 | P a g e




vid is has been declared as the video input object, and now the camera can be referenced by
this name. To see a preview of the video through your camera, use preview command
>> preview(vid)

You can check out the preview with different formats. You will see that the size of preview
window changes. Use a format that suits your size requirement. A larger size gives greater


15 | P a g e

clarity and is easier to work with, but consumes more memory and therefore is slow. But in a
smaller image, it is difficult to differentiate between two objects.

Capturing Images

Now you have a video stream available and you need to capture still images from it. For that,
use getsnapshot() command.

>>im=getsnapshot(vid); % where vid is video input object

Here im is the 3D matrix and you can see the image by the usual imshow() command

>>imshow(im);

If you get an unexpected image (with shade of violet/green/pink and low clarity) as shown
below,

there is nothing to worry. You must be using a format starting with YUY2_... which means that
your image is in YCbCr format and not RGB format. Therefore, you must convert it in RGB
format by using

>>im=ycbcr2rgb(im);
>>imshow(im);



16 | P a g e

If a format somewhat like RGB24_160x120 (anything starting with RGB24_....) is used, then
you directly get the image in RGB format. If you want to store an image captured, so that you
can view it later (like .jpg, .png, .bmp), you can use imwrite()

>>imwrite(im,'myimage.jpg');

The file myimage.jpg is saved in the current working directory.

*Note: It takes time for the camera to be active and sufficient light to enter it after giving
preview() command. Hence, there should be a time gap of 2-3 seconds between preview() and
getsnapshot(). If you are typing in command window, then you can maintain this time gap
manually. But generally you will use these commands in an m-file, hence, the delay must be
given using pause() command. Also in a vision based robot, the images have to be taken
continuously, so use an infinite loop.

vid= videoinput('winvideo',1, 'YUY2_160x120');
preview(vid); pause(3);
while(1) img=getsnapshot(vid); % Do all image processing and analysis here
end

Once you have the image matrix im, you can perform all the operations like extracting region
of particular colors, finding their centroid and area, etc. by the methods described previously.
SIGH! Now sufficient Image Processing has been learnt. Great! What next? Something apart
from image processing must be known to make and run the robot. Without the knowledge of
motors no matter how good you have programed your bot, it will not move as you want it to.
So, next question arises How to run a dc motor or stepper motor?

Motor
D.C. motor



17 | P a g e


For controlling the dc motor we need some kind of motor driving IC. L293D is good option for
this purpose. It is a 16 pin chip and its pin configuration is shown below



Driving D.C. Motors with the L293D
This chip is designed to drive two motors in clockwise and anticlockwise direction. There are 2
input and 2 output pins for each motor. The connection are shown below




18 | P a g e

The behavior of motor for various input condition are as follows

Input A Input B Output
0 0 Motor stops or breaks
0 1 Motor runs anti-clockwise
1 0 Motor runs clockwise
1 1 Motor stops or breaks

STEPPER MOTOR
Introduction to Stepper Motors

A stepper motor is a permanent magnet or variable reluctance dc motor that has the following
performance characteristics:
1. Rotation in both directions,
2. Precision angular incremental changes,
3. Repetition of accurate motion or velocity profiles,
4. A holding torque at zero speed, and
5. Capability for digital control.


19 | P a g e

A stepper motor can move in accurate angular increments known as steps in response to the
application of digital pulses to an electric drive circuit from a digital controller. The number and
rate of the pulses control the position and speed of the motor shaft. Generally, stepper motors
are manufactured with steps per revolution of 12, 24, 72, 144, 180, and 200, resulting in shaft
increments of 30, 15, 5, 2.5, 2, and 1.8 degrees per step. Stepper motors are either bipolar,
requiring two power sources or a switchable polarity power source, or unipolar, requiring only
one power source.
Driving Stepper Motors with the L293D
The L293D contains two H-bridges for driving small DC motors. It can also be used to drive
stepper motors because stepper motors are, in fact, two (or more) coils being driven in a
sequence, backwards and forwards. One L293D can, in theory, drive one bi-polar 2 phase
stepper motor, if you supply the correct sequence.
STEPPER CONTROLLER SCHEMATIC


Bipolar Stepper Motor
The L293D chip has 16 pins. Here is how each of the pins should be connected:


20 | P a g e

Pin 1, 9 Enable pins. Hook them together and you can either keep them high or run the motor
all the time, or you can control them with you own controller (e.g. 68HC11).
Pin 3, 6, 11, and 14 Here is where you plug in the two coils. To tell which wires correspond to
each coil, you can use a multimeter to measure the resistance between the wires. The wires
correspond to the same coil has a much lower resistance than wires correspond to different
coils. (This method only applies to bipolar stepper motors. For unipolar stepper motors, you
have to
refer to the spec. sheet to tell which wires correspond to each coil.) You can then get one coil
hooked up to pin 3,6 and another one hooked up to pin 11, 14.
Pin 4, 5, 12, and 13 Gets hooked to ground.
Pin 8 Motor voltages, for the motors we are using, it is 12V.
Pin 16 +5V. It is the power supply of the chip and it's a good idea to keep this power supply
separate from your motor power.
Pin 2, 7, 10, and 15 Control signals. Here is where you supply the pulse sequence. The following
is how you pulse them for a single-cycle (to move the motor in the opposite direction, just
reverse the steps. i.e. from step 4 to step1):

Coil 1a Coil 2a Coil 1b Coil 2b
Step 1 High High Low Low
Step 2 Low High High Low
Step 3 Low Low High High
Step 4 High Low Low High





BASICS OF IMAGE PROCESSING

Before entering into details of image processing let us get acquainted with basic terminology of
images:


21 | P a g e

Pixel: Pixels are the building blocks of an image. In other words, a pixel is the smallest possible
image that can be depicted on your screen.
Binary Image: An image that consists of only black and white pixels.

A binary image
Grayscale Image: It contains intensity values ranging from a minimum (depicting absolute
black) to a maximum (depicting absolute white) and in between varying shades of gray.
Typically, this range is between 0 and 255.

A Grayscale Image
*Note: In daily language what we refer to as black-and-white (as in old photos) are actually
grayscale. Hence avoid confusion here in technical terms.



22 | P a g e

Color Image: We all have seen this! Such an image is composed of the three primary colors,
Red, Green and Blue, hence also called an RGB image


A color image
RGB value: All colors which we see around us can be made by adding red, blue and green
components in varying proportions. Hence, any color of the world can uniquely be described by
its RGB value, which stands for Red, Blue and Green values. This triplet has each value ranging
from 0 to 255, with 0 obviously meaning no component of that particular color and 255
meaning full component. For example, pure red color has RGB value [255 0 0], pure white has
[255 255 255], pure black has [0 0 0] and has RGB value [255 135 105].


Above images are preloaded in MATLAB directory. You can check them out yourself. Try typing
>> I = imread('circles.png');
>> imshow(I)
In command window and see what you get.
Similarly try
>> I = imread('cameraman.tif');
>> imshow(I)
And
>> I = imread('peppers.png');
>> imshow(I)





23 | P a g e

Representation of an Image in MATLAB
An image in MATLAB is stored as a 2D matrix (of size mxn) where each element of the matrix
represents the intensity of light/color of that particular pixel. Hence, for a binary image, the
value of each element of the matrix is either 0 or 1 and for a grayscale image each value lies
between 0 and 255. A color image is stored as an mxnx3 matrix where each element is the RGB
value of that particular pixel (hence its a 3D matrix). You can consider it as three 2D matrices
for red, green and blue intensities.


IMAGE PROCESSING AND ROBOTICS
Controlling a bot using image processing involves a whole lot of steps which can be broadly
classified into following stages





i
Image Acquisition

Isolating the area of Interest

Noise Removal

Commanding the Bot


24 | P a g e

STAGE 1: IMAGE ACQUISITION

Some important commands-
imread : to read an image
eg i=imread(name.jpg);
where i is a matrix. If the file is in the current directory , then you only need to write
the filename, else you need to write the complete path. Filename should be with
extension (.jpg, .bmp,..). There are some default images of MATLAB like peppers.png.
You can try reading them as
>>i=imread('peppers.png');
It is always advised to use a semi-colon (;) at the end of the statement of reading an image, else
an entite matrix representation of image appers

imshow : to view the image
eg imshow(i);

im2bw : converts a coloured image to black and white
eg b=im2bw(i);

Using image tool box



Whenever imshow command is executed the image opens in a new window with toolbar as
shown above

Data cursor: To see the values of the colors in the figure window, go to Tools>Data Cursor (or
select from the toolbar), and click over any point in the image. You can see the RGB values of
the pixel at location (X,Y).

A better option of data cursor is the function imtool(). Type the following
>>imtool(peppers.png);
and see the pixel info on lower left corner as you move mouse pointer over different pixels.



25 | P a g e

STAGE 2: ISOLATING AREA OF INTEREST

For a bot based on image processing distinguishing and separating colors, areas and boundaries
are very important. From these properties bot identifies it surrounding and executes the task
for which it is built.

Identifying and separating colors

Colors are distinguished on the basis of their RGB values and with the help of these values one
color can be separated from the others
In the given example, following function takes the input as a colored image and returns a
binary image where the blue pixels have been replaced as white, rest are black.

[m,n,t]=size(im);
binblue=zeros(m,n); num=0;
for i=1:m
for j=1:n
if(im(i,j,1)==0 && im(i,j,2)==0 && im(i,j,3)==255)
%Red and Green components must be zero and blue must be full
binblue(i,j)=1; num=num+1;
end
end
imshow(binblue);
end


As you can see, this is a binary image with white pixels at those coordinates which were blue in
input image.


26 | P a g e

Now this was an ideal image where each color was perfect. But in practice, you dont have
images with perfect colors. So, we give a range of RGB values to extract our required region of
image.

Some important commands-

Regionprops: - Measures a set of properties for each connected component (object) in the
binary image using this command following Shape Measurements can be done

'Area' 'EulerNumber' 'Orientation'
'BoundingBox' 'Extent' 'Perimeter'
'Centroid' 'Extrema' 'PixelIdxList'
'ConvexArea' 'FilledArea' 'PixelList'
'ConvexHull' 'FilledImage' 'Solidity'
'ConvexImage' 'Image' 'SubarrayIdx'
'Eccentricity' 'MajorAxisLength'
'EquivDiameter' 'MinorAxisLength'

Syntax- s = regionprops(BW, 'property');
for example if you want to locate centroid of any object in a picture you can use the following
command
s = regionprops(BW, 'centroid');

Bwlabel: - Label connected components in 2-D binary image
Syntax-
L = bwlabel(BW, n)
L = bwlabel(BW, n) returns a matrix L, of the same size as BW, containing labels for the
connected objects in BW. The variable n can have a value of either 4 or 8, where 4 specifies 4-
connected objects and 8 specifies 8-connected objects. If the argument is omitted, it defaults to
8.
The elements of L are integer values greater than or equal to 0. The pixels labeled 0 are the
background. The pixels labeled 1 make up one object; the pixels labeled 2 make up a second
object; and so on.
You can also use [L, num] = bwlabel(BW,n).It returns in num the number of connected objects
found in BW.


27 | P a g e

Imcrop: -it creates an interactive Crop Image tool associated with the image displayed in the
current figure, called the target image. The Crop Image tool is a moveable, resizable rectangle
that you can position interactively using the mouse.
Syntax-
I = imcrop(im)

bwboundries: -traces the exterior boundary of objects, as well as boundaries of holes inside
these objects.
Syntax-
B=bwboundaries(BW)
BW must be a binary image where nonzero pixels belong to an object and 0 pixels constitute
the background.
Bwboundaries returns B, a P-by-1 cell array, where P is the number of objects and holes. Each
cell in the cell array contains a Q-by-2 matrix. Each row in the matrix contains the row and
column coordinates of a boundary pixel. Q is the number of boundary pixels for the
corresponding region.

*It is advised to read in details about these command from MATLAB help
STAGE 3: Removing noise
To understand the concepts of removing noise from an object lets start with the shown
image(not a default image in MATLAB). From this image we want to extract only flower, not the
background





28 | P a g e

From this image we want to extract only flower, not the background, a simple program can help
us with this task

[m,n,t]=size(im);
bw=zeros(m,n);
for j=1:n
for i=1:m
if(im(i,j,1)>70 && im(i,j,2)>70 && im(i,j,3)>150); %specifying range of violet
bw(i,j)=1;
end
end
end
imshow(bw)

You can define more specific range as per your requirement. Now when we see the output
image, it looks like




29 | P a g e

Note-:To get an idea of what range of RGB values you must define, use imtool() function (or
data cursor) with the original file, move the cursor over the region which you need to extract
and note down the RGB values
Now we have to remove noise from this image
The binary image obtained above has quite a lot of noise. You need to smoothe the edges,
remove the tiny dots scattered here and there so that at last you have some countable number
of objects to work upon. There are several functions available in MATLAB to remove noise in an
Image. Some of them are (bw is the above binary image)

imclose(): Performs morphological closing operation. It fills in the gaps between two objects
and smoothe the edges. The degree and type of smoothening and joining depend on the
structuring element, i.e., the basic shape which is used to perform the operation. The
structuring element can be a disk, a diamond, a line, etc. To create a structuring element, use
strel() function.
For example,
>> se=strel('disk',5); % a disk of radius 5
>>bw=imclose(bw,se); %Perform the closing operation on original image itself
>>imshow(bw);



30 | P a g e



imfill(): Remove holes from the image Holes are background pixels surrounded by foreground
(image) pixels.
>>bw=imfill(bw,'holes');
>>imshow(bw);


For removing the spatters imopen() can be used, I have not used this command as it was not
needed in this case but in many cases it is advised to use this command
imopen(): Morphologically open the image.
Example-
>>se=strel('disk',2);


31 | P a g e

>>bw=imopen(bw,se);
>>imshow(bw);
*Note:
The purpose of these functions might not be clear at fist. Hence, it is strongly recommended
that you explore these functions yourself by trying out on different images and have a look at
these functions in MATLAB Help section also.
The sequence of performing these operations is very significant, as the subsequent operation
is performed on the converted image and not the original image. The sequence I have adopted
is NOT necessary, and you must try yourself which sequence suits your requirement.
The size and shape of structuring element is also to be determined experimentally, so that the
number of objects you get in the binary image is same as what you require. This final image
obtained in this example is still not workable, and you can try yourself to get a consolidated
image.
There are many other functions available for noise removal like imerode(), imdilate(), etc.
Please refer to MATLAB Help section for details.
An object is defined as a connected region in a binary image.














32 | P a g e

Our problem statement
In most of problem statements of robotics based on image processing, we are required to find
the centroid, area, and no. of objects of a particular color. MATLAB has in-built functions for
these tasks which operate on binary images only. Hence we create binary images corresponding
to different colors. For example, in the problem statement OPTIKA of TECHNEX 11, the image
from the top (overhead camera) looks somewhat like (again its an ideal image; the real one will
be far different and full of noise)




Now we first take a sample image of arena, note down the RGB values (using imtool()) and then
extract the regions of different color by making binary images. Then we can find the centre of
different objects using the function bwboundaries() and regionprops().




33 | P a g e


Stage 4: Commanding the robot
Instructions are sent from MATLAB to your robot via serial or parallel port. The Instrument
Control Toolbox of MATLAB can be used to access serial port (also called as COM port) and
parallel port (also called as printer port or LPT port) of a PC. Since we encourage serial port we
are providing information on serial port only. If you want to work on parallel port then it is
easier (but you will not find parallel port in the system provided to you at the event). If you are
having old PC, then you will be having both serial as well as parallel port. But in your Laptops
and latest desktops both are missing. So, you will have to go for either USB to serial or USB to
parallel converter. Both are easily available in the market. If you want to do something
interesting then you are having parallel port in your motherboard. Open your CPU and attach a
parallel port yourself. You may find the connecting device from any computer shop having old
PCs. Now we are going to tell you about how to communicate with your robot using serial port.
If you want to use USB then look for it yourself.
.
USB to serial converter


Serial and Parallel Port






34 | P a g e

Serial port and its interfacing:
A serial port has 9 pins.
Serial port transmits data bit by bit.
Advantage of using serial port is that it
needs only 2 wires to transmit data while in
parallel port, 9 wires are required. Pin 3 is
used to transmit data and of course you are
going to use ground (pin 5). At the
receivers side, a microcontroller with UART
is required. UART stands for Universal
Asynchronous receiver Transmitter.
Most of the microcontrollers (such as ATMEGA 16, PIC etc.) have a UART.
Serial port data transfer:
The serial data format includes one start bit, between five and eight data bits, and one stop bit.
A parity bit and an additional stop bit might be included in the format as well. In a serial port
data transfer LSB comes first and MSB at last. The diagram below illustrates the serial data
format:

Initially you need to check the device manager of your system (My computer-> System
properties-> Device manager-> Ports). Here you will find the name given to the serial port. Or
you can use instrhwinfo function to return the available serial ports programmatically.
Pin diagram of serial port


35 | P a g e


Before you start writing data both serial port object and instrument must have same
communication settings. Hence you need to configure specific, such as, baudrate, databits,
parity, terminator, stopbits.
We can access serial port from MATLAB by defining a serial port object, as shown below:
test = serial(a, baud rate,9600);
Different steps to write a code:
Each serial port object is associated with one serial port. For example, to create a serial port
object associated with the COM1 port,
test = serial('COM1'); % Create a serial port object
fopen(test) %Connect to the instrument
fwrite (test,'L') % move left
fwrite(test, R) % move right %Write and read data
fclose(test) %Disconnect and clean up
delete(test)
clear test;





36 | P a g e

Electronics required to use serial port:

The standard RS-232 is used for serial communication. The RS-232 standard defines the voltage
levels for logical one and logical zero levels. Valid signals are plus or minus 3 to 15 volts. But we
know that this voltage is not used as voltage level for our microcontrollers. Hence, we use IC
MAX-232 for the conversion of this voltage to the required levels (i.e. Logic 0= 0volts, Logic 1=
5volts). IC-MAX 232 is used always with 4 capacitors of capacitance of 10uf. Circuit for this
system is as follows:
Note: Tx and Rx are connected to the microcontroller.

Now you have completed all the 4 steps and are ready to solve the problem. We wish you best
of luck.




Note- For more information you can check MATLABs demos for image acquisition, image
processing and instrument control.

Vous aimerez peut-être aussi