Accessing the Serial Port using MATLAB Code: Serial communication through MATLAB

Through MATLAB, we can access various computer peripherals. One of them are Serial Ports. These serial port supports a maximum baud rate of 115200bps. This program is set for the most commonly used baud rate i.e., 9600bps. If the error rate of the medium is very high, or you are using it to communicate a slower device, then you have to use a lower baud rate like, 4800bps, 2400bps etc.
It is particularly useful when you are communicating through a Micro-controller Controlled Application, it that you can actually give command in you MATLAB's command window, and the MCU will react to that command. 

#  In the program below we have used the serial port COM25, which is fed as a string in the function "serial".
#  In the subsequent lines we are using "set" function to set various other serial communication parameters.
# it will display all the data it got from the external device, communicating through that COM port in nearly 100 iterations
# when the port is being successfully setup, it will display a success message & then you can transmit & receive data from that serial port.

SAMPLE RUN OF THE CODE BELOW:
Accessing the Serial Port using MATLAB Code: Serial communication through MATLAB
Accessing the Serial Port using MATLAB Code: Serial communication through MATLAB

Code:
clc
clear all
close all
sp=serial('COM25');  %assigns the object s the serial port object
set(sp, 'InputBufferSize', 256); 
%number of bytes in inout buffer
set(sp, 'FlowControl', 'hardware');
set(sp, 'BaudRate', 9600);
set(sp, 'Parity', 'none');
set(sp, 'DataBits', 8);
set(sp, 'StopBit', 1);
set(sp, 'Timeout',10);
disp(get(s,'Name'));
prop(1)=(get(sp,'BaudRate'));
prop(2)=(get(sp,'DataBits'));
prop(3)=(get(sp, 'StopBit'));
prop(4)=(get(sp, 'InputBufferSize'));

disp(['Port Setup Finished Successfully!',num2str(prop)]);

fopen(sp);          
%opens the serial port
t=1;
disp('Running');
x=0;
while t<100
   a=fread(sp);
   a=max(a);
   x =[x a];
   plot(x);
   axis auto;
   grid on;
   disp([num2str(t),'th iteration max= ',num2str(a)]);
   hold on;
   t=t+1;
   a=0;
   drawnow;
end

fclose(sp);
%close the serial port

0 comments: