SlideShare a Scribd company logo
Matlab Serial Port
Practical notes on Matlab serial port programming
by
Roberto Meattini
PhD student in Robotics and Automatic Control @ University of Bologna
roberto [dot] meattini2 [at] unibo [dot] it
Matlab interfaces with serial ports through the
SERIAL PORT OBJECT
but first…
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
2
Serial port overview
• Serial communication
• most used low-level protocol to connect devices
• send/receive bytes in a serial way (1 bit at a time)
• Serial data format
• start bit
• 5 to 8 data bits
• parity bit
• 1 to 2 stop bits
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
3
start data data data data data data data data parity stop stop
Decription format: n. data bits – parity type – n. stop bits
Example: 8-N-2
Serial port overview (I)
• Synchronous vs. asynchronous
• sync: all transmitted bits are synchronized with a common clock
(start/stop bits are not necessary)
• async: every device has its own internal clock and data is transmitted at
arbitrary time
(start/stop bits are necessary)
• Baud rate
• n. bits transferred per second
• OS serial port
• in the following we will refer to Windows OS  COM1, COM2, …
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
4
The Matlab serial port session
• Example:
s=serial(‘COM1’)  create the serial port object
set(s,’BaudRate’,4800);  configurate properties
fopen(s);  connection to the device
fprintf(s,’*IDN?’)  read/write data
out=fscanf(s);  read/write data
fclose(s)  disconnection
delete(s)  delete port boject
clear s  clean
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
5
The serial port session (I)
• set(s)
• shows the list of all properties
• get(s)
• shows the list of all properties with respective values
• s.BaudRate
• the way to show a single property value
• set(s,’BaudRate’,4800)
• the way to set a property value
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
6
Create a Serial Port Object
• s = serial(‘<port_name>’);
• the port name depends on the OS (Windows  COM1,COM2, ...)
• instrhwinfo(‘serial’)
• it is a Control Instrument Toolbox command that return a list of available
serial port
• Once the port object is created, typing
s ,
we obtain an object display summary with
serial port obj name, communication settings,
communication state, read/write operations state
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
7
Communication settings
• BaudRate  bits per second
• DataBits  specifies n. bits to be transmitted
• Parity  specifies the parity checking type
• Terminator  specifies the termination character
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
8
Writing and reading data
• Synchronous communication
• transmission is synchronized using start and stop bits and/or a common clock
between devices
• in this case, the read/write operations block the access to the Matlab command line
• Asynchronous communication
• read/write operations are not blocking
• it is possible to read and write simultaneously
• callback functions can be used
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
9
Writing data
• Writing functions
• fprintf  writes text on the device
• fwrite  writes binary data on the device
• stopasync  stops write asynchronous operations
• Writing properties
• BytesOutput  n. bytes present in the output buffer
• OutputBufferSize  output buffer’s dimension (in bytes)
• Timeout  max waiting time to complete a write operation
• TransferStatus  indicates if an asynchronous write operation is in
progress
• ValuesSent  n. values written on the device
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
10
Writing data (I)
• Synchronous vs. asynchronous
• fprintf and fwrite are synchronous by default
• to write in asynchronous mode we have to explicit it as an argument
• example:
fprintf(s, ’<…text…>’, ’async’)
• in this case it is possible to write and read simultaneously, and to use callback functions
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
11
Reading data
• Reading functions
• fgetl  reads a text line and discards the terminator
• fgets  reads a text line and includes the terminator
• fread  reads binary data
• fscanf reads data from the device as text
• readasync  reads data asynchronously
• stopasync  stops read asynchronous operations
• Reading properties
• BytesAvailable  n. bytes available in the input buffer
• InputBufferSize  input buffer’s dimension (in bytes)
• ReadAsyncMode  specifies if an asynchronous read operation is “continuous” or
“manual”
• Timeout  max waiting time to complete a read operation
• TransferStatus  indicates if an asynchronous read operation is in progress
• ValuesReceived  n. values read from the device
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
12
Reading data (I)
• Synchronous vs. asynchronous
• if ReadAsyncMode is set to
• ‘continuous’  (default value) the Serial Port Object continuously checks if there are
available data from the device and, if it is present, stores it
asynchronously into the input buffer. Then it is possible to use a
synchronous function to transfer data to Matlab
(fget/fread/fscan)
• ‘manual’  the Serial Port Object does not check continuously the device … …
• remind: with asynchronous mode it is possible to write and read
simultaneously, and to use callback functions
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
13
Reading data (II)
• fscanf operation
• blocks access to the command line until:
• the terminator is read
• timeout is expired
• n. of specified values are read
• input buffer is full
• fread operation
• it does not care about the terminator because reads directly the number of specified
values (by default bytes). Example:
s.BytesAvailable = 69;
out = fread(s, 69)  reads directly 69 bytes and stores in the variable “out”
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
14
Callback
A function executed when an event occurs, specifying the name of the callback function as a
value of the associated callback property
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
15
Events and Callbacks
• Event: BREAK INTERRUPT
• Associated properties: BreakInterruptFcn
• the serial port generate a break interrupt when the received data stay inactive for a period
greater than a character transmission time
• Event: BYTES AVAILABLE
• Associated properties: BytesAvailableFcn
BytesAvailableFcnCount
BytesAvailableFcnMode
• if BytesAvailableFcnMode is set as ‘byte’, the callback specified in
BytesAvailableFcn is executed every time there are as many bytes as in
BytesAvailableFcnCount
• if BytesAvailableFcnMode is set as ‘terminator’, the callback is executed when
the terminator character is read
• N.b.: this event can be generated only during asynchronous read operations
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
16
Events and Callbacks (I)
• Event: ERROR
• Associated properties: ErrorFcn
• an error event occurs when read/write operation are not complited in the time specified
in Timeout
• only for asynchronous read/write
• Event: OUTPUT EMPTY
• Associated properties: OutoutEmptyFcn
• only for asynchronous write operations
• Event: PIN STATUS
• Associated properties: PinStatusFcn
• associated to the change of the values of some control pins … …
• for both sync and async operations
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
17
Events and Callbacks (II)
• Event: TIMER
• Associated properties: TimerFcn
TimerPeriod
• this event is generated when the time specified in TimerPeriod expires, starting from
the serial obj connection time; callback specified in TimerFcn is executed
• based on the “system velocity” the TimePeriod value is lower bounded
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
18
Events and Callbacks (III)
• Event information
• composed by Type and Data values specified in the callback function header
• Type  event name
• Data.AbsTime  day-month-year hour:minute:second
• for the TIMER event there is also: Data.Message  <…stringa errore…>
• more Data values for the event PIN STATUS event … …
• Executing callback functions
• we need to set the value of the callback property as the name of file with the code of
the callback
• example:
s.ByteAvailableFcnMode = ‘terminator’;
s.ByteAvailableFcn = @my_callback;
• to pass additional parameters, example: s.ByteAvailableFcn = {@my_callback,val1,val2};
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
19
Events and Callbacks (IV)
• Callback file, example:
function my_callback(obj,event[…others possible parameters …])
…
…
…
end
• If an error occurs during the callback execution
• the callback is automatically disabled
• a warning is shown
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
20
Save and loading
• myserial  file
• s  serial port obj
• out  variable with read data
save myserial s out  stores data and serial obj
load myserial  recreates s and out in the workspace
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
21
REFERENCE:
http://it.mathworks.com/help/matlab/serial-port-devices.html
by Roberto Meattini - PhD student in Robotics and Automatic
Control @ University of Bologna
22

