You are currently viewing Serial Communication Using Matlab

Serial Communication Using Matlab

Spread the love

Matlab Code to Transmit Data Through Serial Port

Serial communication is the simplest way to communicate between two devices,This program provides a walkthrough to ocnnect your PC to embedded devices using Matlab.So you can transmit or receive data thru serial port and further analyze the data in PC using Matlab

% Instrreset Disconnect and delete all instrument objects.
instrreset;

Before you can send or receive information using a serial port, you must first identify what port will
be used (COM1 or COM2). This is done by using the serial command. For example,CreateSerialPort =serial(‘COM1’); selects COM1 and returns an identifier which is captured by the variable ‘CreateSerialPort ’. If you enter the command without the ‘;’ and press return, the current settings of COM1 should be
displayed.

%Construct serial port object.
CreateSerialPort = serial('COM1');

Once you create the serial port object,the next step is to configure the serial port settings.You have to specify the baudrate,output buffer size ,flow control and parity.

%Set Serial Port Settings
set(CreateSerialPort,'BaudRate',115200,'StopBits',1,'FlowControl','none','Parity','none','DataBits',8,'OutputBufferSize',50000);

Once you are done with settings,you have to cretae the Buffer size

%Create Buffer Size
CreateSerialPort.InputBufferSize=65537;

Create the timeout period

%Time out
CreateSerialPort.TimeOut=60;
CreateSerialPort.Terminator = '';

Open the serial port for sending the data

%Open Serial Port Object
fopen(CreateSerialPort);

Write to the serial port

%Write to  Serial Port Object
fwrite(CreateSerialPort,'A');

Close the serial port once the message is transmitted

%Close Serial Port Object
fclose(instrfind);

Clear the serial port object

%Clear Instrument Objects
clear CreateSerialPort;

Simplified Version

Steps to follow for using Serial Port Communication:-

%Create Serial Port Object

CreateSerialPort = serial('COM1','BaudRate',9600);

%Open the serial port for Communication

fopen(CreateSerialPort)

%Send some Characters over Serial Port

fprintf(CreateSerialPort,'Embedded Laboratory');

%Close the serial port

fclose(s)

%Delete the serial port

delete(s)