martes, 20 de agosto de 2013

ADQUISICIÓN DE DATOS, USANDO UN ACELEROMETRO MMA7260, UN PIC Y MATLAB


A continuación se muestra como llevar a cabo la adquisición de datos que el sensor mma7260 (fabricante: freescale,  de 3 ejes y analógico) arroja en cada salida correspondiente a la aceleración en su respectiva dirección.
El trabajo se compone en 3 partes fundamentales, mencionados en la siguiente lista:
      1:_ ADQUISICIÓN DE DATOS
      2.- TRANSMISIÓN Y RECEPCIÓN 
      3.- MANIPULACIÓN DE DATOS
Se desarrollo cada una de las etapas anteriormente mencionadas, la integración de este sistema, necesito de que las siguientes tareas se llevaran acabo:
PIC: programación del ADC y del transmisor vía RS232(asm)
MATLAB: programación del receptor  y manipulación de la información.(GUIDE)

Es importante mencionar que para el entendimiento de como funcionan los acelerometros, es necesario llevar a cabo algunas pruebas, en la hoja de datos del integrado http://www.freescale.com/files/sensors/doc/data_sheet/MMA7260QT.pdf en la pagina 6, el fabricante menciona algunas de las configuraciones en la que podemos posicionar nuestro acelerometro para validar los datos que ahí se mencionan así como también verificar el correcto funcionamiento de nuestro sistema.

este trabajo lo he concluido en su totalidad, y lo uso en un sistema de entrenamiento virtual para rehabilitación,  formando parte fundamental de mi sistema que apoya la rehabilitación.

algunas capturas;
la siguiente grafica muestra la configuracion en donde la gravedad actua sobre el eje Z del acelerometro.
en la hoja de datos el fabricante define valores de Z=2.45 Y=1.65, X=1.65.

recordar que los sensores son alimentados por 3.3V y al ADC nos dara una resolucion aproximada de 3.2mv.  sabiendo estos datos obtendremos los siguientes datos que como observaran la interfaz nos muestra.


y este es mi interfaz final.

esta interfaz permite la adquisición de datos por tiempo ilimitado, es decir el usuario empieza con la adquisición y se detiene cuando el quiere solo presionando "detener".


Si alguien gusta que se le proporcione información, contácteme por este medio y con gusto le apoyare en lo que pueda de igual forma acepto criticas, para mejorar mi trabajo.


"Las grandes obras las sueñan los genios locos,las ejecutan los luchadores natos,las disfrutan los felices cuerdos y las critican los inutiles cronicos"





sábado, 10 de agosto de 2013



 ADQUISICION DE DATOS CON MATLAB Y PIC16F877A

ME ENCUENTRO PROGRAMANDO UNA INTERFAZ (MATLAB) QUE SE COMUNIQUE CON EL PIC16F877A (HALF DUPLEX), EL PIC RECOLECTA DATOS DE DISTINTOS SENSORES Y LOS MANDA A LA PC. LA INTERFAZ GRAFICA TODO LO QUE EL PIC MANDA... ME HE ENCONTRADO CON MUCHOS PROBLEMAS, PERO HE LOGRADO RESOLVER LA MAYORIA. PRONTO ESPERO SUBIR RESULTADOS. 

lunes, 18 de febrero de 2013

COMUNICACION PIC- MATLAB.
En el post anterior se hizo una interfaz con la capacidad de transmitir datos por el puerto serial, ahora les mostrare como conectar el PIC16f877A a MATLAB. el codigo ya probado desde hace unos años es el siguiente:



ORG 0X00
GOTO INICIO
ORG  0X04
GOTO    INTER

 INTER
        BANKSEL PIR1
        BTFSS   PIR1,RCIF       ;INTERRUPCION POR RECEPCION
        GOTO    VOLVER          ; NO.FALSA INTERRUPCION
        BCF     PIR1,RCIF       ;SI. REPONER BANDERA
        MOVF    RCREG,W           ;LECTURA DEL DATO RECIBIDO
        MOVWF PORTB
  VOLVER       RETFIE
 
  ;COMINZO DEL PROGRAMA PRINCIPAL
  INICIO      
                BANKSEL PORTB
                CLRWDT  ;REFRESCA PERRO GUARDIAN
                CLRF PORTB
                CLRF PORTC      ;
                CLRF    PORTD
                BANKSEL TRISC
                MOVLW   0XFF
                MOVWF   TRISD
                CLRF TRISB      ;PORTB COMO SALIDA
                MOVLW   B'10111111'     ;RC7/RX ENTRADA
                MOVWF   TRISC           ;RC6/TX SALIDA
                MOVLW  B'11101111'      ;PREDIVISOR DE 128 ASOCIADO AL PERRO GUARDIAN
                MOVWF   OPTION_REG
                MOVLW   B'00100100'     ;CONFIGURACION USART
               
                MOVWF   TXSTA           ; Y ACTIVACION DE TRANSMISION
                MOVLW   .25                    ;9660 BAUDIOS
                MOVWF   SPBRG           ;
                BSF     PIE1,RCIE;HABILITA INTERRUPCION EN RECEPCION
                BANKSEL PORTC
                MOVLW   B'10010000';CONFIGURACION DE USART PARA RECEPCION CONTINUA
                MOVWF   RCSTA   ;RECEPCION COPNTINUA, PUESTA EN ON
                MOVLW   B'11000000'
                MOVWF   INTCON          ;HABILITACION D EINTERRUPCIONES GENERALES
               
                BUCLE  
                        MOVF RCREG,W
