Macros Corregidas

Dependencies:   BLE_API mbed

main.cpp

Committer:
Gustavo_Eduardo338
Date:
2016-09-19
Revision:
10:5580ae8cbe7e
Parent:
9:501a9e6710d2
Child:
11:965d5afe3a63

File content as of revision 10:5580ae8cbe7e:

/*
Copyright (c) 2012-2014 RedBearLab

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

#include "mbed.h"
#include "ble/BLE.h"
#include "GattCallbackParamTypes.h"

#define BLE_UUID_TXRX_SERVICE            0x0000 /**< The UUID of the Nordic UART Service. */
#define BLE_UUID_TX_CHARACTERISTIC       0x0002 /**< The UUID of the TX Characteristic. */
#define BLE_UUIDS_RX_CHARACTERISTIC      0x0003 /**< The UUID of the RX Characteristic. */

#define TXRX_BUF_LEN                     20

#define ON                              1
#define OFF                             0
#define IN                              1
#define OUT                             0
#define PWM                             2
#define NONE                            -1

//Solo puede estar definido un solo Board
//#define nRF51-DK_board
#define redBearLab_board

#ifdef nRF51-DK_board
//Aqui se define el hardware del nRF51-DK

//Analog in
#define A0                               P0_1   //Analog 0
#define A1                               P0_2   //Analog 1
#define A2                               P0_3   //Analog 2
#define A3                               P0_4   //Analog 3
#define A4                               P0_5   //Analog 4
#define A5                               P0_6   //Analog 5

//Digital

#define D0                               P0_14  //Digital I/O            
#define D1                               P0_12  //Digital I/O
#define D2                               P0_13  //Digital I/O 
#define D3                               P0_15  //Digital I/O
#define D4                               P0_21  //Digital I/O  (LED 1)
#define D5                               P0_22  //Digital I/O  (LED 2)
#define D6                               P0_23  //Digital I/O  (LED 3)
#define D7                               P0_24  //Digital I/O  (LED 4)
#define D8                               P0_17  //Digital I/O  (BUTTON 1) 
#define D9                               P0_19  //Digital I/O  (BUTTON 3)
#define D10                              P0_18  //Digital I/O  (BUTTON 2)
#define D11                              P0_20  //Digital I/O  (BUTTON 4)
#define D12                              P0_7   //Digital I/O
#define D13                              P0_30  //Digital I/O
#define D14                              P0_8   //Digital I/O
#define D15                              P0_16  //Digital I/O

//Aplicacion
#define LED_1                            P0_21  //Digital I/O  (LED 1)
#define LED_2                            P0_22  //Digital I/O  (LED 2)
#define LED_3                            P0_23  //Digital I/O  (LED 3)              
#define LED_4                            P0_24  //Digital I/O  (LED 4)

#define BTN_1                            P0_17  //Digital I/O  (BUTTON 1)
#define BTN_2                            P0_18  //Digital I/O  (BUTTON 2)
#define BTN_3                            P0_19  //Digital I/O  (BUTTON 3)
#define BTN_4                            P0_20  //Digital I/O  (BUTTON 4)

// Aqui se acaba la configuracion del board NRF51-DK

#else
//Aqui se define el hardware del redBearLab

//Analog in
#define A0                               P0_1   //Analog 0
#define A1                               P0_2   //Analog 0
#define A2                               P0_3   //Analog 0
#define A3                               P0_4   //Analog 0
#define A4                               P0_5   //Analog 0
#define A5                               P0_6   //Analog 0

//Digital
#define D0                               P0_11  //Digital I/O             
#define D1                               P0_9   //Digital I/O
#define D2                               P0_10  //Digital I/O
#define D3                               P0_8   //Digital I/O
#define D4                               P0_21  //Digital I/O
#define D5                               P0_23  //Digital I/O (PWM RBL)
#define D6                               P0_16  //Digital I/O (PWM RBL)
#define D7                               P0_17  //Digital I/O  
#define D8                               P0_19  //Digital I/O             
#define D9                               P0_18  //Digital I/O (PWM RBL)
#define D10                              P0_14  //Digital I/O
#define D11                              P0_12  //Digital I/O
#define D12                              P0_13  //Digital I/O (LED RBL)
#define D13                              P0_15  //Digital I/O 
#define D14                              P0_29  //Digital I/O
#define D15                              P0_28  //Digital I/O

//Aplicacion
#define LED_1                            P0_21  //Digital I/O  (LED 1)
#define LED_2                            P0_23  //Digital I/O  (LED 2)
#define LED_3                            P0_16  //Digital I/O  (LED 3)              
#define LED_4                            P0_17  //Digital I/O  (LED 4)

#define BTN_1                            P0_11  //Digital I/O  (BUTTON 1)
#define BTN_2                            P0_9   //Digital I/O  (BUTTON 2)
#define BTN_3                            P0_10  //Digital I/O  (BUTTON 3)
#define BTN_4                            P0_8   //Digital I/O  (BUTTON 4)

#endif


// Aqui se acabo la definicion del board REDBEARLAB

