Cristian Castro / Mbed 2 deprecated E02-Entrega_1V2

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "scolor_TCS3200.h"
00003 
00004 
00005 //******************************************************************************
00006 //                          Definicion de Periféricos
00007 
00008 /// Puerto Serial
00009 Serial SerialPort(SERIAL_TX, SERIAL_RX, 9600);
00010 
00011 /// PWM OUTPUTS
00012 PwmOut Buzzer(LED1);
00013 
00014 //  Temporizadores 
00015 Ticker LengthTonoBuzzer;
00016 
00017 // SENSOR DE COLOR
00018 scolor_TCS3200 SENSOR_COLOR (PA_8, PB_10, PB_4, PB_5, PB_3); 
00019 
00020 
00021 
00022 //******************************************************************************
00023 ///         Declarar Variables Globales
00024 
00025 
00026 uint8_t   programa_ejecutar = 0; // Variable que almacena la ORDEN (Telemetria ó Telecomando)
00027                                  // enviada desde el CoolTerm
00028                                  
00029 
00030 long red;                        //Almacenan el Tiempo que dura el CicloUtil de la frecuencia
00031 long blue;                       //Generada por el Sensor TSC3200, al leer el componente
00032 long green;                      //R, G, B o Clear del color que tenga en Frente
00033 long clear;
00034 
00035 uint8_t coolterm_comand;         // Se almacenan Todos los Caracteres recibidos por el SerialPort.
00036 
00037 // No usada por Ahora
00038 uint8_t i = 0;                      // Variable usada como Indice de los vectores,
00039                                     // indica la posicion del vector en donde se reciben 
00040                                     // ó se almacenan los datos
00041 
00042 
00043 uint8_t duracion_tono = 1;       // Variable que almacena el Tiempo que es ESCUCHARÁ el Tono
00044 uint8_t tipo_tono = 1;           // Variable que almacena el Tono que se desee escuchar
00045 // siendo 
00046 #define TONO_DO 0x01 /// si tipo_tono == 0x01, se escuchará un DO
00047 #define TONO_RE 0x02 /// si tipo_tono == 0x02, se escuchará un RE
00048 #define TONO_MI 0x03 /// si tipo_tono == 0x03, se escuchará un MI
00049 #define TONO_SI 0x04 /// si tipo_tono == 0x04, se escuchará un SI
00050 
00051 #define DO 3.78 /// Duración del periodo en ms, que se pondrá en el Buzzer.period_ms() PARA ESCUCHAR UN DO
00052 #define RE 3.36 /// Duración del periodo en ms, que se pondrá en el Buzzer.period_ms() PARA ESCUCHAR UN RE
00053 #define MI 3.03 /// Duración del periodo en ms, que se pondrá en el Buzzer.period_ms() PARA ESCUCHAR UN MI
00054 #define SI 2.02 /// Duración del periodo en ms, que se pondrá en el Buzzer.period_ms() PARA ESCUCHAR UN SI 
00055 
00056 //******************************************************************************
00057 // COMANDOS
00058 
00059 #define iniciar_telemetria      0xFE
00060 #define iniciar_telecomando     0xFF
00061 
00062 #define telemetria_1            0x01  //
00063 #define telemcomando_1          0x01
00064 
00065 #define CMD_rojo   0x01
00066 #define CMD_azul   0x02
00067 #define CMD_verde  0x03
00068 #define CMD_clear  0x04
00069 #define ColorNoIdentificado 0x05
00070 
00071 uint8_t color_identificado = ColorNoIdentificado;
00072 
00073 //****************************************************************************
00074 //                      Prototipo de funciones
00075 
00076 void ReadPort(void);                // Lee el puerto Serial
00077 void MainConfig(void);              // Configuracion Inicial de los Perifericos del uC
00078 void Buzzer_Tone(uint8_t tipo_tono, uint8_t duracion_tono); // configura el tono y la duracion escuchada a travez del Buzzer
00079 void leer_color(void);              // funcion que retorna los componentes
00080                                     // RGB y Clear del color leido
00081                                     
00082                                     
00083 //****************************************************************************
00084 //                  Funciones
00085 
00086 
00087 
00088 void ReadPort()
00089 {
00090     if(SerialPort.writable()) SerialPort.abort_write();
00091     coolterm_comand = SerialPort.getc();
00092     
00093     if (coolterm_comand == iniciar_telemetria)  programa_ejecutar = iniciar_telemetria; ///  El programa que se ejecutará será Telemetria
00094     if (coolterm_comand == iniciar_telecomando)  programa_ejecutar = iniciar_telecomando;
00095     
00096     
00097 }
00098  
00099 
00100 int main()
00101  {
00102     Buzzer.write(0);        ///configura el ciclo util
00103     SerialPort.attach(&ReadPort, Serial::RxIrq);    ////  se Habilita la interrupcion serial o recepcion de datos
00104     //SerialPort.printf("Hello World, System Run !!\n"); // mensaje inicial
00105     
00106     
00107     while(1)
00108     {
00109      // Esperamos hasta que se GENERE una INTERUPCION y  
00110      // coolterm_comand reciba un comando ya sea iniciar_telemetria ó iniciar_telecomandos
00111      // Por lo que generará que programa_ejecutar sea igual al comando recivido
00112      
00113      // AHORA:   
00114      // SI EL PROGRAMA ESCOGIDO ES INICIAR_TELEMETRIA    
00115         if (programa_ejecutar == iniciar_telemetria)
00116         {            
00117             // ESPERAMOS A RECBIR UN COMANDO DESDE EL COOLTERM DIFERENTE AL que YA hemos RECIBIDO
00118             while(coolterm_comand == iniciar_telemetria)    wait_ms(1); // esperamos mientras se recibe otro dato
00119             
00120             ////  Desactivamos la interrupcion serial o recepcion de datos PORQUE NO NECESITAMOS recibir mas datos por AHORA
00121             SerialPort.attach(NULL, Serial::RxIrq);
00122             
00123             // SEGÚN LA TELEMETRIA SELECCIONADA (0X01, 0X02 .... 0XN) ENTONCES SE EJECUTA UNA FUNCIÓN
00124             switch (coolterm_comand)
00125             {
00126                     
00127                     case telemetria_1:  
00128                                         // Ejecutamos la Funcion LeerColor();
00129                                         leer_color();
00130                                         
00131                                         break; // salimos del SWITCH
00132                                         
00133                     // si no fue ninguno de los valores anteriores entonces:                    
00134                     default:            SerialPort.printf("telemetria desconocida, inicie nuevamente !!\n");
00135                                         
00136                                         break; // salimos del SWITCH
00137 
00138             }
00139             
00140             
00141             // Re inicializamos nuestras variables de control a sus valores iniciales
00142             // Para no seguir entrando a las sentencias IF
00143             programa_ejecutar = 0; coolterm_comand = 0; 
00144                                         
00145                                         
00146             ////  HABILITAMOS NUEVAMENTE la interrupcion serial o recepcion de datos
00147             SerialPort.attach(&ReadPort, Serial::RxIrq);          
00148         }
00149         
00150               
00151         
00152         //// SI EL PROGRAMA ESCOGIDO ES INICIAR_TELECOMANDO    
00153         if (programa_ejecutar == iniciar_telecomando)
00154         {        
00155             // ESPERAMOS A RECBIR UN COMANDO DESDE EL COOLTERM DIFERENTE AL que YA hemos RECIBIDO
00156             while(coolterm_comand == iniciar_telecomando)    wait_ms(1); // esperamos mientras se recibe otro dato
00157                     
00158             
00159             // SEGÚN EL TELECOMANDO SELECCIONADO (0X01, 0X02 .... 0XN) ENTONCES SE EJECUTA UNA FUNCIÓN
00160             switch (coolterm_comand)
00161             {
00162                     
00163                     case telemcomando_1:  
00164                                                   
00165                                             // ESPERAMOS A RECBIR UN COMANDO DESDE EL COOLTERM DIFERENTE AL ULTIMO RECIBIDO
00166                                             while(coolterm_comand == telemcomando_1)     wait_ms(1);
00167                                                     duracion_tono = coolterm_comand;  // lo almacenamos en:  duracion_tono
00168                                                     
00169                                             // ESPERAMOS A RECBIR UN COMANDO DESDE EL COOLTERM DIFERENTE AL ULTIMO RECIBIDO
00170                                             while(coolterm_comand == duracion_tono)     wait_ms(1);
00171                                                     tipo_tono = coolterm_comand;  // lo almacenamos en:  tipo_tono 
00172                                                     
00173                                             ////  Desactivamos la interrupcion serial o recepcion de datos PORQUE NO NECESITAMOS recibir mas datos por AHORA
00174                                             SerialPort.attach(0, Serial::RxIrq);
00175                                             // Ejecutamos la Funcion LeerColor();
00176                                             Buzzer_Tone(tipo_tono, duracion_tono);
00177                                         
00178                                         break; // salimos del SWITCH
00179                                         
00180                     // si no fue ninguno de los valores anteriores entonces:                    
00181                     default:            SerialPort.abort_read();
00182                                         SerialPort.printf("TeleComando desconocido, inicie nuevamente !!\n");
00183                                         
00184                                         break; // salimos del SWITCH
00185 
00186             }
00187             
00188             
00189             // Re inicializamos nuestras variables de control a sus valores iniciales
00190             // Para no seguir entrando a las sentencias IF
00191             programa_ejecutar = 0; coolterm_comand = 0; 
00192                                         
00193                                         
00194             ////  HABILITAMOS NUEVAMENTE la interrupcion serial o recepcion de datos
00195             SerialPort.attach(&ReadPort, Serial::RxIrq);  
00196             
00197         } // Finaliza el IF
00198          
00199         
00200     
00201     
00202     }// Finaliza el WHILE
00203     
00204     
00205 } // Finaliza el main
00206 
00207 void Buzzer_Tone(uint8_t tipo_tono, uint8_t duracion_tono)
00208     {
00209         
00210             
00211                 switch (tipo_tono)
00212             {
00213                     
00214                     case TONO_DO:       Buzzer.period_ms(DO);
00215                                        //SerialPort.printf("Tono Seleccionado DO!!\n");                                        
00216                                         
00217                                         break; // salimos del SWITCH
00218                                         
00219                     case TONO_RE:       Buzzer.period_ms(RE);
00220                                         //SerialPort.printf("Tono Seleccionado RE!!\n");
00221                                         
00222                                         break; // salimos del SWITCH
00223                                         
00224                     case TONO_MI:       Buzzer.period_ms(MI);
00225                                         //SerialPort.printf("Tono Seleccionado MI!!\n");
00226                                         
00227                                         break; // salimos del SWITCH
00228                                         
00229                     case TONO_SI:       Buzzer.period_ms(SI);
00230                                         //SerialPort.printf("Tono Seleccionado SI!!\n");
00231                                         
00232                                         break; // salimos del SWITCH
00233                                                             
00234                     // si no fue ninguno de los valores anteriores entonces:                    
00235                     default:            SerialPort.printf("teleComando desconocido, inicie nuevamente !!\n");
00236                                         
00237                                         break; // salimos del SWITCH
00238 
00239             }
00240                 // COMO EL CICLO UTIL DEL BUZZER ESTABA EN 0, POR LO CUAL NO SONABA
00241                 // SE PONE AL 50% DEL PERIODO
00242                 Buzzer.write(0.5);
00243                 // SE ESPERA DURANTE EN TIEMPO INGRESADO (EN SEGUNDOS )
00244                 wait(duracion_tono);
00245                 
00246                 // Se Reinicializa el Periodo y el Ciclo útil de la señal PWM 
00247                 // que va al Buzzer
00248                 Buzzer.period_ms(1);
00249                 Buzzer.write(0);
00250               
00251     
00252     
00253     }
00254 
00255 
00256 
00257 
00258 void leer_color()
00259     {
00260     
00261         red    = SENSOR_COLOR.ReadRed(); // OBTENEMOS EL TIEMPO DEL CICLO UTIL DE LA FRECUENCIA DE SALIDA 
00262         green  = SENSOR_COLOR.ReadGreen();
00263         blue   = SENSOR_COLOR.ReadBlue();
00264         clear  = SENSOR_COLOR.ReadClear();
00265         
00266         //printf("RED: %5d     GREEN: %5d     BLUE: %5d     CLEAR: %5d    \n ", red, green, blue, clear);
00267          
00268         red     *= 2;   // Calculamos EL PERIODO de la frecuencia generada por la lectura del fotodiodo rojo         
00269         blue    *= 2;   // Calculamos EL PERIODO de la frecuencia generada por la lectura del fotodiodo rojo
00270         green   *= 2;   // Calculamos EL PERIODO  de la frecuencia generada por la lectura del fotodiodo rojo
00271         clear   *= 2;   // Calculamos EL PERIODO  de la frecuencia generada por la lectura del fotodiodo rojo
00272         
00273         //printf("RED: %5d     GREEN: %5d     BLUE: %5d     CLEAR: %5d    \n ", red, green, blue, clear);
00274        
00275         
00276        //////////////////////////////////////////////////////////////     
00277        ////         identificar azul
00278        
00279        
00280        if(red <=42 && red >=24)
00281         {
00282             if(green >= 20 && green <= 28 )
00283             {
00284                 if(blue >= 10 && blue <= 16)
00285                 {
00286                         color_identificado = CMD_azul;
00287                         printf ( "0x0%1x\n ", CMD_azul); 
00288                         Buzzer.period_ms(DO);
00289                         Buzzer.write(0.5);
00290                         wait(4);
00291                         Buzzer.write(0);
00292                        
00293                 }
00294             }
00295          }   
00296                  
00297         
00298         
00299         
00300         /////////////////////////////////////////////////////////////
00301         ///         identificar rojo
00302         if(red <= 12 )
00303         {
00304             if(green >= 10 && green <= 28 ) 
00305                 {
00306                     if(blue >= 18 && blue <= 24)
00307                     {
00308                             color_identificado = CMD_rojo;
00309                             printf ( "0x0%1x\n ", CMD_rojo ); 
00310                             Buzzer.period_ms(RE);
00311                             Buzzer.write(0.5);  //PERIODO UTIL
00312                             wait(4);            //TIEMPO ACTIVO DEL BUZZER
00313                             Buzzer.write(0.0);
00314                     }
00315                 }
00316                 
00317             if(green < 10 && green >= 6 )
00318                 {
00319                     if(blue <= 12  )
00320                     {
00321                             color_identificado = CMD_clear;
00322                             printf ( "0x0%1x \n ", CMD_clear );
00323                             Buzzer.period_ms(MI);
00324                             Buzzer.write(0.5);
00325                             wait(4);
00326                             Buzzer.write(0);
00327                     }
00328                     
00329                 }
00330             
00331          }   
00332          
00333          
00334              if(green >= 36 && green <= 44 )
00335             {
00336                 if(red >= 40 && red <= 50 )
00337             
00338                 {
00339                         color_identificado = CMD_verde;
00340                         printf ( "0x0%1x \n ", CMD_verde );
00341                             Buzzer.period_ms(SI);
00342                             Buzzer.write(0.5);
00343                             wait(4);
00344                             Buzzer.write(0); 
00345                         
00346                     
00347                 }
00348             } 
00349             
00350             if  (color_identificado == ColorNoIdentificado)
00351             {
00352                 
00353                  
00354                         printf ( "0x0%1x \n ", ColorNoIdentificado);
00355                             Buzzer.period_ms(10);
00356                             Buzzer.write(0.5);
00357                             wait(4);
00358                             Buzzer.write(0); 
00359                         
00360                 
00361             }
00362                 
00363             color_identificado = ColorNoIdentificado;
00364         }
00365         
00366         
00367