You are on page 1of 16

Matlab Serial Communication Tutorial

Esposito 2009
Tutorial: Serial Communication in Matlab
Objective: This tutorial teaches you how to use Matlab serial objects to interact with external hardware.
Disclaimer: The tutorial is not a replacement for readin the Matlab !ocumentation on Serial "nterfacin#
nor does it con$er all the concepts and implementation details of serial communication and the %S&2'2
protocol. The examples are soley eared toward the types of applications we see in our projects such as
sendin commands to control robots( motors( or readin sensors such as )*S( laser scanners( compasses(
etc. +ther types of e,pitment may re,uire different techni,ues not co$ered here.
Contact:
-ssociate *rofessor .oel M. Esposito
esposito/usna.edu
Systems Enineerin !epartment
0nited States 1a$al -cademy(
-nnapolis( M! 22302
http455www.usna.edu50sers5weapsys5esposito5
*ae 2 of 26
Matlab Serial Communication Tutorial
Esposito 2009
Hardware Devices
- lot of external hardware de$ices are desined to connect to a *C throuh a Serial *ort. Examples in our
department include 7oala %obots( iCreate %obots( Scorbot( %obix 7its# and lots of sensors such as the Sic8
or 9o8uyo :aser Scanners( the 1orthstar 8its( )*S( Compasses( etc
Traditionally all *C;s had a serial port in the bac8. 9owe$er( now they are bein replaced by 0S< ports.
=Serial ports= ta8e many forms. >or example the ?bee modems create a wireless serial lin8. Many laptops
don;t ha$e a serial port @ just 0S< ports. 0S< to Serial Con$erters or <luetooth Connections can function
as =$irtual serial ports=( meanin that once set up correctly Matlab just $eiws them as additional serrial
ports.

Basic Concepts
Cabling:
Serial Message: Aou litterally send or reci$e data o$er this cable on a sinle pin as a series of
bytes B2 byte C D bits or 0 @ 2EEF.
o Example4 G0H G22H G2IH G32H G222H
Terminators: .ust as we use a period in Enlish to dentote the end of a sentence( we use a
=terminator= to indicate the end of a series of bytes that constitute a messae.
o The terminator can be anythin the sender and recei$er aree on but a =carrae return=
BJrF is a common choice.
Buffer: "f you don;t understand how a buffer wor8s( you will ne$er understand serial
communication. Say a sensor is streamin bac8 data to your proram( more fre,uently than your
proram reads it. +n your computer this data ets stored in somethin called a buffer( until you
decide to read it. Thin8 of a buffer as a list.
o -s new data $alues come in they et added to the bottom of the list Bmost recent dataF.
o "f your proram reads a $alue from the buffer( it starts at the top of the list Boldest dataF.
+nce you read a byte of data( it is no loner in the buffer# and the data in the second
position on the list mo$es up to the top position( etc.
o The buffer has a finite lenth Byou set itF. This means there is a limit to how lon the list
can et. +nce the buffer is totally full( what happens when the sensor tries to send new
data to the bufferK The oldest data Btop of the listF ets discarded fore$er( and all the
entries mo$e up( to ma8e room on the bottom of the list for new data.
o "f you;rer smart about usin the buffer( you can ma8e sure you ne$er miss any data. "f
your not smart about it( it is easy to loose data or use old data.
Ex4 Le create a buffer of lenth E. "nitially it is empty
2
2
'
3
E
The sensor writes a $alue B20F to it
2 10
2
'
3
E
The sensor writes another $alue B6F to it( 1ote that the oldest data is in the first position and new data fills
in the buffer from the bottom.
*ae 2 of 26
Matlab Serial Communication Tutorial
Esposito 2009
2 10
2 6
'
3
E
1ow we read a $alue from it into the $ariable x.
2 6
2
'
3
E
xC 20. 1ote that once we read the $alue it is no loner in the bufferM -lso note that we read the top
element which was the oldest data.
9ere is anothet scenario. The buffer is full
2 10
2 6
' 12
3 3
E 1
1ow the sensor writes a $alue to it B3F
2 6
2 12
' 3
3 1
E 4
The oldest data( in the top entry( B20F is discarded fore$er and all the entries shift up 2 spot( to ma8e room
for the new $alue B3F.
Message Length and Check Sum: "t;s $ery possible( especially when you use wireless serial
connections that indi$idual bytes in the messae can et lost or arbled. There are a lot of
complex schemes out there to chec8 that this doesn;t happen. 9ere are two common ones that
show up in some serial command interfaces.
o +ne of the bytes in the messae miht indicate the lenth of the messae Bthe total
number of bytes the messae should containF.
o -nother byte miht be a chec8sum. - chec8sum is a number computed usin a simple
arithmetic formula that can help you determine if the messae has been arbled. 9ere is
an example4 Chec8Sum C 2EE @ Sum of all data bytes in messae.
o +n the recei$in end you can chec8 that the lenth and chec8sum for the messae you
recei$ed match the actual messae. "f they don;t( you can decide to discard the messae
or re,uest new data from the de$ice.
*ae ' of 26
Matlab Serial Communication Tutorial
Esposito 2009
o Example4 G3H G2E'H G2H G2H where 3 is the lenth Bincludes lenth and chec8sum bytesF(
G2H G2H are the data bytes Bmeanin depends on what the sensor doesF( and 2E' C 2EE @
B2N2F is the chec8sum Bdoes not include itself or lenth byteF.
Streaming vs. polling:
o *ollin a sensor is simple. Aou send it a messae re,uestin some data each time you
want to ta8e a measurement# then it returns a messae containin that data.
o Streamin means that you send the sensor a messae to turn it on. Then it beins
sendin bac8 measurements as it ets them @ usually at a reular inter$al

What You Need to Know Before You Continue
)o the computer you will use( your de$ice( and all the documentation that came with it.
Find the Serial Port on the *C. "f there is none( use a 0S<&to&Serial Con$erter. Aou may ha$e
to install dri$ers for it. Connect the de$ice to the *C.
CM Port !umber4 Each serial port on the *C is labeled C+M2( C+M2( etc. Aou need to
fiure out which one you;re attached to.
o "f there is a serial port at the bac8 of the computer( chances are it;s C+M2. 9owe$er(
e$en if there is only 2 serial port $isible in the bac8( its possible its C+M2( or C+M'
especially if there is a modem.
o "f you use a con$erter or blue tooth the port number ets assined in software and may
chane each time you disconnect or reconnect the de$ice. +n Lindows ?* Bor $ista
classic $iewF( o to Control Panel"S#stem"$ard%are"&eviceManager"Ports"Comm Ports
and $erify which port your de$ice was assined
&evice Settings4 )o to the documentation that came with your de$ice and identify the
Communication settins. Le;ll need this for the next section. 9ere is an example4
o <aud %ate
o
Serial Command 'nterface (SC')4 )o to the documentation that came with your de$ice and find
the serial command interface Bmay ha$e a different nameF. "t explains how messaes are
formatted and how to interpret the results. Le;ll need this later
Setting up Serial port objects
Basic Concepts
Matlab uses a special $ariable type to 8eep trac8 of serial connections @ the Serial +bject.
0nli8e nornal $ariables which ha$e a sinle $alue( objects ha$e many =attributes= or parameters
that can be set. Bex. port number( baud rate( buffersiOe( etcF
+ne of those attributes is the port number. - label that cooresponds to which port your de$ice is
connected to.
"n order to actually send or recie$e data throuh the serial port object it must be open. Lhen not
in use it can be closed Bnot the same as deletin itF
Aou can ha$e many different serial objects in memory. They can all send and recei$e data at the
same time as lon as they are each on a different port.
There can e$en be se$eral objects associated with the same physical port. 9owe$er( only one of
those objects associated with a i$en port can actually be open Bsendin or recei$in dataF at any
time.
Creating a Serial Port Object
9ere is an example of how to do this. the only piece of information you must supply is which com port to
use. The rest of the attributes are set to some default $alues4
serialPort = serial('com1')
*ae 3 of 26
Matlab Serial Communication Tutorial
Esposito 2009
Serial Port Object : Serial-COM1
Communication Settings
Port: COM1
BaudRate: 9600
Terminator: !"
Communication State
Status: closed
RecordStatus: o##
Read$%rite State
Trans#erStatus: idle
B&tes'(ailable: 0
)aluesRecei(ed: 0
)aluesSent: 0


1ote that this list of parameters and attributes it returns is not exhausti$e.
Setting the Parameters
Most of the time you don;t want to use the default $alues. Aou can $iew or chane any attribute usin the
functions et and set.
get(serialPort, 'baudrate')
ans *
9600
set(serialPort, 'BaudRate', 19200)
get(serialPort, 'BaudRate')
ans *
19+00
This method is cumbersome if you ha$e a lot of thins you want to chane. - better way to to set them
when you create the Serial +bject.
serialPort_new = serial('com1', 'baudrate', 19200, 'terminator', 'CR')
Serial Port Object : Serial-COM1
Communication Settings
Port: COM1
BaudRate: 19+00
Terminator: CR
Communication State
Status: closed
RecordStatus: o##
Read$%rite State
Trans#erStatus: idle
B&tes'(ailable: 0
)aluesRecei(ed: 0
*ae E of 26
Matlab Serial Communication Tutorial
Esposito 2009
)aluesSent: 0

Aou can list as many properties as you want. The name of the property oes in sinle ,uotes Bchec8
spellinF and the $alue follows Bif the $alue is text then use sinle ,uotesF
The Parameters
To see a list of parameters and their current $alues
get(serialPort)
B&teOrder * little,ndian
B&tes'(ailable * 0
B&tes'(ailable"cn *
B&tes'(ailable"cnCount * -.
B&tes'(ailable"cnMode * terminator
B&tesToOut/ut * 0
,rror"cn *
0n/utBu##erSi1e * 21+
3ame * Serial-COM1
Object)isibilit& * on
Out/utBu##erSi1e * 21+
Out/ut,m/t&"cn *
Record4etail * com/act
RecordMode * o(er5rite
Record3ame * record6t7t
RecordStatus * o##
Status * closed
Tag * 8armin8PS
Timeout * 0
Timer"cn *
TimerPeriod * 1
Trans#erStatus * idle
T&/e * serial
9ser4ata * :;
)aluesRecei(ed * 0
)aluesSent * 0
S,R0'! s/eci#ic /ro/erties:
BaudRate * 19+00
Brea<0nterru/t"cn *
4ataBits * .
4ataTerminalRead& * on
"lo5Control * none
Parit& * none
PinStatus * :171 struct;
PinStatus"cn *
Port * COM1
Read's&ncMode * continuous
Re=uestToSend * on
Sto/Bits * 1
Terminator * !"
1ote that some $alues are just numbers( while others can only ta8e on certain $alues in a list B ex. ;on; or
;off ;F. To see a list of all paremeters with $alid choices type Bnote that the curly brace denotes the default
$alueF
set(serialPort)
*ae 6 of 26
Matlab Serial Communication Tutorial
Esposito 2009
B&teOrder: : >little,ndian? @ big,ndian ;
B&tes'(ailable"cn: string -or- #unction Aandle -or- cell arra&
B&tes'(ailable"cnCount
B&tes'(ailable"cnMode: : >terminator? @ b&te ;
,rror"cn: string -or- #unction Aandle -or- cell arra&
0n/utBu##erSi1e
3ame
Object)isibilit&: : >on? @ o## ;
Out/utBu##erSi1e
Out/ut,m/t&"cn: string -or- #unction Aandle -or- cell arra&
Record4etail: : >com/act? @ (erbose ;
RecordMode: : >o(er5rite? @ a//end @ inde7 ;
Record3ame
Tag
Timeout
Timer"cn: string -or- #unction Aandle -or- cell arra&
TimerPeriod
9ser4ata

S,R0'! s/eci#ic /ro/erties:
BaudRate
Brea<0nterru/t"cn: string -or- #unction Aandle -or- cell arra&
4ataBits
4ataTerminalRead&: : >on? @ o## ;
"lo5Control: : >none? @ Aard5are @ so#t5are ;
Parit&: : >none? @ odd @ e(en @ mar< @ s/ace ;
PinStatus"cn: string -or- #unction Aandle -or- cell arra&
Port
Read's&ncMode: : >continuous? @ manual ;
Re=uestToSend: : >on? @ o## ;
Sto/Bits
Terminator

Suggestions on Parameters
Some of these you don;t really need to chane. +thers you will want to chane.
Always Set
Aou always ha$e to set this to match what is specified in the documentation that came with your de$ice.
Baud*ate
Always Check
The defaults here are usually +7( but you should chec8 that they match whate$er is specified in the de$ice
documentation.
Terminator Bsometimes ha$e to chaneF ;:>; is linefeed( ;C%; is carrae return( etc
Flo%Control Bdefaults usually +7F
Parit# Bdefaults usually +7F
&ataBits Bdefaults usually +7F
B#terder Bmore on this laterF
*ae I of 26
Matlab Serial Communication Tutorial
Esposito 2009
Good Idea To Set
Aour de$ice will wor8 without settin these but you can set these to ma8e your life easy later.
Tag4 The ta is li8e i$in the serial port object a nic8name. "f ha$e a few different serial ports
open this a ood way to 8eep trac8 of them. Example( serial*ort is confiured to tal8 with a
armin )*S.
set(serialPort, 'tag', 'arminP!')
Timeut4 "f you try to read data from the serial port and there is no data in the buffer matlab will
8eep tryin to read for =Timeout= seconds Bdefault 20 secF4
get(serialPort, '"imeout')
ans *
10
This miht really slow down your code. There are ways around this( but if there is no data there
you probably don;t want to sit there for 20 seconds( so consider ma8in it smaller. +n the other
hand( it does ta8e some time for messaes to pass o$er the wire( so settin it to Oero means you
will probably miss a lot of messaes.
'nputBufferSi+e4 This specifies how lon the buffer is. The default is E22 bytes. That miht not
be lon enouh for your messaes. Especially if you thin8 the sensor will be streamin data bac8
more fre,uently than you plan on readin the buffer. %emember if the sensor tries to send data
and the buffer is full it will discard some old data and it will be one fore$er. +n the otherhand(
ha$in an unessecarliy lare buffer can be cumbersome.
Closing Serial Port Objects
Concepts
Lhen your done with a serial port object it doesn;t o away. -lso( closin it( deletin it from memory and
clearin it from the wor8space are three separate actions.
!ample Code
>or technical reasons you ha$e to use this systax to properly et rid of it4
delete(serialPort_new)
clear serialPort_new
Comprehensive Eample On Creating a !ew Port
Sometimes( if your proram does not terminate correctly you ha$e to abort BCT%:&CF before you can
properly delete or close a port. So( it is ood practice to chec8 for old serial objects before creatin new
ones4
old!erial = instr#ind('Port', 'C$%1')& ' C(ec) to see i# t(ere are
e*isting serial ob+ects (instr#ind) w(os 'Port' ,ro,ert- is set to
'C$%1'
' can also use instr#ind() wit( no in,ut arguments to #ind .// e*isting
serial ob+ects
i# (0isem,t-(old!erial)) ' i# t(e set o# suc( ob+ects is not(0) em,t-
dis,('1.R2324 C$%1 in use5 Closing5')
delete(old!erial)
end

' creating a new serial ob+ect #or m- P! (note 3 can do all t(is in one
line i# 3 wanted to
serP! = serial('C$%1')& ' 6e#ine serial ,ort
set(serP!, 'BaudRate', 7800)& ' instructions #or P! ga9e me t(is
*ae D of 26
Matlab Serial Communication Tutorial
Esposito 2009
set(serP!, '"ag', 'P!')& ' gi9e it a name #or m- own re#erence
set(serP!, '"ime$ut', 51)& '3 am willing to wait 051 secs #or data to
ari9e
' 3 wanted to ma)e m- bu##er onl- big enoug( to store one message
set(serP!, '3n,utBu##er!i:e', ;90 )
get(serP!) 'so -ou can see m- result
%'R3038: COM1 in use6 Closing6
B&teOrder * little,ndian
B&tes'(ailable * 0
B&tes'(ailable"cn *
B&tes'(ailable"cnCount * -.
B&tes'(ailable"cnMode * terminator
B&tesToOut/ut * 0
,rror"cn *
0n/utBu##erSi1e * B90
3ame * Serial-COM1
Object)isibilit& * on
Out/utBu##erSi1e * 21+
Out/ut,m/t&"cn *
Record4etail * com/act
RecordMode * o(er5rite
Record3ame * record6t7t
RecordStatus * o##
Status * closed
Tag * 8PS
Timeout * 061
Timer"cn *
TimerPeriod * 1
Trans#erStatus * idle
T&/e * serial
9ser4ata * :;
)aluesRecei(ed * 0
)aluesSent * 0
S,R0'! s/eci#ic /ro/erties:
BaudRate * -.00
Brea<0nterru/t"cn *
4ataBits * .
4ataTerminalRead& * on
"lo5Control * none
Parit& * none
PinStatus * :171 struct;
PinStatus"cn *
Port * COM1
Read's&ncMode * continuous
Re=uestToSend * on
Sto/Bits * 1
Terminator * !"

"riting To The Serial Port
*ae 9 of 26
Matlab Serial Communication Tutorial
Esposito 2009
<efore you can write to your serial port( you need to open it4
#o,en(serP!)
1ow you need to fiure out two thins from the Serial Command "nterface BSC"F that came with your
de$ice4
2. Lill you send binary data BbytesF or text BasciiFK
2. Lhat will you send to itK
"f your SC"s messaes loo8 li8e a list of numbers Bex4 G3HG2E'HG2HG2HFF( its probably the first choice. 1ote
that e$en thouh what you send is actually binary( the documentation miht list it as numbers between 0
and 2EE( or hexidecimal numbers.
"f your SC"s messaes loo8 li8e a mix of text and numbers Bex4 ;M+PE '2;F( its probably the second
choice.
Writing Binar" #ata
0se the command fwrite to send four bytes of binary data
fwriteBser)*S( G0( 22( 22I( 2E2HF#
Writing $SC% Commands
0se the command fprintf to send asci data. Aou can use a mix of text in sinle ,uotes and $ariables $alues.
mo$e1um C 9D# pauseTime C 2# Q just some example data
fprintfBser)*S( ;M+PE Qd( *-0SE Qd;( Gmo$e1um( pauseTimeH F # Q note
"ts important to understand that a number( Bex. 9DF is not sent as a number. "ts actually the asci code for the
characters ;9; and ;D;.
!ample Code

#eading $rom The Serial Port
Streaming vs Polling: $lushing the %u&&er
"f you are oin to poll the de$ice Bsend it a re,uest each time you want to et dataF you don;t want to read
any old data that miht be left o$er in the buffer. This is a useful and ,uic8 way to clean it out
1 C ser%oomba.<ytes-$ailableBF#
whileB1RC0F
#readCserRoombaD3EF
3 * serRoomba6B&tes'(ailableCEF
end
#eading $ormatted 'SC(
Say my de$ice returns a text sentence li8e this
GD +61D HD B6+D TD -062
*ae 20 of 26
Matlab Serial Communication Tutorial
Esposito 2009
Lhere ? is the x position( A the y position and T is the headin.
sentence * #scan#CserialObjD IsEF I tAis reads in as a string Cuntil
a terminater is reacAedE
:7D 7PositionD &D &PositionD tD Jeading; * strreadCsentenceD IsI#IsI#Is
I#D 1D delimiterD DE
I decodes KsentenceK as stringD #loatD stringD #loatD stringD #loatK
se/erated CdelimtedE b& commas
ans *
7 * G
7Position * +61
& * H
&Position * B6+
t * T
Jeading * -062
#eading Data
Aou can use fread to read in data Bnot textF. "t can automatically format the data for you. 9ere is
an example. Say the buffer currently has 2 bytes of data in it
G2H( GDH
a * #readCserialObjD +EF
I %ill read t5o b&tes and create a (ector
a * :1F .;
"f you omit the (2 the result would be the same && it will just read until either a terminater is
reached or there is no more data in the buffer
-lternati$ely( suppose you 8now those two bytes are used to express a sinel 26&bit inteer( you
can use
a * #readCserialObjD 1D int16E
ans *
+6-
Lhich is e,ui$ilent to 2SB2E6T2F N DSB2E6T0F
1ote that e$en thouh we only =read= 2 $alue( two elements were ta8e out of the buffer since a 26
bit interer is actually composed of two bytes. To see a list of all format types( type
UU help serial5fread
Putting (t 'll Together
)ood Programming 'dvice
to ma8e your code crash resistance try4 preinitialiOatin any return $ariables( then put the readin
and writiin to the serial port inside a T %A&C-TC9 statement
!ebuinKK
*ae 22 of 26
Matlab Serial Communication Tutorial
Esposito 2009
Eample *: )PS (nitiali+ation
#unction :ser8PS; * initiali1e8arminCComPort3umberE
ITAis #unction initiali1es tAe serial /ort /ro/erl&
I #or use 5itA tAe 8armin 8PS
ICOMPORT is tAe number o# tAe serial /ort: e7 use B #or COMB
I /ort number can be cAec<ed in
I Control Panel$S&stem$Jard5are$4e(iceManager$Ports
I ser8PS out/ut is a matlab serial /ort object
I ,s/osito 6$+2$+00. 5itA code #rom regneierD bisAo/D et alF modi#ied b&
I M043 1$C !i


/ort * strcatCCOMDnum+strCComPort3umberE EF

out * instr#indCPortD /ortEF I CAec< to see i# TJ'T serial /ort is
alread& de#ined in M'T!'B
i# CLisem/t&CoutEE I 0t is
dis/C%'R3038: /ort in use6 Closing6E
i# CLstrcm/CgetCoutC1ED StatusEDo/enEE I 0s it o/enM
deleteCoutC1EEF I 0# notD delete
else I is o/en
#closeCoutC1EEF
deleteCoutC1EEF
end
end


ser8PS * serialC/ortEF I 4e#ine serial /ort
setCser8PSD BaudRateD 19+00EF I 4e#ault Baud rate o# 19+00
setCser8PSD TagD 8PSEF I gi(e it a name
setCser8PSD TimeOutD 61EF
I 5ant to ma<e tAe bu##er big enougA tAat ne5 message can al5a&s #it
ICe7am/le is B.9 cAaracters long but messsage lengtA is (ariableE
I but not so big as to Aold + messages
setCser8PSD Out/utBu##erSi1eD #loorCB.9N162E EF
setCser8PSD 0n/utBu##erSi1eD #loorCB.9N162E EF
#o/enCser8PSEF I O/en itF
/auseC1E I gi(e it a second to start getting data
dis/C8armin 0nitiali1edE
Eample *: #ead )PS
#unction :latD lon; * Read8arminCser8PSE
I Reads a streaming 8PS6 0# no dataD does not 5aitD returns nans6
I 3ote tAat tAis code ne(er crasAes6 ,(en i# tAe 8PS unit dies or
gets un/luggedD or cant #ind satelites6
I serial /ort must #irst be initiali1ed using initiali1e8armin
I in/uts: ser8PS C#rom initiali1e8arminE
I Out/uts: 7 ClonE and &ClatE

II initiali1e to nanD 5ill Aa(e sometAing to return e(en i# serial
comms #ail
lat *nanF lon * nanF
*ae 22 of 26
Matlab Serial Communication Tutorial
Esposito 2009
II 0" TJ,R, 0S 3O 4'T'M
i# CgetCser8PSD B&tes'(ailableE**0E
dis/C4ata not a(ail &et6 Tr& again or cAec< transmitter6E
return
end

II 0" TJ,R, 0S 4'T'
5Aile CgetCser8PSD B&tes'(ailableEL*0E
tr&
I read until terminator
sentence * #scan#Cser8PSD IsEF
3s * lengtACsentenceEF


I Ma<e sure Aeader is tAere
i# strcm/CsentenceC1:6EDO8PRMCE

:/re#i7RMCDtimeRMCD'cti(eRMCDlatDlatdirRMCDlonDlondirRMCDs/dPnotsD'ngle4
eg; * strreadCsentenceD IsI#IsI#IsI#IsI#I#D 1D delimiterD DEF

I tAese cases mean tAat tAe 8PS cant #ind satelities
I Cstatus not e=ual to ' Cacti(eE
I or tAe sentence 5asnt long enougA to #ill in lat and lon
i# isem/t&ClatE@@C'cti(eRMC>1? L*'E
lat * nanF
end
i# isem/t&ClonE@@C'cti(eRMC>1? L*'E
lon * nanF
end
end

catcA ,RRQMS8
I i# sometAing didnt 5or< correctl& tAe error message dis/la&s
dis/C,rror Reading 4ataR CAec< 9nitE

end

end
*ae 2' of 26
Matlab Serial Communication Tutorial
Esposito 2009
Eample ,: (nitiali+e the i#obot Create
#unction :serPort; * Roomba0nitCm&QCOMEF
I initiali1es serial /ort #or use 5itA Roomba
I COMM/ort is tAe number o# tAe comm /ort
I e76 Roomba0nitC1E sets /ort * COM1
I note tAat it sets baudrate to a de#ault o# 2S600
I can be cAanged Csee SC0E6 %ill 3OT 5or< i# robot is /lugged into
I cAarger6
I 'n o/tional time dela& can be added a#ter all commands
I i# &our code crasAes #re=uentl&
global td
td * 0601F
I TAis code /uts tAe robot in S'",C1B0E modeD 5AicA means robot sto/s
I 5Aen cli## sensors or 5Aeel dro/s are trueF or 5Aen /lugged into
cAarger
Contrl * 1B+F

I ,s/osito 9$+00.

5arning o##

II set u/ serial commsD
I out/ut bu##er must be big enougA to ta<e largest message si1e
comm * strcatCCOMD num+strCm&QCOMEEF


a * instr#indC/ortDcommEF
i# Lisem/t&CaE
dis/CTAat com /ort is in use6 Closing it6E
#closeCaE
deleteCaE
end

dis/C,stablisAing connection to Roomba666EF

I de#aults at 2S600D can cAange
serPort * serialCcommDBaudRateD 2S600EF
setCserPortDTerminatorD!"E
setCserPortD0n/utBu##erSi1eD100E
setCserPortD TimeoutD 1E
setCserPortD B&teOrderDbig,ndianEF
setCserPortD TagD RoombaE

dis/CO/ening connection to Roomba666EF
#o/enCserPortEF

II Con#irm t5o 5a& connumication
dis/CSetting Roomba to Control Mode666EF
I StartR and see i# its ali(e
Start*:1+.;F
#5riteCserPortDStartEF
/auseC61E

#5riteCserPortDContrlEF
*ae 23 of 26
Matlab Serial Communication Tutorial
Esposito 2009
/auseC61E
I ligAt !,4S
#5riteCserPortD:1B9 +2 0 1+.;EF

I set song
#5riteCserPortD :1-0 1 1 -. +0;EF
/auseC0602E
I sing it
#5riteCserPortD :1-1 1;E

dis/C0 am ali(e i# m& t5o outboard ligAts came onE

con#irmation * C#readCserPortD-EE
/auseC61E
Eample ,: #ead all sensors &rom the Create-
#unction :Bum/RigAtD Bum/!e#tD Bum/"rontD %allD (irt%allD Cli##!#tD 666
Cli##RgtD Cli##"rnt!#tD Cli##"rntRgtD !e#tCurrO(erD RigAtCurrO(erD
666
4irt!D 4irtRD ButtonPla&D Button'd(D 4istD 'ngleD 666
)oltsD CurrentD Tem/D CAargeD Ca/acit&D /CAarge; *
'llSensorsReadRoombaCserPortEF
I Reads all +B Roomba Sensors #rom a single data /ac<et6 )alues are
I :Bum/RigAt C0$1ED Bum/!e#tC0$1ED Bum/"rontC0$1ED %allC0$1ED
(irt%allC0$1ED Cli##!#tC0$1ED 666
I Cli##RgtC0$1ED Cli##"rnt!#tC0$1ED Cli##"rntRgtC0$1ED !e#tCurrO(er
C0$1ED RigAtCurrO(erC0$1ED 666
I 4irt!C0$1ED 4irtRC0$1ED ButtonPla&C0$1ED Button'd(C0$1ED 4ist
Cmeters since last callED 'ngle Crad since last callED 666
I )olts C)ED Current C'm/sED Tem/ CcelciusED CAarge Cmilliam/AoursED
Ca/acit& Cmilliam/AoursED /CAarge C/ercentE;
I Can add otAers i# &ou li<eD see code
I ,s/osito B$+00.
5arning o##
global td
sensorPac<et * :;F
I #lusAing bu##er
con#irmation * C#readCserPortD1EEF
5Aile Lisem/t&Ccon#irmationE
con#irmation * C#readCserPortD+6EEF
end


II 8et C1-+E '!!C0E data #ields
#5riteCserPortD :1-+ 0;EF

II Read data #ields
Bm/%Ae4r/s * dec+binC#readCserPortD 1ED.EF I

Bum/RigAt * bin+decCBm/%Ae4r/sCendEE I 0 no bum/D 1 bum/
Bum/!e#t * bin+decCBm/%Ae4r/sCend-1EE
i# Bum/RigAtNBum/!e#t**1 I center bum/ sensor is reall& just
I le#t '34 rigAt at same time
Bum/RigAt *0F
*ae 2E of 26
Matlab Serial Communication Tutorial
Esposito 2009
Bum/!e#t * 0F
Bum/"ront *1F
else
Bum/"ront * 0F
end
%all * #readCserPortD 1E I0 no 5allD 1 5all

Cli##!#t * #readCserPortD 1E I no cli##D 1 cli##
Cli##"rnt!#t * #readCserPortD 1E
Cli##"rntRgt * #readCserPortD 1E
Cli##Rgt * #readCserPortD 1E

(irt%all * #readCserPortD 1EI0 no 5allD 1 5all

motorCurr * dec+binC #readCserPortD 1ED. EF
!o51 * motorCurrCendEF I 0 no o(er currentD 1 o(er Current
!o50 * motorCurrCend-1EF I 0 no o(er currD 1 o(er Curr
!o5+ * motorCurrCend-+EF I 0 no o(er currD 1 o(er Curr
!e#tCurrO(er * motorCurrCend-BE I 0 no o(er currD 1 o(er Curr
RigAtCurrO(er * motorCurrCend--E I 0 no o(er currD 1 o(er Curr
4irt! * #readCserPortD 1E
4irtR * #readCserPortD 1E

RemoteCode * #readCserPortD 1EF I coudl be used b& remote or to
communicate 5itA send0R command
Buttons * dec+binC#readCserPortD 1ED.EF
ButtonPla& * ButtonsCendE
Button'd( * ButtonsCend-+E

4ist * #readCserPortD 1D int16E$1000 I con(ert to MetersD signedD
a(erage dist 5Aeels tra(eled since last time called666ca/s at T$-B+
'ngle * #readCserPortD 1D int16EN/i$1.0 I con(ert to radiansD signedD
since last time calledD CC% /ositi(e

CAargeState * #readCserPortD 1EF
)olts * #readCserPortD 1D uint16E$1000
Current * #readCserPortD 1D int16E$1000 I neg sourcingD /os cAarging
Tem/ * #readCserPortD 1D int.E
CAarge * #readCserPortD 1D uint16E I in m'Aours
Ca/acit& * #readCserPortD 1D uint16E
/CAarge * CAarge$Ca/acit& N100 I Ma& be inaccurate
IcAec<sum * #readCserPortD 1E
/auseCtdE

*ae 26 of 26

You might also like