Está en la página 1de 6

Universidad Surcolombiana, Matlab y Arduino

PRACTICAL ACTIVITY V – USO DE ARDUINO Y


COMUNICACIÓN CON MATLAB
Faculty of Engineering, Electronic Engineering.

Eng. Johan Julián Molina

Juan Camilo Trujillo Leiva 20211199220 – u20211199220@usco.edu.co

Leidy Johana Casas Vanegas 20211198957 – u20211198957@usco.edu.co

21 de abril – 2023

Resumen - La práctica de laboratorio se enfocó en el uso de la plataforma electrónica “Arduino” en conjunto con el
software de análisis de datos MATLAB para la comunicación de periféricos y sensores. Para llevar a cabo la
práctica, se estableció una conexión entre el Arduino y la computadora mediante un cable USB y se cargó un
programa en el Arduino utilizando el entorno de desarrollo integrado (IDE) de Arduino. Se configuró MATLAB para
leer los datos de los sensores en tiempo real y graficarlos de manera visualmente comprensible.

Abstract - The laboratory practice focused on the use of the "Arduino" electronics platform in conjunction with
MATLAB data analysis software for peripheral and sensor communication. To carry out the practice, a connection
was established between the Arduino and the computer using a USB cable and a program was loaded on the
Arduino using the Arduino integrated development environment (IDE). MATLAB was configured to read the sensor
data in real time and plot it in a visually understandable way.

DESARROLLO –
Para la practica #5, primero se discutió por el sensor a usar que fuera excelente para la lectura de datos y
para demostrar la comunicación con periféricos y un software de apoyo. Para ello se compro el sensor PIR
HC Sr501 tal como se muestra en la siguiente imagen:

Ilustración 1, Sensor de movimiento PIR

Seguido a ello, se procedió a realizar el código con las funciones correspondientes para la práctica. El código tiene
como objetivo tomar las lecturas del sensor de movimiento como “1” y “0” lógicos, lo cual encenderá un led al
procesar la información Matlab y de allí se leerán los datos en una gráfica en el tiempo especificado.
Universidad Surcolombiana, Matlab y Arduino

CODIGO
clc;
clear all;

% Definir la duración de la medición en segundos


duracion_medicion = input('Ingrese el tiempo correspondiente ');

a = arduino('COM4', 'Uno', 'Libraries', 'Servo');


sensorpir = 'D2';
ledpin = 'D3';
configurePin(a, sensorpir, 'DigitalInput');
configurePin(a, ledpin, 'DigitalOutput');

tic % Iniciar contador de tiempo


% Inicializar el vector para almacenar los valores leídos y el vector de tiempo
valores_led = [];
tiempo = [];

while toc <= duracion_medicion


valor = readDigitalPin(a, sensorpir);
fprintf('Valor del sensor PIR: %d\n', valor);
writeDigitalPin(a, ledpin, valor);
pause(0.25);

% Almacenar el valor del LED en el vector y el tiempo en el vector de tiempo


valores_led = [valores_led, valor];
tiempo = [tiempo, toc];
end

% Graficar los valores del LED como una gráfica de barras


bar(tiempo, valores_led);
title('Lecturas del LED', fontsize=15);
xlabel('Tiempo (segundos)');
ylabel('Valor (0 o 1)');
grid on

% Establecer los límites del eje Y en 0 y 1


ylim([0 1.5]);
Universidad Surcolombiana, Matlab y Arduino

Luego se diseñó en GUIDE una interfaz interactiva y didáctica para que el usuario pueda visualizar de
mejor manera el funcionamiento del programa anterior:
function varargout = gui_sensor_led_pir(varargin)
% GUI_SENSOR_LED_PIR MATLAB code for gui_sensor_led_pir.fig
% GUI_SENSOR_LED_PIR, by itself, creates a new GUI_SENSOR_LED_PIR or raises the existing
% singleton*.
%
% H = GUI_SENSOR_LED_PIR returns the handle to a new GUI_SENSOR_LED_PIR or the handle to
% the existing singleton*.
%
% GUI_SENSOR_LED_PIR('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI_SENSOR_LED_PIR.M with the given input arguments.
%
% GUI_SENSOR_LED_PIR('Property','Value',...) creates a new GUI_SENSOR_LED_PIR or raises
the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_sensor_led_pir_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_sensor_led_pir_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help gui_sensor_led_pir

% Last Modified by GUIDE v2.5 21-Apr-2023 07:20:46

% Begin initialization code - DO NOT EDIT


gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_sensor_led_pir_OpeningFcn, ...
'gui_OutputFcn', @gui_sensor_led_pir_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before gui_sensor_led_pir is made visible.


function gui_sensor_led_pir_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui_sensor_led_pir (see VARARGIN)
Universidad Surcolombiana, Matlab y Arduino

% Choose default command line output for gui_sensor_led_pir


handles.output = hObject;

% Update handles structure


guidata(hObject, handles);

% UIWAIT makes gui_sensor_led_pir wait for user response (see UIRESUME)


% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = gui_sensor_led_pir_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure


varargout{1} = handles.output;

% --- Executes on button press in pushbutton1.


function pushbutton1_Callback(hObject, eventdata, handles)
% Definir la duración de la medición en segundos
duracion_medicion = 20;

% Inicializar el vector para almacenar los valores leídos y el vector de tiempo


valores_led = [];
tiempo = [];

% Inicializar arduino y configurar el sensor PIR y el LED


a = arduino('COM4', 'Uno', 'Libraries', 'Servo');
sensorpir = 'D2';
ledpin = 'D3';
configurePin(a, sensorpir, 'DigitalInput');
configurePin(a, ledpin, 'DigitalOutput');

tic % Iniciar contador de tiempo

while toc <= duracion_medicion


valor = readDigitalPin(a, sensorpir);
fprintf('Valor del sensor PIR: %d\n', valor);
writeDigitalPin(a, ledpin, valor);
pause(0.25);

% Almacenar el valor del LED en el vector y el tiempo en el vector de tiempo


valores_led = [valores_led, valor];
tiempo = [tiempo, toc];

% Actualizar el gráfico
plot(handles.axes1, tiempo, valores_led, LineWidth=2);
title(handles.axes1, 'Lecturas del LED', 'fontsize', 15);
xlabel(handles.axes1, 'Tiempo (segundos)');
ylabel(handles.axes1, 'Valor (0 o 1)');
grid(handles.axes1, 'on');
ylim(handles.axes1, [0 1.5]);
drawnow;
end
Universidad Surcolombiana, Matlab y Arduino

% Limpiar el objeto arduino


clear a
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

function edit1_CreateFcn(hObject, eventdata, handles)


% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.


% See ISPC and COMPUTER.
if isequal(get(hObject,'Tag'),'')
set(hObject,'Tag','edit1');
end
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.


function edit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.


% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton2.


function pushbutton2_Callback(hObject, eventdata, handles)
pause;
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% --- Executes on button press in pushbutton3.


% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

function edit3_Callback(hObject, eventdata, handles)


% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text


% str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.


function edit3_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
Universidad Surcolombiana, Matlab y Arduino
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

IMPLEMENTACION –

Ilustración 2, montaje del programa

También podría gustarte