More Related Content

PDF
Serial comm matlab
PDF
interfacing matlab with embedded systems
PPTX
Java Input and Output
PDF
C Programming - Refresher - Part III
PDF
New c sharp3_features_(linq)_part_iii
PDF
Introduction to MPI
PDF
C Programming - Refresher - Part IV
PDF
Serial comm matlab
interfacing matlab with embedded systems
Java Input and Output
C Programming - Refresher - Part III
New c sharp3_features_(linq)_part_iii
Introduction to MPI
C Programming - Refresher - Part IV

What's hot (20)

PPT
Loader
PDF
220 runtime environments
PPT
Os Reindersfinal
PDF
Introduction to c++
DOCX
Bitstuffing
PPTX
02 copy file_fill_sp16
PPTX
Design of a two pass assembler
PPT
Chapter Seven(2)
ODP
(6) collections algorithms
PDF
Generacion de codigo ensamblado
PDF
Function in C++
PPTX
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
PDF
C programming notes
PPTX
Co&amp;al lecture-05
PPTX
Cpu-fundamental of C
PPTX
FUNDAMENTAL OF C
PPTX
Co&amp;al lecture-07
PDF
C- language Lecture 5
PPTX
Co&amp;al lecture-08
PPTX
Modern C++
Loader
220 runtime environments
Os Reindersfinal
Introduction to c++
Bitstuffing
02 copy file_fill_sp16
Design of a two pass assembler
Chapter Seven(2)
(6) collections algorithms
Generacion de codigo ensamblado
Function in C++
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
C programming notes
Co&amp;al lecture-05
Cpu-fundamental of C
FUNDAMENTAL OF C
Co&amp;al lecture-07
C- language Lecture 5
Co&amp;al lecture-08
Modern C++
Ad