MOVWF PORTB
GOTO BUCLE
                   
                END
El programa solo recibe datos, que es lo que necesitamos.
ahora ya tenemos los datos que se envian desde MATLAB y lo podemos visualizar con LEDS en la salidas del PIC.

Notas:
En caso de no tener un puerto serial, puedes adquirir un convertidor USB- RS232
Recuerda siempre usar el convertidor de CMOS- TTL (max 232 en mi caso)
dudas y preguntas, con gusto les atendere.
SALUDOS, en un tiempo libre; documentare y detallare como controlar un motor de CD todo lo que necesitan saber antes de aventurarse y lo mas importante mi codigo para el control de motores de CD desde MATLAB.
saludos

INTERFAZ PARA CONTROLAR MOTORES DE CD.

En este post se presenta información de como controlar un motor de CD (común) usando GUIDE, herramienta de MATLAB.
Es importante recalcar que en esta ocasión solo se pretende desarrollar una interfaz gráfica en MATLAB, que cumpla con las siguientes condiciones:
FIG. 1: interfaz gráfica (PWM)
ABRIR EL PUERTO SERIAL MEDIANTE UN BOTÓN 
CERRA EL PUERTO SERIAL CON UN BOTÓN DISPONIBLE 
BARRA SLIDER PARA VARIAR EL VALOR DEL DUTY CICLE
ENVIÓ CORRECTO DE DATOS DE 8 BITS
MENSAJES AL USUARIO

PUNTOS IMPORTANTES A CONSIDERAR:
El nombre (etiqueta) del puerto serial
La velocidad de transmisión
Bits a enviar (N bits, bit de parada y bit de error)

Tomando en cuenta estas dichas especificaciones y consideraciones, se desarrollo la interfaz (véase FIG 1).
Ahora se muestra el código funcional propuesto para este diseño.

CODIGO (MATLAB):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = PWMcD(varargin)
% PWMCD M-file for PWMcD.fig
%      PWMCD, by itself, creates a new PWMCD or raises the existing
%      singleton*.
%
%      H = PWMCD returns the handle to a new PWMCD or the handle to
%      the existing singleton*.
%
%      PWMCD('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PWMCD.M with the given input arguments.
%
%      PWMCD('Property','Value',...) creates a new PWMCD or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before PWMcD_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to PWMcD_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 PWMcD

% Last Modified by GUIDE v2.5 18-Feb-2013 17:24:54

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @PWMcD_OpeningFcn, ...
                   'gui_OutputFcn',  @PWMcD_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 PWMcD is made visible.
function PWMcD_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 PWMcD (see VARARGIN)

% Choose default command line output for PWMcD
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes PWMcD wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = PWMcD_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)
% 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)


% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% 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 slider movement.
function slider2_Callback(hObject, eventdata, handles)
% hObject    handle to slider2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
PWM= get(handles.slider2,'value');
PWM=(round(PWM(1)));
s=instrfind
if isempty( s )
    set(handles.edit4,'string','ABRIR EL PUERTO');
end
fwrite(s,PWM,'uint8')
set(handles.edit3,'string',fix(PWM));
guidata(hObject, handles); 



% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider


% --- Executes during object creation, after setting all properties.
function slider2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (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 edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
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 ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (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 edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double


% --- 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 pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
s = instrfind;
if ~isempty( s )
    fclose( s );
    delete( s );
    clear s
end
s = serial('COM3');
set(s,'BaudRate',9600);
set(s,'DataBits',8);
set(s,'Parity','none');
set(s,'StopBits',1);
set(s,'FlowControl','none');
%%%%%%%%%%%%%%%%%%%%config serial
fopen(s);     %Almacena

if ~isempty( s )
set(handles.edit4,'string','RS-232 ABIERTO')
end
guidata(hObject, handles); 



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
%valor=str2double(get(hObject,'value')) returns contents of edit3 as a double
set(handles.slider2,'value');



% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (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 pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
s = instrfind;
if ~isempty( s )
    fclose( s );
    delete( s );
    clear s
    set(handles.edit4,'string','CERRADO');
end
guidata(hObject, handles); 




function edit4_Callback(hObject, eventdata, handles)
% hObject    handle to edit4 (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 edit4 as text
%        str2double(get(hObject,'String')) returns contents of edit4 as a double


% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit4 (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


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

En el código se puede observar la configuración del puerto RS-232, el envió de datos al puerto especificado (COM3).
P.D. este código esta abierto, en mi caso el control de motores los estoy haciendo con un PIC16f877A de Microchip(http://ww1.microchip.com/downloads/en/devicedoc/39582b.pdf).

Si tienes dudas, puedes preguntar y tratare de responder a la mayor brevedad posible. La programación es sencilla, no cuesta nada programar las interfaces. 
Saludos.