Proyecto de Tesis en Mecatrónica. Universidad Técnica del Norte. Ernesto Palacios <mecatronica.mid@gmail.com>

Dependencies:   EthernetNetIf HTTPServer QEI_hw RPCInterface mbed

setup.cpp

Committer:
Yo_Robot
Date:
2012-05-09
Revision:
18:cf1e07d82630
Parent:
17:a4f380bc2516
Child:
19:c26cf8a48986

File content as of revision 18:cf1e07d82630:

/**
 * @brief  Tren de impulsos con Timer2
 * @file   setup.cpp
 * @author Ernesto Palacios
 *
 * Created on 25 de Marzo de 2012
 *
 * Licencia  GPL v3.0
 * http://www.gnu.org/licenses/gpl-3.0.html
 */


#include "setup.h"
#include "EthernetNetIf.h"
#include "mbed.h"

// Salida Serial de mbed
extern Serial pc;
extern DigitalOut   pin_son;   // SON
extern DigitalOut   pin_dir;   // SIGN+
extern InterruptIn  pin_alm;   // ALM 
extern AnalogOut    aout;      // +-10V

int fq_posicion = 10000;  // Variable global donde se almacenara 
                         // la velocidad de posicionamiento en Hz


EthernetNetIf configurarEthernet()
{
        //____________ *** ARCHIVO DE CONFIGURACION  ***_______________________ //
        
        printf("\n *** CONFIGURACION ETHERNET DE MBED ***\n"); 
        printf("Leyendo archivo de configuracion...\n\n"); 
        
        FILE *fp = fopen("/local/config.txt", "r"); // Abre el archivo y lo guarda en fp
        
        if(!fp)   // En caso de no encontrarse el archivo
        {
            printf("\nEl archivo /mbed/config.txt no puede ser abierto!\n");
            exit(1);
              
        }
        else
        {
            // Cadenas de caracteres desde el Archivo config.txt
            char isDHCP [15];    //Modo Automatico o Manual
            char empty  [2];     // Linea vacia
            char ip     [40];    // Direccion IP
            char mask   [40];    // Mascara de Subred
            char gate   [40];    // Puerta de enlace 
            char dns    [40];    // Direccion DNS
            
            // Valores 'int' para agregar a la configuracion manual
            int DHCP;
            int n_ip[4];
            int n_mask[4];
            int n_gate[4];
            int n_dns[4];
            
            
            // Leer linea a linea el archivo
            fgets( isDHCP, 15, fp );
            fgets( empty,  2, fp );
            fgets( ip,     40, fp );
            fgets( mask,   40, fp );
            fgets( gate,   40, fp );
            fgets( dns,    40, fp );
            
            printf("Cerrando archivo...\n");
            fclose(fp);
            
            // Extraer los valores numericos
            sscanf( isDHCP,"%*s %d",&DHCP );
            
            sscanf(   ip,"%*s %d.%d.%d.%d",&n_ip[0],&n_ip[1],&n_ip[2],&n_ip[3] );
            sscanf( mask,"%*s %d.%d.%d.%d",&n_mask[0],&n_mask[1],&n_mask[2],&n_mask[3] );
            sscanf( gate,"%*s %d.%d.%d.%d",&n_gate[0],&n_gate[1],&n_gate[2],&n_gate[3] );
            sscanf(  dns,"%*s %d.%d.%d.%d",&n_dns[0],&n_dns[1],&n_dns[2],&n_dns[3] );
            
            
            if(DHCP) //En caso de modo DHCP
            {
                printf("\n   Configurar red de manera automatica\n");
                EthernetNetIf eth; //Crea la interfaz
                EthernetErr ethErr = eth.setup();
                if( ethErr )
                {
                    printf( "Error %d en la configuracion\n", ethErr );
                    exit(1);
                }
            
                printf("Configuracion Correcta\n\n");
                return eth;
            }
            else                       
            {                        
                sscanf(   ip,"%*s %d.%d.%d.%d",&n_ip[0],  &n_ip[1],  &n_ip[2],  &n_ip[3] );
                sscanf( mask,"%*s %d.%d.%d.%d",&n_mask[0],&n_mask[1],&n_mask[2],&n_mask[3] );
                sscanf( gate,"%*s %d.%d.%d.%d",&n_gate[0],&n_gate[1],&n_gate[2],&n_gate[3] );
                sscanf(  dns,"%*s %d.%d.%d.%d",&n_dns[0], &n_dns[1], &n_dns[2], &n_dns[3] );
                printf(" %s %s %s %s %s\n  " , isDHCP, ip, mask, gate, dns );            
                
                printf("\n   Configurar red de manera manual\n");
                EthernetNetIf eth(
                IpAddr( n_ip[0],  n_ip[1],  n_ip[2],  n_ip[3]), //IP Address
                IpAddr( n_mask[0],n_mask[1],n_mask[2],n_mask[3]), //Network Mask
                IpAddr( n_gate[0],n_gate[1],n_gate[2],n_gate[3]), //Gateway
                IpAddr( n_dns[0], n_dns[1], n_dns[2], n_dns[3] )  //DNS
                );
                
                EthernetErr ethErr = eth.setup();
                if( ethErr )
                {
                    printf( "Error %d en la configuracion\n", ethErr );
                    exit(1);
                }
    
                printf("Configuracion Correcta\n\n");
                return eth;
            }
            
        }   
        EthernetNetIf eth;
        return eth;
}