Similar to Matlab Serial Port (20)

PPT
Telelab 2
PDF
Control of Industrial Pneumatic & Hydraulic Systems using Serial Communicatio...
PDF
Control of Industrial Pneumatic & Hydraulic Systems using Serial Communicatio...
PPT
AN INTRODUCTION TO SERIAL PORT INTERFACING
PDF
Lecture 3 - Driving.pdf
PDF
Serial Programming
PPT
Introduction to embedded systems
PDF
Device Operation using PC by Arduino (1).pdf
PPT
Pic18 f4520 and robotics
PPTX
Serial Busses.pptx
PPS
Robotix Tutorial 8
PPTX
What Have We Lost - A look at some historical techniques
PDF
Arduino reference
PDF
Arduino - Classes and functions
PPTX
serial_busses_i2c.pptx
PPTX
5-Tut3_Networking_with_Python.pptx good intro
PPTX
Real Time Debugging - What to do when a breakpoint just won't do
DOCX
ESL report
PDF
Arduino Teaching Program
PPT
11_interface.ppt
Telelab 2
Control of Industrial Pneumatic & Hydraulic Systems using Serial Communicatio...
Control of Industrial Pneumatic & Hydraulic Systems using Serial Communicatio...
AN INTRODUCTION TO SERIAL PORT INTERFACING
Lecture 3 - Driving.pdf
Serial Programming
Introduction to embedded systems
Device Operation using PC by Arduino (1).pdf
Pic18 f4520 and robotics
Serial Busses.pptx
Robotix Tutorial 8
What Have We Lost - A look at some historical techniques
Arduino reference
Arduino - Classes and functions
serial_busses_i2c.pptx
5-Tut3_Networking_with_Python.pptx good intro
Real Time Debugging - What to do when a breakpoint just won't do
ESL report
Arduino Teaching Program
11_interface.ppt
Ad

Recently uploaded (20)

PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
composite construction of structures.pdf
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
additive manufacturing of ss316l using mig welding
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Welding lecture in detail for understanding
PPTX
OOP with Java - Java Introduction (Basics)
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPT
Mechanical Engineering MATERIALS Selection
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
CH1 Production IntroductoryConcepts.pptx
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
CYBER-CRIMES AND SECURITY A guide to understanding
composite construction of structures.pdf
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
additive manufacturing of ss316l using mig welding
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Embodied AI: Ushering in the Next Era of Intelligent Systems
bas. eng. economics group 4 presentation 1.pptx
Welding lecture in detail for understanding
OOP with Java - Java Introduction (Basics)
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Mechanical Engineering MATERIALS Selection