/****  Aqui se definen los pines necesarios independientemente del board seleccionado ******************

                     Instrucciones:
Pines digitales -->
                    ON  --> Usado
                    OFF --> No sera usado
                    IN  --> Entrada
                    OUT --> Salida

Pines Analogicos -->
                    ON  --> Usado
                    OFF --> No sera usado
                    Valor del TED en numero reales, ejemplo 39.1, sino se va a usar se queda con 0
********************************************************************************************************/

#define A0_USO                           ON     //-> Divisor de voltaje para medir bateria VDD
#define A1_USO                           ON     //-> Temperatura PT1000 (Borneras Shield de pruebas) Borneras
#define A2_USO                           OFF     //-> Temperatura PT1000 (Borneras Shield de pruebas)
#define A3_USO                           OFF    //-> Humedad (Borneras Shield de pruebas)
#define A4_USO                           OFF     //-> Humedad (Borneras Shield de pruebas)
#define A5_USO                           OFF     //-> Conectarlo al LM35

#define A0_TED                           39.1  //Volts,  bateria
#define A1_TED                           39.2   // ºC  temperatura PT 1000
#define A2_TED                           0   // ºC  temperatura PT 1000
#define A3_TED                           0
#define A4_TED                           0
#define A5_TED                           0   // ºC  temperatura ambiental con el LM35

#define D0_USO                           OFF    //Ejemplo: ON
#define D1_USO                           OFF    //Ejemplo: OFF
#define D2_USO                           ON
#define D3_USO                           ON
#define D4_USO                           ON
#define D5_USO                           ON
#define D6_USO                           OFF
#define D7_USO                           ON
#define D8_USO                           ON
#define D9_USO                           ON     //BUTTON 1 (NRF51-DK)
#define D10_USO                          OFF     //BUTTON 2 (NRF51-DK)
#define D11_USO                          OFF     //BUTTON 3 (NRF51-DK)
#define D12_USO                          OFF     //BUTTON 4 (NRF51-DK)
#define D13_USO                          OFF
#define D14_USO                          OFF
#define D15_USO                          OFF

#define D0_TYPE                          NONE    // Ejemplo: OUT
#define D1_TYPE                          NONE     // Ejemplo: IN
#define D2_TYPE                          IN    // Para medir Humedad con Resistencia AC
#define D3_TYPE                          IN    // Led encienden con 1
#define D4_TYPE                          IN    // Led encienden con 0
#define D5_TYPE                          IN    // Led encienden con 0
#define D6_TYPE                          NONE    // Led encienden con 1
#define D7_TYPE                          OUT     // Pushbuttons  (Activos en bajo)
#define D8_TYPE                          OUT     // Pushbuttons  (Activos en bajo)
#define D9_TYPE                          PWM     // DIP Switch 1 (Activos en bajo)
#define D10_TYPE                         NONE     // DIP Switch 2 (Activos en bajo)
#define D11_TYPE                         NONE     // DIP Switch 3 (Activos en bajo)
#define D12_TYPE                         NONE    // Para medir Humedad con Resistencia AC
#define D13_TYPE                         NONE     // DIP Switch 4 (Activos en bajo)
#define D14_TYPE                         NONE    // Para medir Humedad con Resistencia AC
#define D15_TYPE                         NONE    // Para medir Humedad con Resistencia AC

//Macros de mbed
/*** Aqui Se definen todas macros en funcion de si el bit esta ON u OFF   ************

Estos son las macors ya definidas:
DigitalOut      LED_SET(DIGITAL_OUT_PIN);   //Modo de uso --> LED_SET = 1 o LED_SET = 0;
DigitalIn       BUTTON(DIGITAL_IN_PIN);     //Modo de uso --> if (BUTTON != old_state)
PwmOut          PWM(PWM_PIN);               //Modo de uso -->  PWM = value;
AnalogIn        ANALOGTEMP(ANALOG_IN_PIN);  //Modo de uso -> float s = ANALOG_A0;
AnalogIn        ANALOGBAT(ANALOG_IN_BAT);
Servo           MYSERVO(SERVO_PIN);
*************************************************************************************/

//Macros analogicas
AnalogIn        ANALOG_A0(A0);   //Bateria
AnalogIn        ANALOG_A1(A1);
AnalogIn        ANALOG_A2(A2);
AnalogIn        ANALOG_A3(A3);
AnalogIn        ANALOG_A4(A4);
AnalogIn        ANALOG_A5(A5);   //Temperatura ambiental con LM35

//Macros Digitales
DigitalIn  BUTTON_0(D0);
DigitalIn  BUTTON_1(D1);
DigitalIn  BUTTON_2(D2);
DigitalIn  BUTTON_3(D3);
DigitalIn  BUTTON_4(D4);
DigitalIn  BUTTON_5(D5);
DigitalIn  BUTTON_6(D6);
DigitalIn  BUTTON_7(D7);
DigitalIn  BUTTON_8(D8);
DigitalIn  BUTTON_9(D9);
DigitalIn  BUTTON_10(D10);
DigitalIn  BUTTON_11(D11);
DigitalIn  BUTTON_12(D12);
DigitalIn  BUTTON_13(D13);
DigitalIn  BUTTON_14(D14);
DigitalIn  BUTTON_15(D15);