void setTimer2()
{
    // Encender Timer2 (PCONP[22])
    LPC_SC->PCONP |= 1 << 22; 

    // Resetear y parar el Timer
    LPC_TIM2->TCR  = 0x2; 
    LPC_TIM2->CTCR = 0x0; 

    // Establecer el Preescaler en cero
    // SIn Preesclaer
    LPC_TIM2->PR = 0;

    // Calcular el periodo Inicial
    uint32_t periodo = ( SystemCoreClock / 400 ); 

    // Establecer los Registros de Coincidencia
    // ( Match Register )
    LPC_TIM2->MR2 = periodo;
    LPC_TIM2->MR3 = periodo;  // Legacy, salidas identicas
    
    LPC_TIM2->MCR |= 1 << 7;    // Resetear Timer en MR2
    
    LPC_TIM2->EMR |= 15UL << 8;  // Alternar Pin MAT2.2 
                                //      y MAT2.3

    LPC_PINCON->PINSEL0 |= 15UL << 16;  //Activar  MAT2.2 
                                      // y MAT2.3 como salidas
   
}

void ISR_Serial()
{
    int value;        // Nuevo Valor
    char command;     // Comando al que aplicar el nuevo valor

    pc.scanf( "%d-%c", &value, &command ) ;
    //pc.printf("\n %d-%c \n", value, command );

    // Establecer nueva frecuencia
    if( command == 'H')
        setPTO( value );
    
    else if( command == 'K' )
        setPTO( value * 1000 );
        
    // Nuevo voltaje de salida
    // Alguna formula para calcular el Vout necesario
    // -100% a +100%
    else if( command == 'A')
        aout = (float)( value + 10000.0 ) / 20000.0;
        
        
    // Cambiar la direccion
    else if( command == 'D')
    {
        stopTimer2();
        pin_dir = value;
        wait_us( 2 );
        startTimer2();
    }
       
        
    //Encender el Servo
    else if( command == 'S')
        pin_son = value;
    
    else if( command == 'V')
      fq_posicion = value;
      
    else if( command == 'G' )  
    {
        int pulsos = value;       //Numero de pulsos a generar
        float t_alto = pulsos / fq_posicion;  //Tiempo que debe ser generado el tren de pulsos.
    
        stopTimer2();               //Deten el tren de pulsos
        setPTO( fq_posicion );      //Nueva frecuencia de salida
        startTimer2();              //Inicia el tren de pulsos
        wait( t_alto );             //Espera hasta llegar a la posicion
        stopTimer2();               //Posicion alcanzada ALTO. 
    }
}