Matlab Serial Port

  • 1. Matlab Serial Port Practical notes on Matlab serial port programming by Roberto Meattini PhD student in Robotics and Automatic Control @ University of Bologna roberto [dot] meattini2 [at] unibo [dot] it
  • 2. Matlab interfaces with serial ports through the SERIAL PORT OBJECT but first… by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 2
  • 3. Serial port overview • Serial communication • most used low-level protocol to connect devices • send/receive bytes in a serial way (1 bit at a time) • Serial data format • start bit • 5 to 8 data bits • parity bit • 1 to 2 stop bits by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 3 start data data data data data data data data parity stop stop Decription format: n. data bits – parity type – n. stop bits Example: 8-N-2
  • 4. Serial port overview (I) • Synchronous vs. asynchronous • sync: all transmitted bits are synchronized with a common clock (start/stop bits are not necessary) • async: every device has its own internal clock and data is transmitted at arbitrary time (start/stop bits are necessary) • Baud rate • n. bits transferred per second • OS serial port • in the following we will refer to Windows OS  COM1, COM2, … by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 4
  • 5. The Matlab serial port session • Example: s=serial(‘COM1’)  create the serial port object set(s,’BaudRate’,4800);  configurate properties fopen(s);  connection to the device fprintf(s,’*IDN?’)  read/write data out=fscanf(s);  read/write data fclose(s)  disconnection delete(s)  delete port boject clear s  clean by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 5
  • 6. The serial port session (I) • set(s) • shows the list of all properties • get(s) • shows the list of all properties with respective values • s.BaudRate • the way to show a single property value • set(s,’BaudRate’,4800) • the way to set a property value by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 6
  • 7. Create a Serial Port Object • s = serial(‘<port_name>’); • the port name depends on the OS (Windows  COM1,COM2, ...) • instrhwinfo(‘serial’) • it is a Control Instrument Toolbox command that return a list of available serial port • Once the port object is created, typing s , we obtain an object display summary with serial port obj name, communication settings, communication state, read/write operations state by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 7
  • 8. Communication settings • BaudRate  bits per second • DataBits  specifies n. bits to be transmitted • Parity  specifies the parity checking type • Terminator  specifies the termination character by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 8
  • 9. Writing and reading data • Synchronous communication • transmission is synchronized using start and stop bits and/or a common clock between devices • in this case, the read/write operations block the access to the Matlab command line • Asynchronous communication • read/write operations are not blocking • it is possible to read and write simultaneously • callback functions can be used by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 9
  • 10. Writing data • Writing functions • fprintf  writes text on the device • fwrite  writes binary data on the device • stopasync  stops write asynchronous operations • Writing properties • BytesOutput  n. bytes present in the output buffer • OutputBufferSize  output buffer’s dimension (in bytes) • Timeout  max waiting time to complete a write operation • TransferStatus  indicates if an asynchronous write operation is in progress • ValuesSent  n. values written on the device by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 10
  • 11. Writing data (I) • Synchronous vs. asynchronous • fprintf and fwrite are synchronous by default • to write in asynchronous mode we have to explicit it as an argument • example: fprintf(s, ’<…text…>’, ’async’) • in this case it is possible to write and read simultaneously, and to use callback functions by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 11
  • 12. Reading data • Reading functions • fgetl  reads a text line and discards the terminator • fgets  reads a text line and includes the terminator • fread  reads binary data • fscanf reads data from the device as text • readasync  reads data asynchronously • stopasync  stops read asynchronous operations • Reading properties • BytesAvailable  n. bytes available in the input buffer • InputBufferSize  input buffer’s dimension (in bytes) • ReadAsyncMode  specifies if an asynchronous read operation is “continuous” or “manual” • Timeout  max waiting time to complete a read operation • TransferStatus  indicates if an asynchronous read operation is in progress • ValuesReceived  n. values read from the device by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 12
  • 13. Reading data (I) • Synchronous vs. asynchronous • if ReadAsyncMode is set to • ‘continuous’  (default value) the Serial Port Object continuously checks if there are available data from the device and, if it is present, stores it asynchronously into the input buffer. Then it is possible to use a synchronous function to transfer data to Matlab (fget/fread/fscan) • ‘manual’  the Serial Port Object does not check continuously the device … … • remind: with asynchronous mode it is possible to write and read simultaneously, and to use callback functions by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 13
  • 14. Reading data (II) • fscanf operation • blocks access to the command line until: • the terminator is read • timeout is expired • n. of specified values are read • input buffer is full • fread operation • it does not care about the terminator because reads directly the number of specified values (by default bytes). Example: s.BytesAvailable = 69; out = fread(s, 69)  reads directly 69 bytes and stores in the variable “out” by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 14
  • 15. Callback A function executed when an event occurs, specifying the name of the callback function as a value of the associated callback property by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 15
  • 16. Events and Callbacks • Event: BREAK INTERRUPT • Associated properties: BreakInterruptFcn • the serial port generate a break interrupt when the received data stay inactive for a period greater than a character transmission time • Event: BYTES AVAILABLE • Associated properties: BytesAvailableFcn BytesAvailableFcnCount BytesAvailableFcnMode • if BytesAvailableFcnMode is set as ‘byte’, the callback specified in BytesAvailableFcn is executed every time there are as many bytes as in BytesAvailableFcnCount • if BytesAvailableFcnMode is set as ‘terminator’, the callback is executed when the terminator character is read • N.b.: this event can be generated only during asynchronous read operations by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 16
  • 17. Events and Callbacks (I) • Event: ERROR • Associated properties: ErrorFcn • an error event occurs when read/write operation are not complited in the time specified in Timeout • only for asynchronous read/write • Event: OUTPUT EMPTY • Associated properties: OutoutEmptyFcn • only for asynchronous write operations • Event: PIN STATUS • Associated properties: PinStatusFcn • associated to the change of the values of some control pins … … • for both sync and async operations by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 17
  • 18. Events and Callbacks (II) • Event: TIMER • Associated properties: TimerFcn TimerPeriod • this event is generated when the time specified in TimerPeriod expires, starting from the serial obj connection time; callback specified in TimerFcn is executed • based on the “system velocity” the TimePeriod value is lower bounded by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 18
  • 19. Events and Callbacks (III) • Event information • composed by Type and Data values specified in the callback function header • Type  event name • Data.AbsTime  day-month-year hour:minute:second • for the TIMER event there is also: Data.Message  <…stringa errore…> • more Data values for the event PIN STATUS event … … • Executing callback functions • we need to set the value of the callback property as the name of file with the code of the callback • example: s.ByteAvailableFcnMode = ‘terminator’; s.ByteAvailableFcn = @my_callback; • to pass additional parameters, example: s.ByteAvailableFcn = {@my_callback,val1,val2}; by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 19
  • 20. Events and Callbacks (IV) • Callback file, example: function my_callback(obj,event[…others possible parameters …]) … … … end • If an error occurs during the callback execution • the callback is automatically disabled • a warning is shown by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 20
  • 21. Save and loading • myserial  file • s  serial port obj • out  variable with read data save myserial s out  stores data and serial obj load myserial  recreates s and out in the workspace by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 21
  • 22. REFERENCE: http://it.mathworks.com/help/matlab/serial-port-devices.html by Roberto Meattini - PhD student in Robotics and Automatic Control @ University of Bologna 22