DigitalOut LED_SET_0(D0);
DigitalOut LED_SET_1(D1);
DigitalOut LED_SET_2(D2);
DigitalOut LED_SET_3(D3);
DigitalOut LED_SET_4(D4);
DigitalOut LED_SET_5(D5);
DigitalOut LED_SET_6(D6);
DigitalOut LED_SET_7(D7);
DigitalOut LED_SET_8(D8);
DigitalOut LED_SET_9(D9);
DigitalOut LED_SET_10(D10);
DigitalOut LED_SET_11(D11);
DigitalOut LED_SET_12(D12);
DigitalOut LED_SET_13(D13);
DigitalOut LED_SET_14(D14);
DigitalOut LED_SET_15(D15);

PwmOut     PWM_5(D5);
PwmOut     PWM_6(D6);
PwmOut     PWM_9(D9);

//Hasta aqui la definicion de macos
//Digital Inputs --> DATA VALUE
uint16_t DigitalInput_DATA = 0x0000;    //Mapa de bits con los valores de la entrada digital segun la posicion
uint16_t PAQUETE_ID  = 0;

float AnalogInput_Ted [6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};  //Si el TED es cero, es que no está en uso

//Digital input, cantidad, posiciones --> de todos, ted = 0, tipico hasta 16
uint16_t DigitalInput_Pos = 0x0000;    //Mapa de bits, seran usados los bytes del TED 16 bits

//Digital output, cantidad, pocisiones --> de todos, ted = 0,  tipico hasta 16
uint16_t DigitalOutput_Pos = 0x0000;    //Mapa de bits, seran usados los bytes del TED 16 bits

uint16_t DigitalPwm_Pos = 0x0000;       //Mapa de bits, seran usados los bytes del TED 16 bits

//Digital input, cantidad, posiciones --> de todos, ted = 0, tipico hasta 16
uint8_t AnalogInput_Pos = 0x0000;    //Mapa de bits, seran usados los bytes del TED 16 bits

//Digital output, cantidad, pocisiones --> de todos, ted = 0,  tipico hasta 16
uint8_t AnalogOutput_Pos = 0x0000;   //Mapa de bits, seran usados los bytes del TED 16 bits


// Declarando los pines
//static int32_t send_config = 0;

static int8_t SEND_CONFIG_GENERAL = 0;
static int8_t SEND_CONFIG_ANALOG_0 = 0, SEND_CONFIG_ANALOG_1 = 0, SEND_CONFIG_ANALOG_2 = 0, SEND_CONFIG_ANALOG_3 = 0, SEND_CONFIG_ANALOG_4 = 0, SEND_CONFIG_ANALOG_5 = 0;


BLE ble;

// Permite imprimir mensajes en la consola
Serial pc(USBTX, USBRX);

static uint8_t analog_enabled = 0;
static uint8_t state_button_2 = 0, state_button_3 = 0,state_button_4 = 0,state_button_5 = 0 ;
static uint8_t state_button_6 = 0, state_button_7 = 0, state_button_8 = 0, state_button_9 = 0,state_button_10 = 0,state_button_11 = 0 ;
static uint8_t state_button_12 = 0, state_button_13 = 0, state_button_14 = 0, state_button_15 = 0;