void setPTO( int freq )
{
    if( freq != 0 )
    {
        LPC_TIM2->TC = 0x00;  //Resetear Timer
        setMR2( getMRvalue( freq ) ); 
        startTimer2();
    
    }else{
        
        stopTimer2();
        LPC_TIM2->TC = 0x00;  //Resetear Timer
    }
}

void setPTO_eth( char * input, char * output )
{
    int freq = atoi( input );
    
    if( freq != 0 ){
        LPC_TIM2->TC = 0x00;            // Resetear Timer
        setMR2( getMRvalue( freq ) );  // Cambiar frefuencia
        startTimer2();                // Iniciar Timer
        if( pin_alm == 0 )
            sprintf( output,"Ok" );
        else
            sprintf( output,"AL" );    
    }else{
        stopTimer2();
        LPC_TIM2->TC = 0x00;  // Resetear Timer
        if( pin_alm == 0 )
            sprintf( output,"Ok" );
        else
            sprintf( output,"AL" );
    }           
}

void setANG_eth( char * input, char * output )
{
    long int pulsos = atol( input );       //Numero de pulsos a generar
    float t_alto = pulsos / fq_posicion;  //Tiempo que debe ser generado el tren de pulsos.
    
    stopTimer2();               //Deten el tren de pulsos
    setPTO( fq_posicion );      //Nueva frecuencia de salida
    startTimer2();              //Inicia el tren de pulsos
    wait( t_alto );             //Espera hasta llegar a la posicion
    stopTimer2();               //Posicion alcanzada ALTO. 
    
    if( pin_alm == 0 )
        sprintf( output,"Ok" );
    else
        sprintf( output,"AL" );    
    
}
void setSPD_eth( char * input, char * output )
{
    fq_posicion = atoi( input );      
    // Esta funcion cambia la velocidad con la que se
    // posicionara el eje del motor en un angulo determinado
    if( pin_alm == 0 )
        sprintf( output,"Ok" );
    else
        sprintf( output,"AL" );    
        
}
void getENC_eth( char * input, char * output )
{
    //Leer el Encoder  *******  F A L T A
    if( pin_alm == 0 )
        sprintf( output,"Ok" );
    else
        sprintf( output,"AL" );    
    
}


void ISR_Alarm()
{
    pin_son = 0 ;
    stopTimer2();
    aout =  0.5 ;
 
    pc.printf( "AL" ); //ALARMA! solo es AL para que 
                      //sea conciso con el modo ETH y funcione
                     //bien en LabVIEW.
}

int getMRvalue( int fout  )
{
    int   toRegister;
    
    toRegister = (24000000 /(fout*2.0) ) -1;
    return toRegister;
}


void setMR2( int newValue )
{
    LPC_TIM2->MR2 = newValue; // Las dos salidas son identicas
    LPC_TIM2->MR3 = newValue; // Para testear el programa.
}



void startTimer2()
{
    // Arrancer el Timer 2
    LPC_TIM2->TCR = 1;
}

void stopTimer2()
{
    // Detener el Timer 2
    LPC_TIM2->TCR = 0x2;
}


//    **** Funciones Liberia Ethernet  *****   //

void setAout_eth( char * input, char * output )
{
    int    vout = atoi( input );
    aout = (float)( vout + 10000 ) / 20000;   
    if( pin_alm == 0 )
        sprintf( output,"Ok" );
    else
        sprintf( output,"AL" );
}



void setDir_eth ( char * input, char * output )
{
    int value = atoi( input );
    
    pin_dir = value;
    
    if( pin_alm == 0 )
        sprintf( output,"Ok" );
    else
        sprintf( output,"AL" );
}



void setSON_eth ( char * input, char * output )
{
    int value = atoi( input );
    
    pin_son = value;
    
    if( pin_alm == 0 )
        sprintf( output,"Ok" );
    else
        sprintf( output,"AL" );
        
}



/*  LEGACY FUNCTIONS
 *
 *  El codigo actual no hace referencia a estas funciones
 *  sin embargo no hay problema en definirlas.
 */ 
void setMR3( int newValue )
{
    LPC_TIM2->MR3 = newValue;
}


void setPrescaler( int newValue)
{
    LPC_TIM2->PR = newValue; 
}