SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
oscon2007
 
Chapter Seven(2)
Chapter Seven(2)Chapter Seven(2)
Chapter Seven(2)
bolovv
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
Suchit Patel
 

Was ist angesagt? (20)

Loader
LoaderLoader
Loader
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environments
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Bitstuffing
BitstuffingBitstuffing
Bitstuffing
 
02 copy file_fill_sp16
02 copy file_fill_sp1602 copy file_fill_sp16
02 copy file_fill_sp16
 
Design of a two pass assembler
Design of a two pass assemblerDesign of a two pass assembler
Design of a two pass assembler
 
Chapter Seven(2)
Chapter Seven(2)Chapter Seven(2)
Chapter Seven(2)
 
(6) collections algorithms
(6) collections algorithms(6) collections algorithms
(6) collections algorithms
 
Generacion de codigo ensamblado
Generacion de codigo ensambladoGeneracion de codigo ensamblado
Generacion de codigo ensamblado
 
Function in C++
Function in C++Function in C++
Function in C++
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
 
C programming notes
C programming notesC programming notes
C programming notes
 
Co&amp;al lecture-05
Co&amp;al lecture-05Co&amp;al lecture-05
Co&amp;al lecture-05
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
FUNDAMENTAL OF C
FUNDAMENTAL OF CFUNDAMENTAL OF C
FUNDAMENTAL OF C
 
Co&amp;al lecture-07
Co&amp;al lecture-07Co&amp;al lecture-07
Co&amp;al lecture-07
 
C- language Lecture 5
C- language Lecture 5C- language Lecture 5
C- language Lecture 5
 
Co&amp;al lecture-08
Co&amp;al lecture-08Co&amp;al lecture-08
Co&amp;al lecture-08
 
Modern C++
Modern C++Modern C++
Modern C++
 

Ähnlich wie Matlab Serial Port

Combining Phase Identification and Statistic Modeling for Automated Parallel ...
Combining Phase Identification and Statistic Modeling for Automated Parallel ...Combining Phase Identification and Statistic Modeling for Automated Parallel ...
Combining Phase Identification and Statistic Modeling for Automated Parallel ...
Mingliang Liu
 
HPC Application Profiling and Analysis
HPC Application Profiling and AnalysisHPC Application Profiling and Analysis
HPC Application Profiling and Analysis
Rishi Pathak
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
HPC Application Profiling & Analysis
HPC Application Profiling & AnalysisHPC Application Profiling & Analysis
HPC Application Profiling & Analysis
Rishi Pathak
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
DeepasCSE
 

Ähnlich wie Matlab Serial Port (20)

Combining Phase Identification and Statistic Modeling for Automated Parallel ...
Combining Phase Identification and Statistic Modeling for Automated Parallel ...Combining Phase Identification and Statistic Modeling for Automated Parallel ...
Combining Phase Identification and Statistic Modeling for Automated Parallel ...
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
 
Parallel programming using MPI
Parallel programming using MPIParallel programming using MPI
Parallel programming using MPI
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Programming on Windows 8.1: The New Stream and Storage Paradigm (Raffaele Ria...
Programming on Windows 8.1: The New Stream and Storage Paradigm (Raffaele Ria...Programming on Windows 8.1: The New Stream and Storage Paradigm (Raffaele Ria...
Programming on Windows 8.1: The New Stream and Storage Paradigm (Raffaele Ria...
 
My ppt hpc u4
My ppt hpc u4My ppt hpc u4
My ppt hpc u4
 
The Newest in Session Types
The Newest in Session TypesThe Newest in Session Types
The Newest in Session Types
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Pulsar connector on flink 1.14
Pulsar connector on flink 1.14Pulsar connector on flink 1.14
Pulsar connector on flink 1.14
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
 
HPC Application Profiling and Analysis
HPC Application Profiling and AnalysisHPC Application Profiling and Analysis
HPC Application Profiling and Analysis
 
project_docs
project_docsproject_docs
project_docs
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Programming using MPI and OpenMP
Programming using MPI and OpenMPProgramming using MPI and OpenMP
Programming using MPI and OpenMP
 
HPC Application Profiling & Analysis
HPC Application Profiling & AnalysisHPC Application Profiling & Analysis
HPC Application Profiling & Analysis
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
 
Pattern-based Definition and Generation of Components for a Synchronous React...
Pattern-based Definition and Generation of Components for a Synchronous React...Pattern-based Definition and Generation of Components for a Synchronous React...
Pattern-based Definition and Generation of Components for a Synchronous React...
 

Kürzlich hochgeladen

Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Kürzlich hochgeladen (20)

(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 

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