// The Nordic UART Service
static const uint8_t uart_base_uuid[] = {0x71, 0x3D, 0, 0, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_tx_uuid[]   = {0x71, 0x3D, 0, 3, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_rx_uuid[]   = {0x71, 0x3D, 0, 2, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_base_uuid_rev[] = {0x1E, 0x94, 0x8D, 0xF1, 0x48, 0x31, 0x94, 0xBA, 0x75, 0x4C, 0x3E, 0x50, 0, 0, 0x3D, 0x71};

// Trama de Configuracion de los Pines (a).
static uint8_t TRAMA_CONFIG_GENERAL[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , 0x00};        //  Length 12

uint8_t txPayload[TXRX_BUF_LEN] = {0,};
uint8_t rxPayload[TXRX_BUF_LEN] = {0,};

GattCharacteristic  txCharacteristic (uart_tx_uuid, txPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);
GattCharacteristic  rxCharacteristic (uart_rx_uuid, rxPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
GattCharacteristic *uartChars[] = {&txCharacteristic, &rxCharacteristic};
GattService         uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));

float in[] = { 100.00, 100.39, 100.78, 101.17, 101.56, 101.95, 102.34, 102.73, 103.12, 103.51,
               103.90, 104.29, 104.68, 105.07, 105.46, 105.85, 106.24, 106.63, 107.02, 107.40,
               107.79, 108.18, 108.57, 108.96, 109.35, 109.73, 110.12, 110.51, 110.90, 111.29,
               111.67, 112.06, 112.45, 112.83, 113.22, 113.61, 114.00, 114.38, 114.77, 115.15,
               115.54, 115.93, 116.31, 116.70, 117.08, 117.47, 117.86, 118.24, 118.63, 119.01,
               119.40, 119.78, 120.17, 120.55, 120.94, 121.32, 121.71, 122.09, 122.47, 122.86,
               123.24, 123.63, 124.01, 124.39, 124.78, 125.16, 125.54, 125.93, 126.31, 126.69,
               127.08, 127.46, 127.84, 128.22, 128.61, 128.99, 129.37, 129.75, 130.13, 130.52
             };
// known resistance in voltage divider
int R1 = 217;

float MultiMap(float val, float* _in, uint8_t size)
{
    // calculate if value is out of range
    if (val < _in[0] ) return -99.99;
    if (val > _in[size-1] ) return 99.99;

    //  search for 'value' in _in array to get the position No.
    uint8_t pos = 0;
    while(val > _in[pos]) pos++;

    // handles the 'rare' equality case
    if (val == _in[pos]) return pos;

    float r1 = _in[pos-1];
    float r2 = _in[pos];
    int c1 = pos-1;
    int c2 = pos;

    return c1 + (val - r1) / (r2-r1) * (c2-c1);
}



// https://developer.mbed.org/forum/repo-61676-BLE_GAP_Example-community/topic/17193/
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *)
{
    BLE& ble = BLE::Instance(BLE::DEFAULT_INSTANCE);
    pc.printf("Disconnected \r\n");
    pc.printf("Restart advertising \r\n");
    ble.startAdvertising();
    analog_enabled = 0;         //  Deja que envie lecturas el PT 1000

    SEND_CONFIG_GENERAL = 0;

    //  En caso de no completarse el envio de la configuraciones las detenemos por completo, y dehabilitamos el envio.
    SEND_CONFIG_ANALOG_0 == OFF;
    SEND_CONFIG_ANALOG_1 == OFF;
    SEND_CONFIG_ANALOG_2 == OFF;
    SEND_CONFIG_ANALOG_3 == OFF;
    SEND_CONFIG_ANALOG_4 == OFF;
    SEND_CONFIG_ANALOG_5 == OFF;

}

//Leemos todos las entradas digitales que esten activas y lo ponemos en la posicion correspondiente
void readDigitalInputs_Value ()
{
    //  DigitalInput_DATA = (uint16_t) ((BUTTON_15 << 15) | (BUTTON_14 << 14) | (BUTTON_13 << 13) | (BUTTON_12 << 12) | (BUTTON_11 << 11) | (BUTTON_10 << 10) | (BUTTON_9 << 9) | (BUTTON_8 << 8) | (BUTTON_7 << 7) | (BUTTON_6 << 6) |(BUTTON_5 << 5) | (BUTTON_4 << 4) | (BUTTON_3 << 3) | (BUTTON_2 << 2) | (BUTTON_1 << 1) | (BUTTON_1 << 0));
    DigitalInput_DATA = (uint16_t) ((BUTTON_15 << 15) | (BUTTON_14 << 14) | (BUTTON_13 << 13) | (BUTTON_12 << 12) | (BUTTON_11 << 11) | (BUTTON_10 << 10) | (BUTTON_9 << 9) | (BUTTON_8 << 8) | (BUTTON_7 << 7) | (BUTTON_6 << 6) |(BUTTON_5 << 5) | (BUTTON_4 << 4) | (BUTTON_3 << 3) | (BUTTON_2 << 2));
}

//Funcion para crear los extra bytes
void makeExtraBytes_CONFIG ()
{
    //  Teds de los Analog inputs
    AnalogInput_Ted [0] = A0_TED;
    AnalogInput_Ted [1] = A1_TED;
    AnalogInput_Ted [2] = A2_TED;
    AnalogInput_Ted [3] = A3_TED;
    AnalogInput_Ted [4] = A4_TED;
    AnalogInput_Ted [5] = A5_TED;

    if (D15_USO == ON && D15_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D15_USO << 15);

    if (D14_USO == ON && D14_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D14_USO << 14);

    if (D13_USO == ON && D13_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D13_USO << 13);

    if (D12_USO == ON && D12_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D12_USO << 12);

    if (D11_USO == ON && D11_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D11_USO << 11);

    if (D10_USO == ON && D10_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D10_USO << 10);

    if (D9_USO == ON && D9_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D9_USO << 9);

    if (D8_USO == ON && D8_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D8_USO << 8);

    if (D7_USO == ON && D7_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D7_USO << 7);

    if (D6_USO == ON && D6_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D6_USO << 6);

    if (D5_USO == ON && D5_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D5_USO << 5);

    if (D4_USO == ON && D4_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D4_USO << 4);

    if (D3_USO == ON && D3_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D3_USO << 3);

    if (D2_USO == ON && D2_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D2_USO << 2);

    if (D1_USO == ON && D1_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D1_USO << 1);

    if (D0_USO == ON && D0_TYPE == IN)
        DigitalInput_Pos |=  (uint16_t) (D0_USO << 0);




    if (D15_USO == 1 && D15_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D15_USO << 15);

    if (D14_USO == 1 && D14_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D14_USO << 14);

    if (D13_USO == 1 && D13_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D13_USO << 13);

    if (D12_USO == 1 && D12_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D12_USO << 12);

    if (D11_USO == 1 && D11_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D11_USO << 11);

    if (D10_USO == 1 && D10_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D10_USO << 10);

    if (D9_USO == 1 && D9_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D9_USO << 9);

    if (D8_USO == 1 && D8_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D8_USO << 8);

    if (D7_USO == 1 && D7_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D7_USO << 7);

    if (D6_USO == 1 && D6_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D6_USO << 6);

    if (D5_USO == 1 && D5_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D5_USO << 5);

    if (D4_USO == 1 && D4_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D4_USO << 4);

    if (D3_USO == 1 && D3_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D3_USO << 3);

    if (D2_USO == 1 && D2_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D2_USO << 2);

    if (D1_USO == 1 && D1_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D1_USO << 1);

    if (D0_USO == 1 && D0_TYPE == OUT)
        DigitalOutput_Pos |=  (uint16_t) (D0_USO << 0);



    if (D15_USO == 1 && D15_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D15_USO << 15);

    if (D14_USO == 1 && D14_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D14_USO << 14);

    if (D13_USO == 1 && D13_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D13_USO << 13);

    if (D12_USO == 1 && D12_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D12_USO << 12);

    if (D11_USO == 1 && D11_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D11_USO << 11);

    if (D10_USO == 1 && D10_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D10_USO << 10);

    if (D9_USO == 1 && D9_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D9_USO << 9);

    if (D8_USO == 1 && D8_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D8_USO << 8);

    if (D7_USO == 1 && D7_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D7_USO << 7);

    if (D6_USO == 1 && D6_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D6_USO << 6);

    if (D5_USO == 1 && D5_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D5_USO << 5);

    if (D4_USO == 1 && D4_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D4_USO << 4);

    if (D3_USO == 1 && D3_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D3_USO << 3);

    if (D2_USO == 1 && D2_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D2_USO << 2);

    if (D1_USO == 1 && D1_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D1_USO << 1);

    if (D0_USO == 1 && D0_TYPE == PWM)
        DigitalPwm_Pos |=  (uint16_t) (D0_USO << 0);


    //Digital inputs
    AnalogInput_Pos = (uint16_t) ((A5_USO << 5) | (A4_USO << 4) | (A3_USO << 3) | (A2_USO << 2) | (A1_USO << 1) | (A0_USO << 0));
    //Digital Outputs



    //para probar
    pc.printf("DigitalInput_Pos = %x \r\n", DigitalInput_Pos);
    pc.printf("DigitalOutput_Pos = %x \r\n", DigitalOutput_Pos);
    pc.printf("AnalogInput_Pos = %x \r\n", AnalogInput_Pos);
    pc.printf("AnalogOutput_Pos = %x \r\n", DigitalPwm_Pos);
    pc.printf("---------------------------\r\n");

    //  Definimos la trama de configuracion general
    TRAMA_CONFIG_GENERAL [0] = 0xC1;                    //  Codigo de configuracion general
    TRAMA_CONFIG_GENERAL [1] = 0xA1;                    //  Codigo de entradas analogicas
    TRAMA_CONFIG_GENERAL [2] = AnalogInput_Pos;                    //  Valor de las entradas analogicas
    TRAMA_CONFIG_GENERAL [3] = 0xA0;                    //  Codigo de las salidas analogicas
    TRAMA_CONFIG_GENERAL [4] = (DigitalPwm_Pos >> 8);                    //  Valor de las salidas analogicas
    TRAMA_CONFIG_GENERAL [5] = (DigitalPwm_Pos);                    //  Valor de las salidas analogicas
    TRAMA_CONFIG_GENERAL [6] = 0xD1;                    //  Codigo de las entradas digitales
    TRAMA_CONFIG_GENERAL [7] = (DigitalInput_Pos >> 8);
    TRAMA_CONFIG_GENERAL [8] = DigitalInput_Pos;
    TRAMA_CONFIG_GENERAL [9] = 0xD0;                    //  Codigo de las salidas difitales
    TRAMA_CONFIG_GENERAL [10] = (DigitalOutput_Pos>> 8);
    TRAMA_CONFIG_GENERAL [11] = DigitalOutput_Pos;

}



// Ingresa por este metdo unicamente la primera vez que se conecta al mote.
// Tomado desde: https://developer.mbed.org/teams/Bluetooth-Low-Energy/code/BLE_LEDBlinker/file/dc392bde2b3c/main.cpp
void connectionCallback(const Gap::ConnectionCallbackParams_t *)
{
    pc.printf("connectionCallback \r\n");

    makeExtraBytes_CONFIG();
    SEND_CONFIG_GENERAL = 1;
}

// Recepta las caracteristicas que se desea escribir en el mote.
void WrittenHandler(const GattWriteCallbackParams *Handler)
{
    pc.printf("WrittenHandler(const GattWriteCallbackParams *Handler) \r\n");
    uint8_t buf[TXRX_BUF_LEN];
    uint16_t bytesRead, index;

    if (Handler->handle == txCharacteristic.getValueAttribute().getHandle()) {
        ble.readCharacteristicValue(txCharacteristic.getValueAttribute().getHandle(), buf, &bytesRead);
        memset(txPayload, 0, TXRX_BUF_LEN);
        memcpy(txPayload, buf, TXRX_BUF_LEN);

        for(index=0; index<bytesRead; index++)
            pc.putc(buf[index]);

        pc.printf("Leemos la trama: \r\n");
        for(index=0; index<bytesRead; index++) {
            pc.printf("buf[%02x]: %02x\r\n", index, buf[index]);
        }

        // Desde el telefono desactiva el envio de tramas de configuracion general o de cada sensor.
        if (buf[0] == 0xDC) {              //  Dato Configuracion
            if(buf[1] == 0xC1) {            //  Hace referencia a la configuración general
                SEND_CONFIG_GENERAL = buf[2];      // Debe ser cero, hace que ya no se vuelva a enviar la conf general del mote

                //  Comprueba si estan habilitados las salidas analogicas, y las
                //  inicializa a 1 para que mas adelante envie la configuracion
                //  de cada sensor
                SEND_CONFIG_ANALOG_0 = (A0_USO == ON)?1:0;
                SEND_CONFIG_ANALOG_1 = (A1_USO == ON)?1:0;
                SEND_CONFIG_ANALOG_2 = (A2_USO == ON)?1:0;
                SEND_CONFIG_ANALOG_3 = (A3_USO == ON)?1:0;
                SEND_CONFIG_ANALOG_4 = (A4_USO == ON)?1:0;
                SEND_CONFIG_ANALOG_5 = (A5_USO == ON)?1:0;
            }

            //  Maneja las Tramas de confirmacion de la configuracion detallada de cada senssor analogico
            if(buf[1] == 0xC2) {            //  Hace referencia a la configuracion detallada por sensor.
                switch (buf[2]) {           //  Evalua la posición
                    case 0x00:              //  0xA0
                        SEND_CONFIG_ANALOG_0 = buf[3];      //  buf[3] debe ser 0, para detenerse el envió SEND_CONFIG_ANALOG_0
                        break;
                    case 0x01:              //  0xA1
                        SEND_CONFIG_ANALOG_1 = buf[3];      //  buf[3] debe ser 0, para detenerse el envió SEND_CONFIG_ANALOG_1
                        break;
                    case 0x02:              //  0xA2
                        SEND_CONFIG_ANALOG_2 = buf[3];      //  buf[3] debe ser 0, para detenerse el envió SEND_CONFIG_ANALOG_2
                        break;
                    case 0x03:              //  0xA3
                        SEND_CONFIG_ANALOG_3 = buf[3];      //  buf[3] debe ser 0, para detenerse el envió SEND_CONFIG_ANALOG_3
                        break;
                    case 0x04:              //  0xA4
                        SEND_CONFIG_ANALOG_4 = buf[3];      //  buf[3] debe ser 0, para detenerse el envió SEND_CONFIG_ANALOG_4
                        break;
                    case 0x05:              //  0xA5
                        SEND_CONFIG_ANALOG_5 = buf[3];      //  buf[3] debe ser 0, para detenerse el envió SEND_CONFIG_ANALOG_5
                        break;
                }
            }
        }


        // Verifico si es una trama de Escitura.
        if(buf[0] == 0xEE) {
            PAQUETE_ID = buf[1];
            // Verifico si es un signal Digital Out
            if(buf[2] == 0xD0) {
                //  Evaluo sobre que pin se debe actuar.
                switch (buf[3]) {
                    case 0x00:
                        LED_SET_0 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x01:
                        LED_SET_1 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x02:
                        LED_SET_2 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x03:
                        LED_SET_3 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x04:
                        LED_SET_4 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x05:
                        LED_SET_5 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x06:
                        LED_SET_6 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x07:
                        LED_SET_7 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x08:
                        LED_SET_8 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x09:
                        LED_SET_9 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x10:
                        LED_SET_10 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x11:
                        LED_SET_11 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x12:
                        LED_SET_12 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x13:
                        LED_SET_13 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x14:
                        LED_SET_14 = (buf[4] == 0x01) ? 1:0;
                        break;
                    case 0x15:
                        LED_SET_15 = (buf[4] == 0x01) ? 1:0;
                        break;
                }
                // Verifico si es un signal Analog out
            } else if(buf[2] == 0xA0) {
                float value = (float)buf[4]/255;
                switch (buf[3]) {
                    case 0x05:
                        PWM_5 = value;
                        break;
                    case 0x06:
                        PWM_6 = value;
                        break;
                    case 0x09:
                        PWM_9 =value;
                        break;

                }
            }

        }
    }
}


/*
* Desde este metodo envia las tramas al Gateway.
*/
void m_status_check_handle(void)
{

    uint8_t TRAMA_CONFIG_ANALOG[5];
    uint8_t LECTURA_DIGITAL[6];

    /**if (analog_enabled) { // if analog reading enabled
        // Read and send out
        float s = ANALOG;
        uint16_t value = s*1024;
        buf[0] = (0xDD);                    //  Codigo
        buf[1] = (0x00);                    //  paquete id
        buf[2] = (0xA1);                    //  A1| A0| D1| D0
        buf[3] = (20);                      //  Posicion
        buf[4] = (value >> 8);                   //  Valor
        buf[5] = (value);                   //  Valor

        //pc.printf("buf[4]: %d\r\n", buf[4]);
        //pc.printf("buf[5]: %d\r\n", buf[5]);

        //pc.printf("value pt 1000: %d\r\n", value);  // Imprimo en terminal lo que esta enviando desde el mote.

        ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 6);    // Para el RTD
    }
    **/

    //pc.printf("enviar_config %d \r\n", enviar_config_01);
    if (SEND_CONFIG_GENERAL == 1) {
        //  Envia la configuracion Genaral del Mote.
        pc.printf("TRAMA_CONFIG_GENERAL0 %d \r\n", TRAMA_CONFIG_GENERAL[0]);
        pc.printf("TRAMA_CONFIG_GENERAL1 %d \r\n", TRAMA_CONFIG_GENERAL[1]);
        pc.printf("SEND_CONFIG_GENERAL %d \r\n", SEND_CONFIG_GENERAL);
        ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), TRAMA_CONFIG_GENERAL, 12);
    }

//  Envio de las tramas de Configuracion del Mote.
    //  --  Configuracion detallada de los sensores.
    //  Evalua si se encuentra pendiente enviar la configuracion de los sensores.
    if (SEND_CONFIG_ANALOG_0 == ON||SEND_CONFIG_ANALOG_1 == ON||SEND_CONFIG_ANALOG_2 == ON||SEND_CONFIG_ANALOG_3 == ON||SEND_CONFIG_ANALOG_4 == ON||SEND_CONFIG_ANALOG_5 == ON) {

        TRAMA_CONFIG_ANALOG[0] = (0xC2);                //  Codigo que indica que la configuracion sera por cada Pin.
        TRAMA_CONFIG_ANALOG[1] = (0x05);                //  Categoria puede ser: A (Actuador) | 5 (Sensor)
        TRAMA_CONFIG_ANALOG[2] = (0xAA);                //  Tipo de Signal AA | DD

        if (A0_USO == ON && SEND_CONFIG_ANALOG_0 == ON) {
            TRAMA_CONFIG_ANALOG[3] = 0x00;              //  Posicion que ocupa en el mote
            TRAMA_CONFIG_ANALOG[4] = A0_TED;
            pc.printf("SEND_CONFIG_ANALOG_0 \r\n");
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), TRAMA_CONFIG_ANALOG, 5);

        } else if (A1_USO == ON && SEND_CONFIG_ANALOG_1 == ON) {
            TRAMA_CONFIG_ANALOG[3] = 0x01;              //  Posicion que ocupa en el mote
            TRAMA_CONFIG_ANALOG[4] = A1_TED;
            pc.printf("SEND_CONFIG_ANALOG_1 \r\n");
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), TRAMA_CONFIG_ANALOG, 5);

        } else if (A2_USO == ON && SEND_CONFIG_ANALOG_2 == ON) {
            TRAMA_CONFIG_ANALOG[3] = 0x02;              //  Posicion que ocupa en el mote
            TRAMA_CONFIG_ANALOG[4] = A2_TED;
            pc.printf("SEND_CONFIG_ANALOG_2 \r\n");
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), TRAMA_CONFIG_ANALOG, 5);

        } else if (A3_USO == ON && SEND_CONFIG_ANALOG_3 == ON) {
            TRAMA_CONFIG_ANALOG[3] = 0x03;              //  Posicion que ocupa en el mote
            TRAMA_CONFIG_ANALOG[4] = A3_TED;
            pc.printf("SEND_CONFIG_ANALOG_3 \r\n");
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), TRAMA_CONFIG_ANALOG, 5);

        } else if (A4_USO == ON && SEND_CONFIG_ANALOG_4 == ON) {
            TRAMA_CONFIG_ANALOG[3] = 0x04;              //  Posicion que ocupa en el mote
            TRAMA_CONFIG_ANALOG[4] = A4_TED;
            pc.printf("SEND_CONFIG_ANALOG_4 \r\n");
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), TRAMA_CONFIG_ANALOG, 5);

        } else if (A5_USO == ON && SEND_CONFIG_ANALOG_5 == ON) {
            TRAMA_CONFIG_ANALOG[3] = 0x05;              //  Posicion que ocupa en el mote
            TRAMA_CONFIG_ANALOG[4] = A5_TED;
            pc.printf("SEND_CONFIG_ANALOG_5 \r\n");
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), TRAMA_CONFIG_ANALOG, 5);
        }
    }

//  Envio de las tramas de lecturas del Mote.
    //  --  Envio las lecturas digitales
    if (PAQUETE_ID != 0) {
        PAQUETE_ID = 0;
        readDigitalInputs_Value();                      //  Leemos los estados digitales.

        LECTURA_DIGITAL[0] = (0xDD);                    //  Codigo
        LECTURA_DIGITAL[1] = PAQUETE_ID;                //  paquete id
        LECTURA_DIGITAL[2] = PAQUETE_ID;                //  paquete id
        LECTURA_DIGITAL[3] = 0xDD;                      //  A1| A0| D1| D0
        LECTURA_DIGITAL[4] = DigitalInput_DATA;         //  Posicion
        pc.printf("Envio LECTURA_DIGITAL \r\n");  // Imprimo en terminal lo que esta enviando desde el mote.

        ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), LECTURA_DIGITAL, 5);    // Para el RTD
    }
    //  --  Envio de las lecturas Analogicas.

    /**
        if (resp_digital_out_7 != 0) {
            // Envia trama de lectura
            buf[0] = (0xDD);                    //  Codigo
            buf[1] = resp_digital_out_7;         //  paquete id
            buf[2] = (0xD0);                    //  A1| A0| D1| D0
            buf[3] = (10);                      //  Posicion
            buf[4] = LED_SET_7;                       //  Valor
            pc.printf("resp_digital_out_7 %d\r\n", resp_digital_out_7);  // Imprimo en terminal lo que esta enviando desde el mote.

            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 5);    // Para el RTD
        }**/
    //wait_ms(100);

    // If digital in changes, report the state
    if ((BUTTON_2 != state_button_2 && D2_TYPE == IN) || (BUTTON_3 != state_button_3 && D3_TYPE == IN) || (BUTTON_3 != state_button_3 && D3_TYPE == IN) || (BUTTON_4 != state_button_4 && D4_TYPE == IN) || (BUTTON_5 != state_button_5 && D5_TYPE == IN) || (BUTTON_6 != state_button_6 && D6_TYPE == IN) || (BUTTON_7 != state_button_7 && D7_TYPE == IN) || (BUTTON_8 != state_button_8 && D8_TYPE == IN) || (BUTTON_9 != state_button_9 && D9_TYPE == IN) || (BUTTON_10 != state_button_10 && D10_TYPE == IN) || (BUTTON_11 != state_button_11 && D11_TYPE == IN) || (BUTTON_12 != state_button_12 && D12_TYPE == IN) || (BUTTON_13 != state_button_13 && D13_TYPE == IN) || (BUTTON_14 != state_button_14 && D14_TYPE == IN) || (BUTTON_15 != state_button_15 && D15_TYPE == IN)) {
        //  Lecturas digitales
        readDigitalInputs_Value();
        //  Actualizando estados de las variables auxiliares
        state_button_2 = (D2_USO == ON && D2_TYPE == IN) ? BUTTON_2 : 0;
        state_button_3 = (D3_USO == ON && D3_TYPE == IN) ? BUTTON_3:0;
        state_button_4 = (D4_USO == ON && D4_TYPE == IN) ? BUTTON_4:0;
        state_button_5 = (D5_USO == ON && D5_TYPE == IN) ? BUTTON_5:0;
        state_button_6 = (D6_USO == ON && D6_TYPE == IN) ? BUTTON_6:0;
        state_button_7 = (D7_USO == ON && D7_TYPE == IN) ? BUTTON_7:0;
        state_button_8 = (D8_USO == ON && D8_TYPE == IN) ? BUTTON_8:0;
        state_button_9 = (D9_USO == ON && D9_TYPE == IN) ? BUTTON_9:0;
        state_button_10 = (D10_USO == ON && D10_TYPE == IN) ? BUTTON_10:0;
        state_button_11 = (D11_USO == ON && D11_TYPE == IN) ? BUTTON_11:0;
        state_button_12 = (D12_USO == ON && D12_TYPE == IN) ? BUTTON_12:0;
        state_button_13 = (D13_USO == ON && D13_TYPE == IN) ? BUTTON_13:0;
        state_button_14 = (D14_USO == ON && D14_TYPE == IN) ? BUTTON_14:0;
        state_button_15 = (D15_USO == ON && D15_TYPE == IN) ? BUTTON_15:0;

        PAQUETE_ID = 0x3E8;
        pc.printf("DigitalInput_DATA: %d \r\n", DigitalInput_DATA);
        LECTURA_DIGITAL[0] = 0xDD;                                      //  Codigo
        LECTURA_DIGITAL[1] = (PAQUETE_ID >> 8);                         //  primera parte del paquete
        LECTURA_DIGITAL[2] = PAQUETE_ID ;                               //  segunda parte del paquete
        LECTURA_DIGITAL[3] = 0xD0;                                      //  A1| A0| D1| D0
        LECTURA_DIGITAL[4] = (DigitalInput_DATA >> 8);                  //  Valor de las salidas digitales
        LECTURA_DIGITAL[5] = (DigitalInput_DATA);                       //  Valor de las salidas digitales

        ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), LECTURA_DIGITAL, 6);    // Para el RTD
    }


    /**int pt100 = ANALOG_A5.read();
    pc.printf("pt100: %f Ohm\r\n", pt100);

    float Vout = pt100 * (5.0 / 1023.0);
    float R2 = R1 * 1/(5.0/Vout - 1);

    float c =  MultiMap(R2,in,80);

    pc.printf("Resistance: %f Ohm\r\n", R2);
    pc.printf("Temperature: %f C\r\n", c);
    */
}

int main(void)
{
    Ticker ticker;
    ticker.attach_us(m_status_check_handle, 200000);

    ble.init();
    ble.onDisconnection(disconnectionCallback);
    ble.onConnection(connectionCallback);
    ble.onDataWritten(WrittenHandler);

    pc.baud(9600);
    pc.printf("SimpleChat Init \r\n");
    //pc.attach( uartCB , pc.RxIrq);

    // setup advertising
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *)"Biscuit", sizeof("Biscuit") - 1);   // Original:  Biscuit
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid));

    ble.setAdvertisingInterval(160);

    ble.addService(uartService);

    ble.startAdvertising();
    pc.printf("Advertising Start \r\n");

    //por dixys
    // para probar, luego quitar. Esto hace que cada ticker se envie un dato analogico via BLE
    analog_enabled = 0;

    while(1) {
        ble.waitForEvent();
    }
}