Exemple #1
0
/**
 * @brief Function for main application entry.
 */
int main(void)
{
    LEDS_CONFIGURE(LEDS_MASK);
    LEDS_OFF(LEDS_MASK);
    uint32_t err_code;
    const app_uart_comm_params_t comm_params =
      {
          RX_PIN_NUMBER,
          TX_PIN_NUMBER,
          RTS_PIN_NUMBER,
          CTS_PIN_NUMBER,
          APP_UART_FLOW_CONTROL_ENABLED,
          false,
          UART_BAUDRATE_BAUDRATE_Baud38400
      };

    APP_UART_FIFO_INIT(&comm_params,
                         UART_RX_BUF_SIZE,
                         UART_TX_BUF_SIZE,
                         uart_error_handle,
                         APP_IRQ_PRIORITY_LOW,
                         err_code);

    APP_ERROR_CHECK(err_code);

  //  printf("\n\rStart: \n\r");
		for(int time_ctr = 0; time_ctr <100000; time_ctr ++);


 //   printf("INPUT_BUFFER_SIZE: %u\r\n", HEATSHRINK_STATIC_INPUT_BUFFER_SIZE);
	//		for(int time_ctr = 0; time_ctr <100000; time_ctr ++);
  //  printf("WINDOW_BITS: %u\r\n", HEATSHRINK_STATIC_WINDOW_BITS);
	//		for(int time_ctr = 0; time_ctr <100000; time_ctr ++);
  //  printf("LOOKAHEAD_BITS: %u\r\n", HEATSHRINK_STATIC_LOOKAHEAD_BITS);
	//	for(int time_ctr = 0; time_ctr <100000; time_ctr ++);
 //   printf("sizeof(heatshrink_encoder): %zd\r\n", sizeof(heatshrink_encoder));
	//	for(int time_ctr = 0; time_ctr <100000; time_ctr ++);
 //   printf("sizeof(heatshrink_decoder): %zd\r\n", sizeof(heatshrink_decoder));
	//	for(int time_ctr = 0; time_ctr <100000; time_ctr ++);
			
 //   for (uint32_t size=4; size < 2048; size <<= 1) {
      pseudorandom_data_should_match(256);
//    }
//		printf("done\r\n");
    while(1);
		
    while (true)
    {
        uint8_t cr;
   //     while(app_uart_get(&cr) != NRF_SUCCESS);

        //uint8_t input[COMPRESSION_BUF_SIZE];
    	//fill_with_patient_data(input,size);
				
        while(app_uart_put(cr) != NRF_SUCCESS);

        if (cr == 'q' || cr == 'Q')
        {
            printf(" \n\rExit!\n\r");

            while (true)
            {
                // Do nothing.
            }
        }
    }
}
Exemple #2
0
uint32_t bsp_init(uint32_t type, uint32_t ticks_per_100ms, bsp_event_callback_t callback)
{
    uint32_t err_code = NRF_SUCCESS;

#if LEDS_NUMBER > 0 && !(defined BSP_SIMPLE)
    m_app_ticks_per_100ms = ticks_per_100ms;
    m_indication_type     = type;
#else
    UNUSED_VARIABLE(ticks_per_100ms);
#endif // LEDS_NUMBER > 0 && !(defined BSP_SIMPLE)

#if (BUTTONS_NUMBER > 0) && !(defined BSP_SIMPLE)
    m_registered_callback = callback;

    // BSP will support buttons and generate events
    if (type & BSP_INIT_BUTTONS)
    {
        uint32_t num;

        for (num = 0; ((num < BUTTONS_NUMBER) && (err_code == NRF_SUCCESS)); num++)
        {
            err_code = bsp_event_to_button_action_assign(num, BSP_BUTTON_ACTION_PUSH, BSP_EVENT_DEFAULT);
        }

        if (err_code == NRF_SUCCESS)
        {
            err_code = app_button_init((app_button_cfg_t *)app_buttons,
                                       BUTTONS_NUMBER,
                                       ticks_per_100ms / 2);
        }

        if (err_code == NRF_SUCCESS)
        {
            err_code = app_button_enable();
        }

        if (err_code == NRF_SUCCESS)
        {
            err_code = app_timer_create(&m_button_timer_id,
                                        APP_TIMER_MODE_SINGLE_SHOT,
                                        button_timer_handler);
        }
    }
#elif (BUTTONS_NUMBER > 0) && (defined BSP_SIMPLE)

    if (type & BSP_INIT_BUTTONS)
    {
        uint32_t cnt;
        uint32_t buttons[] = BUTTONS_LIST;

        for (cnt = 0; cnt < BUTTONS_NUMBER; cnt++)
        {
            nrf_gpio_cfg_input(buttons[cnt], BUTTON_PULL);
        }
    }
#endif // (BUTTONS_NUMBER > 0) && !(defined BSP_SIMPLE)

#if LEDS_NUMBER > 0 && !(defined BSP_SIMPLE)

    if (type & BSP_INIT_LED)
    {
        LEDS_OFF(LEDS_MASK);
        NRF_GPIO->DIRSET = LEDS_MASK;
    }

    // timers module must be already initialized!
    if (err_code == NRF_SUCCESS)
    {
        err_code =
            app_timer_create(&m_leds_timer_id, APP_TIMER_MODE_SINGLE_SHOT, leds_timer_handler);
    }

    if (err_code == NRF_SUCCESS)
    {
        err_code =
            app_timer_create(&m_alert_timer_id, APP_TIMER_MODE_REPEATED, alert_timer_handler);
    }
#endif // LEDS_NUMBER > 0 && !(defined BSP_SIMPLE)

    return err_code;
}
Exemple #3
0
/**
 * The main function.
 */
int main( void )
{
    uint8_t i;
    uint8_t length;

    /* Stop the watchdog timer. */
    WDTCTL = WDTPW + WDTHOLD;

    /* Setup MCLK 8MHz and SMCLK 1MHz */
    set_mcu_speed_xt2_mclk_8MHz_smclk_1MHz();

    /* Enable Interrupts */
    eint();

    LEDS_INIT();
    LEDS_ON();

    uart0_init(UART0_CONFIG_1MHZ_115200);
    printf("CC2420 RX test program with address recognition and acknowledge frames\r\n");

    cc2420_init();
    cc2420_io_sfd_register_cb(sfd_cb);
    cc2420_io_sfd_int_set_falling();
    cc2420_io_sfd_int_clear();
    cc2420_io_sfd_int_enable();

    uint8_t src_pan_id[2] = {0x22,0x00};
    uint8_t src_addr[2] = {0x11,0x11};

    while ( (cc2420_get_status() & 0x40) == 0 ); // waiting for xosc being stable

    cc2420_set_panid(src_pan_id); // save pan id in ram
    cc2420_set_shortadr(src_addr); // save short address in ram

    printf("CC2420 initialized\r\n");

    LEDS_OFF();

    while(1)
    {
        cc2420_cmd_idle();
        cc2420_cmd_flushrx();
        cc2420_cmd_rx();

        while (flag == 0) ;
        micro_delay(0xFFFF);
        flag = 0;
	LED_GREEN_TOGGLE();
        cc2420_fifo_get(&length, 1);
        if ( length < 128 )
        {
            cc2420_fifo_get(rxframe, length);
            // check CRC
            if ( (rxframe[length-1] & 0x80) != 0 )
            {
                printf("Frame received with rssi=%ddBm:\r\n", ((signed int)((signed char)(rxframe[length-2])))-45);
                LED_BLUE_TOGGLE();
		// ignore 11 first bytes (fcf,seq,addr) and the 2 last ones (crc)
                for (i=11; i<length-2; i++)
                {
                    printf("%c",rxframe[i]);
                }
                printf("\r\n\n");
            }
	    else {
		printf("CRC non OK, erreur de transmission?\n");
                printf("\r\n");
                LED_RED_TOGGLE();
	    }
        }
    }

    return 0;
}
Exemple #4
0
static void handle_led_request(uint32_t led_mask, coap_message_t * p_request, coap_resource_t * p_resource)
{
    coap_message_conf_t response_config;
    memset (&response_config, 0, sizeof(coap_message_conf_t));

    if (p_request->header.type == COAP_TYPE_NON)
    {
        response_config.type = COAP_TYPE_NON;
    }
    else if (p_request->header.type == COAP_TYPE_CON)
    {
        response_config.type = COAP_TYPE_ACK;
    }
    
    // PIGGY BACKED RESPONSE
    response_config.code = COAP_CODE_405_METHOD_NOT_ALLOWED;
    // Copy message ID.
    response_config.id = p_request->header.id;
   
    // Copy token.
    memcpy(&response_config.token[0], &p_request->token[0], p_request->header.token_len);
    // Copy token length.
    response_config.token_len = p_request->header.token_len;
    
    coap_message_t * p_response;
    uint32_t err_code = coap_message_new(&p_response, &response_config);
    APP_ERROR_CHECK(err_code);
    
    err_code = coap_message_remote_addr_set(p_response, &p_request->remote);
    APP_ERROR_CHECK(err_code);
        
    // Handle request.
    switch (p_request->header.code)
    {
        case COAP_CODE_GET:
        {
            p_response->header.code = COAP_CODE_205_CONTENT;
            
            // Select the first common content-type between the resource and the CoAP client.
            coap_content_type_t ct_to_use;
            err_code = coap_message_ct_match_select(&ct_to_use, p_request, p_resource);
            if (err_code != NRF_SUCCESS)
            {
                // None of the accept content formats are supported in this resource endpoint.
                p_response->header.code = COAP_CODE_415_UNSUPPORTED_CONTENT_FORMAT;
                p_response->header.type = COAP_TYPE_RST;
            }
            else
            {   
                // Set response payload to actual LED state.
                char * response_str;
                led_value_get(led_mask, ct_to_use, &response_str);
                err_code = coap_message_payload_set(p_response, response_str, strlen(response_str));
                APP_ERROR_CHECK(err_code);
            }
            break;
        }
        
        case COAP_CODE_PUT:
        {
            p_response->header.code = COAP_CODE_204_CHANGED;

            // Change LED state according to request. 
            switch (p_request->p_payload[0])
            {
                case COMMAND_ON:
                {
                    LEDS_ON(led_mask);
                    break;
                }
                case COMMAND_OFF:
                {
                    LEDS_OFF(led_mask);
                    break;
                }
                case COMMAND_TOGGLE:
                {
                    LEDS_INVERT(led_mask);
                    break;
                }
                default:
                {
                    p_response->header.code = COAP_CODE_400_BAD_REQUEST;
                    break;
                }
            }
            break;
        }
        
        default:
        {
            p_response->header.code = COAP_CODE_405_METHOD_NOT_ALLOWED;
            break;
        }
    }
    
    uint32_t msg_handle;
    err_code = coap_message_send(&msg_handle, p_response);
    APP_ERROR_CHECK(err_code);
    
    err_code = coap_message_delete(p_response);
    APP_ERROR_CHECK(err_code);
}
Exemple #5
0
/**@brief Timer callback used for controlling board LEDs to represent application state.
 *
 */
static void blink_timeout_handler(iot_timer_time_in_ms_t wall_clock_value)
{
    UNUSED_PARAMETER(wall_clock_value);

#ifdef COMMISSIONING_ENABLED
    static bool id_mode_previously_enabled;

    if (m_identity_mode_active == false)
    {
#endif // COMMISSIONING_ENABLED
    switch (m_disp_state)
    {
        case LEDS_INACTIVE:
        {
            LEDS_OFF((LED_ONE | LED_TWO));
            LEDS_OFF((LED_THREE | LED_FOUR));
            break;
        }
        case LEDS_CONNECTABLE_MODE:
        {
            LEDS_INVERT(LED_ONE);
            LEDS_OFF(LED_TWO);
            LEDS_OFF((LED_THREE | LED_FOUR));
            break;
        }
        case LEDS_IPV6_IF_DOWN:
        {
            LEDS_ON(LED_ONE);
            LEDS_INVERT(LED_TWO);
            LEDS_OFF((LED_THREE | LED_FOUR));
            break;
        }
        case LEDS_IPV6_IF_UP:
        {
            LEDS_OFF(LED_ONE);
            LEDS_ON(LED_TWO);

            // If m_blink_led_three is set, keep LED_THREE on for 1 period.
            if LED_IS_ON(LED_THREE)
            {
                LEDS_OFF(LED_THREE);
            }
            else if (m_blink_led_three == true)
            {
                LEDS_ON(LED_THREE);
                m_blink_led_three = false;
            }

            // If m_blink_led_four is set, keep LED_FOUR on for 1 period.
            if LED_IS_ON(LED_FOUR)
            {
                LEDS_OFF(LED_FOUR);
            }
            else if (m_blink_led_four == true)
            {
                LEDS_ON(LED_FOUR);
                m_blink_led_four = false;
            }
            break;
        }
        default:
        {
            break;
        }
    }
Exemple #6
0
/**@brief Process ANT message on ANT mobile interface channel
 * 
 * @details   This function handles all events on the mobile interface channel.
 *            On EVENT_TX an ANT_MOBILE_MAIN_PAGE message is queue. The format is:
 *            byte[0]   = page (1 = ANT_MOBILE_MAIN_PAGE)
 *            byte[1]   = led state (1 = 0N, 0 = OFF)
 *            byte[2-6] = reserved (0xFF)
 *            byte[7]   = relay slave channel status (0 = unnassigned, 1 = assigned, 2 = searching, 3 = tracking)
 *
 *            On EVENT_RX the function will decode an ANT_MOBILE_COMMAND_PAGE. The format is:
 *            byte[0]   = page (2 = ANT_MOBILE_COMMAND_PAGE)
 *            byte[1]   = reserved (Set to 0xFF)
 *            byte[2]   = command (1 = pairing, 2 = led on, 3 = led off)
 *            byte[3-7] = reserved (Set to 0xFF)
 *
 * @param[in] p_ant_event ANT message content.
 */
void ant_process_mobile(ant_evt_t* p_ant_event)
{
    ANT_MESSAGE* p_ant_message = (ANT_MESSAGE*)p_ant_event->evt_buffer;
    switch(p_ant_event->event)
    {
        case EVENT_RX:
        {
            switch(p_ant_message->ANT_MESSAGE_aucPayload[0])
            {
                case ANT_MOBILE_COMMAND_PAGE:
                {
                    switch(p_ant_message->ANT_MESSAGE_aucPayload[2])
                    {
                        case ANT_COMMAND_ON:
                        {
                            LEDS_ON(BSP_LED_0_MASK);
                            m_led_change_counter++;
                            break;
                        }
                        case ANT_COMMAND_OFF:
                        {
                            LEDS_OFF(BSP_LED_0_MASK);
                            m_led_change_counter++;
                            break;
                        }
                        case ANT_COMMAND_PAIRING:
                        {
                            uint8_t channel_status;
                            uint32_t err_code = sd_ant_channel_status_get (ANT_RELAY_SLAVE_CHANNEL, &channel_status);
                            APP_ERROR_CHECK(err_code);

                            if((channel_status & STATUS_CHANNEL_STATE_MASK) == STATUS_ASSIGNED_CHANNEL)
                            {
                                err_code = sd_ant_channel_open(ANT_RELAY_SLAVE_CHANNEL);
                                APP_ERROR_CHECK(err_code);
                            }
                            break;
                        }
                    }

                    break;
                }
                default:
                {
                    break;
                }
            }
            break;
        }
        case EVENT_TX:
        {
            uint8_t status;

            uint32_t err_code = sd_ant_channel_status_get(ANT_RELAY_SLAVE_CHANNEL, &status);
            APP_ERROR_CHECK(err_code);

            m_broadcast_data[0] = ANT_MOBILE_MAIN_PAGE;
            m_broadcast_data[1] = ( LED_IS_ON(BSP_LED_0_MASK) )? 1 : 0;
            m_broadcast_data[2] = 0xFF;
            m_broadcast_data[3] = 0xFF;
            m_broadcast_data[4] = 0xFF;
            m_broadcast_data[5] = 0xFF;
            m_broadcast_data[6] = 0xFF;
            m_broadcast_data[7] = status & STATUS_CHANNEL_STATE_MASK;
            err_code = sd_ant_broadcast_message_tx(ANT_MOBILE_CHANNEL, ANT_STANDARD_DATA_PAYLOAD_SIZE, m_broadcast_data);
            APP_ERROR_CHECK(err_code);

            break;
        }
        default:
        {
            break;
        }
    }
}
Exemple #7
0
/**@brief Timer callback used for controlling board LEDs to represent application state.
 *
 * @param[in]   p_context   Pointer used for passing context. No context used in this application.
 */
static void blink_timeout_handler(iot_timer_time_in_ms_t wall_clock_value)
{
    UNUSED_PARAMETER(wall_clock_value);

#ifdef COMMISSIONING_ENABLED
    static bool id_mode_previously_enabled;

    if (m_identity_mode_active == false)
    {
#endif // COMMISSIONING_ENABLED
    switch (m_display_state)
    {
        case LEDS_INACTIVE:
        {
            LEDS_OFF((LED_ONE | LED_TWO));
            break;
        }

        case LEDS_CONNECTABLE_MODE:
        {
            LEDS_INVERT(LED_ONE);
            LEDS_OFF(LED_TWO);
            break;
        }

        case LEDS_IPV6_IF_DOWN:
        {
            LEDS_OFF((LED_THREE | LED_FOUR));
            LEDS_ON(LED_ONE);
            LEDS_INVERT(LED_TWO);
            break;
        }

        case LEDS_IPV6_IF_UP:
        {
            LEDS_OFF(LED_ONE);
            LEDS_ON(LED_TWO);
            break;
        }

        default:
        {
            break;
        }
    }
#ifdef COMMISSIONING_ENABLED
    }
#endif // COMMISSIONING_ENABLED

#ifdef COMMISSIONING_ENABLED
    if ((id_mode_previously_enabled == false) && (m_identity_mode_active == true))
    {
        LEDS_OFF(LED_THREE | LED_FOUR);
    }

    if ((id_mode_previously_enabled == true) && (m_identity_mode_active == true))
    {
        LEDS_INVERT(LED_THREE | LED_FOUR);
    }

    if ((id_mode_previously_enabled == true) && (m_identity_mode_active == false))
    {
        LEDS_OFF(LED_THREE | LED_FOUR);
    }

    id_mode_previously_enabled = m_identity_mode_active;
#endif // COMMISSIONING_ENABLED
}
Exemple #8
0
/**
 * @brief Assert callback.
 */
void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name)
{
    LEDS_OFF(LEDS_MASK);
    while(1);
}
Exemple #9
0
/**@brief Function for handling BLE Stack events concerning central applications.
 *
 * @details This function keeps the connection handles of central applications up-to-date. It
 * parses scanning reports, initiating a connection attempt to peripherals when a target UUID
 * is found, and manages connection parameter update requests. Additionally, it updates the status
 * of LEDs used to report central applications activity.
 *
 * @note        Since this function updates connection handles, @ref BLE_GAP_EVT_DISCONNECTED events
 *              should be dispatched to the target application before invoking this function.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 */
static void on_ble_central_evt(const ble_evt_t * const p_ble_evt)
{
    // The addresses of peers we attempted to connect to.
    static ble_gap_addr_t periph_addr_hrs;
    static ble_gap_addr_t periph_addr_rsc;

    // For readability.
    const ble_gap_evt_t   * const p_gap_evt = &p_ble_evt->evt.gap_evt;

    switch (p_ble_evt->header.evt_id)
    {
        /** Upon connection, check which peripheral has connected (HR or RSC), initiate DB
         *  discovery, update LEDs status and resume scanning if necessary. */
        case BLE_GAP_EVT_CONNECTED:
        {
            uint32_t err_code;

            // For readability.
            const ble_gap_addr_t * const peer_addr = &p_gap_evt->params.connected.peer_addr;

            /** Check which peer has connected, save the connection handle and initiate DB discovery.
             *  DB discovery will invoke a callback (hrs_c_evt_handler and rscs_c_evt_handler)
             *  upon completion, which is used to enable notifications from the peer. */
            if(memcmp(&periph_addr_hrs, peer_addr, sizeof(ble_gap_addr_t)) == 0)
            {
                NRF_LOG_PRINTF("HRS central connected\r\n");
                // Reset the peer address we had saved.
                memset(&periph_addr_hrs, 0, sizeof(ble_gap_addr_t));

                m_conn_handle_hrs_c = p_gap_evt->conn_handle;

                NRF_LOG_PRINTF("Starting DB discovery for HRS\r\n");
                err_code = ble_db_discovery_start(&m_ble_db_discovery_hrs, p_gap_evt->conn_handle);
                APP_ERROR_CHECK(err_code);
            }
            else if(memcmp(&periph_addr_rsc, peer_addr, sizeof(ble_gap_addr_t)) == 0)
            {
                NRF_LOG_PRINTF("RSC central connected\r\n");
                // Reset the peer address we had saved.
                memset(&periph_addr_rsc, 0, sizeof(ble_gap_addr_t));

                m_conn_handle_rscs_c = p_gap_evt->conn_handle;

                NRF_LOG_PRINTF("Starting DB discovery for RSCS\r\n");
                err_code = ble_db_discovery_start(&m_ble_db_discovery_rsc, p_gap_evt->conn_handle);
                APP_ERROR_CHECK(err_code);
            }

            /** Update LEDs status, and check if we should be looking for more
             *  peripherals to connect to. */
            LEDS_ON(CENTRAL_CONNECTED_LED);
            if (ble_conn_state_n_centrals() == MAX_CONNECTED_CENTRALS)
            {
                LEDS_OFF(CENTRAL_SCANNING_LED);
            }
            else
            {
                // Resume scanning.
                LEDS_ON(CENTRAL_SCANNING_LED);
                scan_start();
            }
        } break; // BLE_GAP_EVT_CONNECTED

        /** Upon disconnection, reset the connection handle of the peer which disconnected, update
         * the LEDs status and start scanning again. */
        case BLE_GAP_EVT_DISCONNECTED:
        {
            uint8_t n_centrals;

            if (p_gap_evt->conn_handle == m_conn_handle_hrs_c)
            {
                NRF_LOG_PRINTF("HRS central disconnected (reason: %d)\r\n",
                       p_gap_evt->params.disconnected.reason);

                m_conn_handle_hrs_c = BLE_CONN_HANDLE_INVALID;
            }
            else if(p_gap_evt->conn_handle == m_conn_handle_rscs_c)
            {
                NRF_LOG_PRINTF("RSC central disconnected (reason: %d)\r\n",
                       p_gap_evt->params.disconnected.reason);

                m_conn_handle_rscs_c = BLE_CONN_HANDLE_INVALID;
            }

            // Start scanning
            // scan_start();

            // Update LEDs status.
            LEDS_ON(CENTRAL_SCANNING_LED);
            n_centrals = ble_conn_state_n_centrals();
            if (n_centrals == 0)
            {
                LEDS_OFF(CENTRAL_CONNECTED_LED);
            }
        } break; // BLE_GAP_EVT_DISCONNECTED

        case BLE_GAP_EVT_ADV_REPORT:
        {
            uint32_t err_code;
            data_t   adv_data;
            data_t   type_data;

            // For readibility.
            const ble_gap_addr_t  * const peer_addr = &p_gap_evt->params.adv_report.peer_addr;

            // Initialize advertisement report for parsing.
            adv_data.p_data     = (uint8_t *)p_gap_evt->params.adv_report.data;
            adv_data.data_len   = p_gap_evt->params.adv_report.dlen;

            err_code = adv_report_parse(BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE,
                                        &adv_data,
                                        &type_data);

            if (err_code != NRF_SUCCESS)
            {
                // Look for the services in 'complete' if it was not found in 'more available'.
                err_code = adv_report_parse(BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE,
                                            &adv_data,
                                            &type_data);

                if (err_code != NRF_SUCCESS)
                {
                    // If we can't parse the data, then exit.
                    break;
                }
            }

            // Verify if any UUID match the Heart rate or Running speed and cadence services.
            for (uint32_t u_index = 0; u_index < (type_data.data_len / UUID16_SIZE); u_index++)
            {
                bool        do_connect = false;
                uint16_t    extracted_uuid;

                UUID16_EXTRACT(&extracted_uuid, &type_data.p_data[u_index * UUID16_SIZE]);

                /** We do not want to connect to two peripherals offering the same service, so when
                 *  a UUID is matched, we check that we are not already connected to a peer which
                 *  offers the same service. We then save the peer address, so that upon connection
                 *  we can tell which peer has connected and update its respective connection
                 *  handle. */
                if ((extracted_uuid      == BLE_UUID_HEART_RATE_SERVICE) &&
                    (m_conn_handle_hrs_c == BLE_CONN_HANDLE_INVALID))
                {
                    do_connect = true;
                    memcpy(&periph_addr_hrs, peer_addr, sizeof(ble_gap_addr_t));
                }
                else if ((extracted_uuid       == BLE_UUID_RUNNING_SPEED_AND_CADENCE) &&
                         (m_conn_handle_rscs_c == BLE_CONN_HANDLE_INVALID))
                {
                    do_connect = true;
                    memcpy(&periph_addr_rsc, peer_addr, sizeof(ble_gap_addr_t));
                }

                if (do_connect)
                {
                    // Initiate connection.
                    err_code = sd_ble_gap_connect(peer_addr, &m_scan_param, &m_connection_param);
                    if (err_code != NRF_SUCCESS)
                    {
                        APPL_LOG("[APPL]: Connection Request Failed, reason %d\r\n", err_code);
                    }
                }
            }
        } break; // BLE_GAP_ADV_REPORT

        case BLE_GAP_EVT_TIMEOUT:
        {
            // We have not specified a timeout for scanning, so only connection attemps can timeout.
            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
            {
                APPL_LOG("[APPL]: Connection Request timed out.\r\n");
            }
        } break; // BLE_GAP_EVT_TIMEOUT

        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
        {
            // Accept parameters requested by peer.
            ret_code_t err_code;
            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                                        &p_gap_evt->params.conn_param_update_request.conn_params);
            APP_ERROR_CHECK(err_code);
        } break; // BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST

        default:
            // No implementation needed.
            break;
    }
}
Exemple #10
0
/*---------------------------------------------------------------------------*/
static int
send_packet(void)
{
  rtimer_clock_t t0;
  rtimer_clock_t t;
  int strobes;
  struct xmac_hdr *hdr;
  int got_ack = 0;
  struct xmac_hdr msg;
  int len;
  int is_broadcast = 0;

#if WITH_TIMETABLE
  TIMETABLE_TIMESTAMP(xmac_timetable, "send");
#endif
  
#if WITH_CHANNEL_CHECK
  /* Check if there are other strobes in the air. */
  waiting_for_packet = 1;
  on();
  t0 = RTIMER_NOW();
  while(RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + xmac_config.strobe_wait_time * 2)) {
    len = radio->read(&msg, sizeof(msg));
    if(len > 0) {
      someone_is_sending = 1;
    }
  }
  waiting_for_packet = 0;
  
  while(someone_is_sending); /* {printf("z");}*/

#if WITH_TIMETABLE
  TIMETABLE_TIMESTAMP(xmac_timetable, "send 2");
#endif /* WITH_TIMETABLE */
  
#endif /* WITH_CHANNEL_CHECK */
  
  /* By setting we_are_sending to one, we ensure that the rtimer
     powercycle interrupt do not interfere with us sending the packet. */
  we_are_sending = 1;

  off();

  
  rimebuf_hdralloc(sizeof(struct xmac_hdr));
  hdr = rimebuf_hdrptr();
  rimeaddr_copy(&hdr->sender, &rimeaddr_node_addr);
  rimeaddr_copy(&hdr->receiver, rimebuf_addr(RIMEBUF_ADDR_RECEIVER));
  if(rimeaddr_cmp(&hdr->receiver, &rimeaddr_null)) {
    is_broadcast = 1;
  }
  rimebuf_compact();

  t0 = RTIMER_NOW();
  strobes = 0;

  BB_SET(XMAC_RECEIVER, hdr->receiver.u16[0]);
  
  LEDS_ON(LEDS_BLUE);

  /* Send a train of strobes until the receiver answers with an ACK. */

  /* Turn on the radio to listen for the strobe ACK. */
  if(!is_broadcast) {
    on();
  }

  watchdog_stop();
  got_ack = 0;
  for(strobes = 0;
      got_ack == 0 &&
	RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + xmac_config.strobe_time);
      strobes++) {

    t = RTIMER_NOW();

    rimeaddr_copy(&msg.sender, &rimeaddr_node_addr);
    rimeaddr_copy(&msg.receiver, rimebuf_addr(RIMEBUF_ADDR_RECEIVER));

#if WITH_TIMETABLE
    if(rimeaddr_cmp(&msg.receiver, &rimeaddr_null)) {
      TIMETABLE_TIMESTAMP(xmac_timetable, "send broadcast strobe");
    } else {
      TIMETABLE_TIMESTAMP(xmac_timetable, "send strobe");
    }
#endif
    if(is_broadcast) {
      /* If we are sending a broadcast, we don't send strobes, we
	 simply send the data packet repetedly */
      radio->send(rimebuf_hdrptr(), rimebuf_totlen());
    } else {
      /* Send the strobe packet. */
      radio->send((const uint8_t *)&msg, sizeof(struct xmac_hdr));
    }
    CPRINTF("+");

    while(got_ack == 0 &&
	  RTIMER_CLOCK_LT(RTIMER_NOW(), t + xmac_config.strobe_wait_time)) {
      /* See if we got an ACK */
      len = radio->read((uint8_t *)&msg, sizeof(struct xmac_hdr));
      if(len > 0) {
	CPRINTF("_");
	if(rimeaddr_cmp(&msg.sender, &rimeaddr_node_addr) &&
	   rimeaddr_cmp(&msg.receiver, &rimeaddr_node_addr)) {
#if WITH_TIMETABLE
	  TIMETABLE_TIMESTAMP(xmac_timetable, "send ack received");
#endif
	  CPRINTF("@");
	  /* We got an ACK from the receiver, so we can immediately send
	     the packet. */
	  got_ack = 1;
	}
      }
    }

    /* XXX: turn off radio if we haven't heard an ACK within a
       specified time interval. */

    /*    if(got_ack == 0) {
      off();
      while(RTIMER_CLOCK_LT(RTIMER_NOW(), t + xmac_config.strobe_wait_time));
      on();
      }*/
  }

  if(got_ack /* XXX && needs_ack */) {
#if WITH_TIMETABLE
    TIMETABLE_TIMESTAMP(xmac_timetable, "send got ack");
#endif
    on(); /* Wait for possible ACK packet */
  } else if(!is_broadcast) {
#if WITH_TIMETABLE
    TIMETABLE_TIMESTAMP(xmac_timetable, "send no ack received");
#endif
    on(); /* shell ping don't seem to work with off() here, so we'll
	     keep it on() for a while. */
  }

  /* Send the data packet. */
  if(is_broadcast || got_ack) {
#if WITH_TIMETABLE
    TIMETABLE_TIMESTAMP(xmac_timetable, "send packet");
#endif
    radio->send(rimebuf_hdrptr(), rimebuf_totlen());
    CPRINTF("#");
  }
  watchdog_start();

  PRINTF("xmac: send (strobes=%u,len=%u,%s), done\n", strobes,
	 rimebuf_totlen(), got_ack ? "ack" : "no ack");

  BB_SET(XMAC_STROBES, strobes);
  if(got_ack) {
    BB_INC(XMAC_SEND_WITH_ACK, 1);
  } else {
    BB_INC(XMAC_SEND_WITH_NOACK, 1);
  }

  /*  printf("Strobe %d got_ack %d\n", strobes, got_ack);*/

  we_are_sending = 0;
#if WITH_TIMETABLE
  TIMETABLE_TIMESTAMP(xmac_timetable, "send we_are_sending = 0");
#endif
  LEDS_OFF(LEDS_BLUE);
  return 1;

}
Exemple #11
0
/**
 * @brief WDT events handler.
 */
void wdt_event_handler(void)
{
    LEDS_OFF(LEDS_MASK);
    
    //NOTE: The max amount of time we can spend in WDT interrupt is two cycles of 32768[Hz] clock - after that, reset occurs
}
Exemple #12
0
/**
 * The main function.
 */
int main( void )
{

    /* Stop the watchdog timer. */
    WDTCTL = WDTPW + WDTHOLD;

    /* Setup MCLK 8MHz and SMCLK 1MHz */
    set_mcu_speed_xt2_mclk_8MHz_smclk_1MHz();

    /* Enable Interrupts */
    eint();

    LEDS_INIT();
    LEDS_ON();

    uart0_init(UART0_CONFIG_1MHZ_115200);
    printf("CC2420 TX test program with address recognition and acknowledge frames\r\n");

    cc2420_init();
    cc2420_io_sfd_register_cb(sfd_cb);
    cc2420_io_sfd_int_set_falling();
    cc2420_io_sfd_int_clear();
    cc2420_io_sfd_int_enable();
    cc2420_set_txpower(CC2420_2_45GHz_TX_0dBm);

    uint8_t fcf[2] = {0x21, 0x88};  /* -> 00100001 10001000 -> reverse of bits for each byte -> 10000100 00010001 -> ack bit = 1 (6th bit), Frame type = 001 (don't forget to read from right to left) */
    uint8_t seq_numb = 0x01;
    uint8_t dest_pan_id[2] = {0x22, 0x00};
    uint8_t dest_addr[2] = {0x11, 0x11};

    uint8_t src_pan_id[2] = {0x22, 0x01};
    uint8_t src_addr[2] = {0x11, 0x12};

    while ( (cc2420_get_status() & 0x40) == 0 ); // waiting for xosc being stable

    cc2420_set_panid(src_pan_id); // save pan id in ram
    cc2420_set_shortadr(src_addr); // save short address in ram

    printf("CC2420 initialized\r\n");

    LEDS_OFF();

    while (1)
    {
        cc2420_cmd_idle();
        cc2420_cmd_flushtx();

        txlength = sprintf((char *)txframe, "Hello World #%i", seq_numb);

        printf("Sent : %s of length %d\r\n", txframe,txlength);

        txlength += 13;

        cc2420_fifo_put(&txlength, 1);
        cc2420_fifo_put(fcf, 2);
        cc2420_fifo_put(&seq_numb, 1);
        cc2420_fifo_put(dest_pan_id, 2);
        cc2420_fifo_put(dest_addr, 2);
        cc2420_fifo_put(src_pan_id, 2);
        cc2420_fifo_put(src_addr, 2);
        cc2420_fifo_put(txframe, txlength-13);

	LED_BLUE_TOGGLE();

        cc2420_cmd_tx();

        micro_delay(0xFFFF);
	while (cc2420_io_sfd_read());

	printf("Waiting for acknowledge frame...\n");

	if (rx_ack())
	{
            seq_numb ++;
	}
	else
	{
	    printf("No Acknowledge frame received for frame number #%i - Retrying...\r\n\n", seq_numb);
	    LED_RED_TOGGLE();
	}
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
        micro_delay(0xFFFF);
    }


    return 0;
}
void ant_message_types_master_setup(void)
{
    uint32_t err_code;

    ant_channel_config_t channel_config =
    {
        .channel_number     = ANT_CHANNEL_NUMBER,
        .channel_type       = CHANNEL_TYPE_MASTER,
        .ext_assign         = EXT_ASSIGN,
        .rf_freq            = RF_FREQUENCY,
        .transmission_type  = CHAN_ID_TRANS_TYPE,
        .device_type        = CHAN_ID_DEV_TYPE,
        .device_number      = (uint16_t) (NRF_FICR->DEVICEID[0]),
        .channel_period     = CHANNEL_PERIOD,
        .network_number     = ANT_CHANNEL_DEFAULT_NETWORK,
    };

    err_code = ant_channel_init(&channel_config);
    APP_ERROR_CHECK(err_code);

    //Set Tx Power
    err_code = sd_ant_channel_radio_tx_power_set(ANT_CHANNEL_NUMBER, RADIO_TX_POWER_LVL_3, ANT_CUSTOM_TRANSMIT_POWER);
    APP_ERROR_CHECK(err_code);

    // Open channel.
    err_code = sd_ant_channel_open(ANT_CHANNEL_NUMBER);
    APP_ERROR_CHECK(err_code);

    // Write counter value to last byte of the broadcast data.
    // The last byte is chosen to get the data more visible in the end of an printout
    // on the recieving end.
    memset(m_tx_buffer, 0, BROADCAST_DATA_BUFFER_SIZE);
    m_tx_buffer[BROADCAST_DATA_BUFFER_SIZE - 1] = m_counter;

    // Configure the initial payload of the broadcast data
    err_code = sd_ant_broadcast_message_tx(ANT_CHANNEL_NUMBER, BROADCAST_DATA_BUFFER_SIZE, m_tx_buffer);
    APP_ERROR_CHECK(err_code);

    //Set state to broadcasting
    state_message_types = BROADCAST;
}


void ant_message_types_master_bsp_evt_handler(bsp_event_t evt)
{
    switch (evt)
    {
        case BSP_EVENT_KEY_0:
            state_message_types = BROADCAST;
            break;

        case BSP_EVENT_KEY_1:
            state_message_types = ACKNOWLEDGED;
            break;

        case BSP_EVENT_KEY_2:
            state_message_types = BURST;
            break;

        default:
            break; // no implementation needed
    }
}


void ant_message_types_master_event_handler(ant_evt_t * p_ant_evt)
{
    uint32_t err_code;
    uint32_t led_output = LED_BROADCAST;

    switch (p_ant_evt->event)
    {
        // ANT broadcast/Acknowledged/Burst Success
        // Send the next message according to the current state and increment the counter.
        case EVENT_TX:                      // Intentional fall through
        case EVENT_TRANSFER_TX_COMPLETED:   // Intentional fall through
        case EVENT_TRANSFER_TX_FAILED:
            LEDS_OFF(LEDS_MASK);
            m_tx_buffer[BROADCAST_DATA_BUFFER_SIZE - 1] = m_counter;

            if(state_message_types == BROADCAST)
            {
                // Send as broadcast
                err_code = sd_ant_broadcast_message_tx(ANT_CHANNEL_NUMBER,
                                                       BROADCAST_DATA_BUFFER_SIZE,
                                                       m_tx_buffer);
                APP_ERROR_CHECK(err_code);

                led_output = LED_BROADCAST;
            }
            else if(state_message_types == ACKNOWLEDGED)
            {
                // Send as acknowledged
                err_code = sd_ant_acknowledge_message_tx(ANT_CHANNEL_NUMBER,
                                                         BROADCAST_DATA_BUFFER_SIZE,
                                                         m_tx_buffer);
                APP_ERROR_CHECK(err_code);

                led_output = LED_ACKNOWLEDGED;
            }
            else if(state_message_types == BURST)
            {
                // If this is a new message, populate the burst buffer
                // with new dummy data.  Otherwise, will retry sending the
                // same content.
                if(p_ant_evt->event != EVENT_TRANSFER_TX_FAILED)
                {
                    for(uint32_t i = 0; i < BURST_BLOCK_SIZE; i++)
                    {
                        m_burst_data[i] = m_counter;
                        m_counter++;
                    }
                }

                // Queue a Burst Transfer.  Since this is a small burst, queue entire burst.
                err_code = sd_ant_burst_handler_request(ANT_CHANNEL_NUMBER,
                                                        BURST_BLOCK_SIZE,
                                                        m_burst_data,
                                                        (BURST_SEGMENT_START | BURST_SEGMENT_END));
                APP_ERROR_CHECK(err_code);

                led_output = LED_BURST;
            }
            // Activate LED for 20ms
            LEDS_ON(led_output);
            nrf_delay_ms(20);
            LEDS_OFF(led_output);
            m_counter++;
            break;

        case TRANSFER_IN_PROGRESS:              //Intentional fall through
        case TRANSFER_SEQUENCE_NUMBER_ERROR:    //Intentional fall through
        case TRANSFER_IN_ERROR:                 //Intentional fall through
        case TRANSFER_BUSY:
            // Ignore these events; will retry burst transfer when we get the EVENT_TRANSFER_TX_FAILED event.
            break;

        default:
            break;

    }
}
/**@brief Function for handling BLE Stack events concerning central applications.
 *
 * @details This function keeps the connection handles of central applications up-to-date. It
 * parses scanning reports, initiating a connection attempt to peripherals when a target UUID
 * is found, and manages connection parameter update requests. Additionally, it updates the status
 * of LEDs used to report central applications activity.
 *
 * @note        Since this function updates connection handles, @ref BLE_GAP_EVT_DISCONNECTED events
 *              should be dispatched to the target application before invoking this function.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 */
static void on_ble_central_evt(const ble_evt_t * const p_ble_evt)
{
    const ble_gap_evt_t   * const p_gap_evt = &p_ble_evt->evt.gap_evt;

    switch (p_ble_evt->header.evt_id)
    {
        /** Upon connection, check which peripheral has connected (HR or RSC), initiate DB
         *  discovery, update LEDs status and resume scanning if necessary. */
        case BLE_GAP_EVT_CONNECTED:
        {
            uint32_t err_code;

            /** If no Heart Rate sensor or RSC sensor is currently connected, try to find them on this peripheral*/
            if ((m_conn_handle_hrs_c == BLE_CONN_HANDLE_INVALID)
                ||(m_conn_handle_rscs_c == BLE_CONN_HANDLE_INVALID))
            {
                NRF_LOG_PRINTF("try to find HRS or RSC on conn_handle 0x%x\r\n", p_gap_evt->conn_handle);

                APP_ERROR_CHECK_BOOL(p_gap_evt->conn_handle < CENTRAL_LINK_COUNT + PERIPHERAL_LINK_COUNT);
                err_code = ble_db_discovery_start(&m_ble_db_discovery[p_gap_evt->conn_handle], p_gap_evt->conn_handle);
                APP_ERROR_CHECK(err_code);
            }

            /** Update LEDs status, and check if we should be looking for more
             *  peripherals to connect to. */
            LEDS_ON(CENTRAL_CONNECTED_LED);
            if (ble_conn_state_n_centrals() == CENTRAL_LINK_COUNT)
            {
                LEDS_OFF(CENTRAL_SCANNING_LED);
            }
            else
            {
                // Resume scanning.
                LEDS_ON(CENTRAL_SCANNING_LED);
                scan_start();
            }
        } break; // BLE_GAP_EVT_CONNECTED

        /** Upon disconnection, reset the connection handle of the peer which disconnected, update
         * the LEDs status and start scanning again. */
        case BLE_GAP_EVT_DISCONNECTED:
        {
            uint8_t n_centrals;

            if (p_gap_evt->conn_handle == m_conn_handle_hrs_c)
            {
                NRF_LOG_PRINTF("HRS central disconnected (reason: %d)\r\n",
                       p_gap_evt->params.disconnected.reason);

                m_conn_handle_hrs_c = BLE_CONN_HANDLE_INVALID;
            }
            if(p_gap_evt->conn_handle == m_conn_handle_rscs_c)
            {
                NRF_LOG_PRINTF("RSC central disconnected (reason: %d)\r\n",
                       p_gap_evt->params.disconnected.reason);

                m_conn_handle_rscs_c = BLE_CONN_HANDLE_INVALID;
            }

            if ((m_conn_handle_rscs_c == BLE_CONN_HANDLE_INVALID)||
                (m_conn_handle_hrs_c == BLE_CONN_HANDLE_INVALID))
            {
                // Start scanning
                scan_start();

                // Update LEDs status.
                LEDS_ON(CENTRAL_SCANNING_LED);
            }
            n_centrals = ble_conn_state_n_centrals();

            if (n_centrals == 0)
            {
                LEDS_OFF(CENTRAL_CONNECTED_LED);
            }
        } break; // BLE_GAP_EVT_DISCONNECTED

        case BLE_GAP_EVT_ADV_REPORT:
        {
            uint32_t err_code;

            if (strlen(m_target_periph_name) != 0)
            {
                if (find_adv_name(&p_gap_evt->params.adv_report, m_target_periph_name))
                {
                    // Initiate connection.
                    err_code = sd_ble_gap_connect(&p_gap_evt->params.adv_report.peer_addr,
                                                  &m_scan_param,
                                                  &m_connection_param);
                    if (err_code != NRF_SUCCESS)
                    {
                        APPL_LOG("[APPL]: Connection Request Failed, reason %d\r\n", err_code);
                    }
                }
            }
            else
            {
               /** We do not want to connect to two peripherals offering the same service, so when
                *  a UUID is matched, we check that we are not already connected to a peer which
                *  offers the same service. */
                if ((find_adv_uuid(&p_gap_evt->params.adv_report, BLE_UUID_HEART_RATE_SERVICE)&&
                     (m_conn_handle_hrs_c == BLE_CONN_HANDLE_INVALID))||
                     (find_adv_uuid(&p_gap_evt->params.adv_report, BLE_UUID_RUNNING_SPEED_AND_CADENCE)&&
                     (m_conn_handle_rscs_c == BLE_CONN_HANDLE_INVALID)))
                {
                    // Initiate connection.
                    err_code = sd_ble_gap_connect(&p_gap_evt->params.adv_report.peer_addr,
                                                  &m_scan_param,
                                                  &m_connection_param);
                    if (err_code != NRF_SUCCESS)
                    {
                        APPL_LOG("[APPL]: Connection Request Failed, reason %d\r\n", err_code);
                    }
                }
            }
        } break; // BLE_GAP_ADV_REPORT

        case BLE_GAP_EVT_TIMEOUT:
        {
            // We have not specified a timeout for scanning, so only connection attemps can timeout.
            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
            {
                APPL_LOG("[APPL]: Connection Request timed out.\r\n");
            }
        } break; // BLE_GAP_EVT_TIMEOUT

        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
        {
            // Accept parameters requested by peer.
            ret_code_t err_code;
            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                                        &p_gap_evt->params.conn_param_update_request.conn_params);
            APP_ERROR_CHECK(err_code);
        } break; // BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST

        default:
            // No implementation needed.
            break;
    }
}
Exemple #15
0
/**
 * Indicate device detection in proximity.
 * Show 2 blinks.
 */
void indicate_proximity() {
	if (DISABLE_INDICATION) return;
	LEDS_ON(LEDS_MASK);
	nrf_delay_ms(DELAY_MS);
	LEDS_OFF(LEDS_MASK);
}
void SHORT_OFF()  { LEDS_OFF(); WAIT( 800111); }
static char
powercycle(struct rtimer *t, void *ptr)
{
  PT_BEGIN(&pt);

  while(1) {
    static uint8_t packet_seen;
    static rtimer_clock_t t0;
    static uint8_t count;

    cycle_start = RTIMER_NOW();

    if(WITH_STREAMING && is_streaming) {
#if NURTIMER
      if(!RTIMER_CLOCK_LT(cycle_start, RTIMER_NOW(), stream_until))
#else
        if(!RTIMER_CLOCK_LT(RTIMER_NOW(), stream_until))
#endif
          {
            is_streaming = 0;
            rimeaddr_copy(&is_streaming_to, &rimeaddr_null);
            rimeaddr_copy(&is_streaming_to_too, &rimeaddr_null);
          }
    }

    packet_seen = 0;

    do {
      for(count = 0; count < CCA_COUNT_MAX; ++count) {
        t0 = RTIMER_NOW();
        if(we_are_sending == 0) {
          powercycle_turn_radio_on();
#if 0
#if NURTIMER
          while(RTIMER_CLOCK_LT(t0, RTIMER_NOW(), t0 + CCA_CHECK_TIME));
#else
          while(RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + CCA_CHECK_TIME));
#endif
#endif /* 0 */
          /* Check if a packet is seen in the air. If so, we keep the
             radio on for a while (LISTEN_TIME_AFTER_PACKET_DETECTED) to
             be able to receive the packet. We also continuously check
             the radio medium to make sure that we wasn't woken up by a
             false positive: a spurious radio interference that was not
             caused by an incoming packet. */
          if(NETSTACK_RADIO.channel_clear() == 0) {
            packet_seen = 1;
            break;
          }
          powercycle_turn_radio_off();
        }
        schedule_powercycle_fixed(t, RTIMER_NOW() + CCA_SLEEP_TIME);
        /*        COOJA_DEBUG_STR("yield\n");*/
        PT_YIELD(&pt);
      }
      
      if(packet_seen) {
        static rtimer_clock_t start;
        static uint8_t silence_periods, periods;
        start = RTIMER_NOW();
        
        periods = silence_periods = 0;
        while(we_are_sending == 0 && radio_is_on &&
              RTIMER_CLOCK_LT(RTIMER_NOW(), (start + LISTEN_TIME_AFTER_PACKET_DETECTED))) {
          
          /* Check for a number of consecutive periods of
             non-activity. If we see two such periods, we turn the
             radio off. Also, if a packet has been successfully
             received (as indicated by the
             NETSTACK_RADIO.pending_packet() function), we stop
             snooping. */
          if(NETSTACK_RADIO.channel_clear()) {
            ++silence_periods;
          } else {
            silence_periods = 0;
          }
          
          ++periods;
        
          if(NETSTACK_RADIO.receiving_packet()) {
            silence_periods = 0;
          }
          if(silence_periods > MAX_SILENCE_PERIODS) {
            LEDS_ON(LEDS_RED);
            powercycle_turn_radio_off();
#if CONTIKIMAC_CONF_COMPOWER
            compower_accumulate(&compower_idle_activity);
#endif /* CONTIKIMAC_CONF_COMPOWER */
            LEDS_OFF(LEDS_RED);
            break;
          }
#if 1
          if(periods > MAX_NONACTIVITY_PERIODIC && !(NETSTACK_RADIO.receiving_packet() ||
                                                     NETSTACK_RADIO.pending_packet())) {
            LEDS_ON(LEDS_GREEN);
            powercycle_turn_radio_off();
#if CONTIKIMAC_CONF_COMPOWER
            compower_accumulate(&compower_idle_activity);
#endif /* CONTIKIMAC_CONF_COMPOWER */
            
            LEDS_OFF(LEDS_GREEN);
            break;
          }
#endif /* 0 */
          if(NETSTACK_RADIO.pending_packet()) {
            break;
          }
          
          schedule_powercycle(t, CCA_CHECK_TIME + CCA_SLEEP_TIME);
          LEDS_ON(LEDS_BLUE);
          PT_YIELD(&pt);
          LEDS_OFF(LEDS_BLUE);
        }
        if(radio_is_on && !(NETSTACK_RADIO.receiving_packet() ||
                            NETSTACK_RADIO.pending_packet())) {
          LEDS_ON(LEDS_RED + LEDS_GREEN);
          powercycle_turn_radio_off();
#if CONTIKIMAC_CONF_COMPOWER
          compower_accumulate(&compower_idle_activity);
#endif /* CONTIKIMAC_CONF_COMPOWER */
          LEDS_OFF(LEDS_RED + LEDS_GREEN);
        }
      } else {
#if CONTIKIMAC_CONF_COMPOWER
        compower_accumulate(&compower_idle_activity);
#endif /* CONTIKIMAC_CONF_COMPOWER */
      }
    } while(is_snooping &&
            RTIMER_CLOCK_LT(RTIMER_NOW() - cycle_start, CYCLE_TIME - CHECK_TIME));

    if(is_snooping) {
      LEDS_ON(LEDS_RED);
    }
    if(RTIMER_CLOCK_LT(RTIMER_NOW() - cycle_start, CYCLE_TIME)) {
      /*      schedule_powercycle(t, CYCLE_TIME - (RTIMER_NOW() - cycle_start));*/
      schedule_powercycle_fixed(t, CYCLE_TIME + cycle_start);
      /*      printf("cycle_start 0x%02x now 0x%02x wait 0x%02x\n",
              cycle_start, RTIMER_NOW(), CYCLE_TIME - (RTIMER_NOW() - cycle_start));*/
      PT_YIELD(&pt);
    }
    LEDS_OFF(LEDS_RED);
  }

  PT_END(&pt);
}
void MEDIUM_OFF() { LEDS_OFF(); WAIT(3000111); }
Exemple #19
0
/**@brief Function for application main entry. Does not return.
 */
int main(void)
{
    // ANT event message buffer.
    static ant_evt_t ant_event;

    // Configure LEDs as outputs.
    nrf_gpio_range_cfg_output(BSP_LED_0, BSP_LED_1);

    // Set LED_0 and LED_1 high to indicate that the application is running.
    LEDS_ON(BSP_LED_0_MASK);
    LEDS_ON(BSP_LED_1_MASK);

    // Enable SoftDevice.
    uint32_t err_code;
    err_code = sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_XTAL_50_PPM, softdevice_assert_callback);
    APP_ERROR_CHECK(err_code);

    // Set application IRQ to lowest priority.
    err_code = sd_nvic_SetPriority(SD_EVT_IRQn, NRF_APP_PRIORITY_LOW);
    APP_ERROR_CHECK(err_code);

    // Enable application IRQ (triggered from protocol).
    err_code = sd_nvic_EnableIRQ(SD_EVT_IRQn);
    APP_ERROR_CHECK(err_code);

    err_code = ant_stack_static_config();
    APP_ERROR_CHECK(err_code);

    // Setup Channel_0 as a TX Master Only.
    ant_channel_setup();

    // Set LED_0 and LED_1 low to indicate that stack is enabled.
    LEDS_OFF(BSP_LED_0_MASK);
    LEDS_OFF(BSP_LED_1_MASK);
    
    button_init();

    // Main loop.
    for (;;)
    {
        // Put CPU in sleep if possible.
        err_code = sd_app_evt_wait();
        APP_ERROR_CHECK(err_code);

        // Extract and process all pending ANT events as long as there are any left.
        do
        {
            // Fetch the event.
            err_code = sd_ant_event_get(&ant_event.channel, &ant_event.event, ant_event.evt_buffer);
            if (err_code == NRF_SUCCESS)
            {
                switch(ant_event.channel)
                {
                    case ANT_RELAY_MASTER_CHANNEL:
                    {
                        ant_process_relay_master(&ant_event);
                        break;
                    }
                    case ANT_RELAY_SLAVE_CHANNEL:
                    {
                        ant_process_relay_slave(&ant_event);
                        break;
                    }
                    case ANT_MOBILE_CHANNEL:
                    {
                        ant_process_mobile(&ant_event);
                        break;
                    }
                    default:
                    {
                        break;
                    }
                }
            }
        }
        while (err_code == NRF_SUCCESS);
    }
}
void LONG_OFF()   { LEDS_OFF(); WAIT(6000111); }
Exemple #21
0
/**@brief Application state machine used for sending DNS Query and Echo Request.
 *
 * @param[in]   p_context   Pointer used for passing context. No context used in this application.
 */
static void app_fsm(void * p_context)
{
    uint32_t                   err_code;
    iot_pbuffer_t            * p_buffer;
    iot_pbuffer_alloc_param_t  pbuff_param;
    ipv6_addr_t                src_addr;

    switch(m_app_state)
    {
      case APP_STATE_QUERYING:
          APPL_LOG("[APPL]: Application in querying state.\r\n");
          // Set number of retransmission to 0.
          m_echo_req_retry_count = 0;

          // Turn off LED_THREE and LED_FOUR
          LEDS_OFF((LED_THREE | LED_FOUR));

          // Find all IPv6 address corresponds to APP_HOSTNAME domain.
          err_code = dns6_query(APP_HOSTNAME, app_dns_handler);
          APP_ERROR_CHECK(err_code);

          // Change state to resolving.
          m_app_state = APP_STATE_RESOLVING;
        break;
      case APP_STATE_RESOLVING:
          APPL_LOG("[APPL]: Application in resolving state.\r\n");
          // Wait for DNS response.
          break;
      case APP_STATE_PINGING:
          APPL_LOG("[APPL]: Application in pinging state.\r\n");

          if(m_echo_req_retry_count < APP_MAX_ECHO_REQUEST_RTR)
          {
              pbuff_param.flags  = PBUFFER_FLAG_DEFAULT;
              pbuff_param.type   = ICMP6_PACKET_TYPE;
              pbuff_param.length = ICMP6_ECHO_REQUEST_PAYLOAD_OFFSET + 10;

              // Allocate packet buffer.
              err_code = iot_pbuffer_allocate(&pbuff_param, &p_buffer);
              APP_ERROR_CHECK(err_code);

              // Fill payload of Echo Request with 'A' letters.
              memset(p_buffer->p_payload + ICMP6_ECHO_REQUEST_PAYLOAD_OFFSET, 'A', 10);

              // Find proper source address for given destination one.
              err_code = ipv6_address_find_best_match(&mp_interface, &src_addr, &m_hostname_address);
              APP_ERROR_CHECK(err_code);

              // Send Echo Request to all nodes.
              err_code = icmp6_echo_request(mp_interface, &src_addr, &m_hostname_address, p_buffer);
              APP_ERROR_CHECK(err_code);

              // Increase retransmission number.
              m_echo_req_retry_count++;
          }
          else
          {
              APPL_LOG("[APPL]: Failed, no Echo Response received.\r\n");
              // Go to initial state.
              m_app_state = APP_STATE_QUERYING;
          }
          break;
      default:
        break;
    }
}
Exemple #22
0
/**@brief Function for the LEDs initialization.
 *
 * @details Initializes all LEDs used by the application.
 */
static void leds_init(void)
{
    LEDS_CONFIGURE(ADVERTISING_LED_PIN | CONNECTED_LED_PIN | LEDBUTTON_LED_PIN);
    LEDS_OFF(ADVERTISING_LED_PIN | CONNECTED_LED_PIN | LEDBUTTON_LED_PIN);
}
/*****************************************************************************
*
*  HTTP Client
*
*  \param  None
*
*  \return  None
*
*  \brief  Main function of Exosite demo code
*
*****************************************************************************/
void HTTPClient(void)
{
    int i;
 // char header[10000];   // for send HTTP HEADER and POST content in one packet

  if (!check_network_connected()){
    return;
  }

  // worked on demo app every 1/3 second
 // if (badcik==1 ||send_data==TRUE)

  if (badcik==1 ||send_data==TRUE||task_delay(TICK_SECOND, 1))
            workon_demo =1;

  if (workon_demo)
  {
    if (badcik == 1)
    {
      badcik = 1;
      check_cloud_activated();
      if (status_code == STATUS_END )
      {
           cloud_status = CLOUD_HOME;
           workon_demo = 0;
           // generate a new data set
      //    generateData(1500);

      }

    }
    else
    {
      if ( cloud_status == CLOUD_HOME)
      {

          if(send_data == TRUE)
          {
            if(Cloud_Post())
            {
                cloud_status =  CLOUD_HOME;
                workon_demo = 0;
                send_data = FALSE;
                LEDS_OFF();
                DelayMs(100);

              }
             else    workon_demo = 1;  //waiting for HTTP response
          }
          else
          {
            // ping or poll for a command from cloud server
              if(Cloud_GetCmd())
              {
                    workon_demo = 0;
                    cloud_status =  CLOUD_HOME;
                    LEDS_OFF();
              }

          }
      }

   /*
     else if (CLOUD_READING == cloud_status)
     {
      //   if (read_command())
         cloud_status++;
     }
      else if (CLOUD_WRITING == cloud_status)
      {
          if (heart_beat_report())
          cloud_status++;
      }
      else if (CLOUD_BUTTON_STATUS_UPDATE == cloud_status)
      {
   //     if (button_monitor())
      //    cloud_status = CLOUD_READING;
          cloud_status = CLOUD_HOME;
      }
   */
    }
  }

  // indicate last status
//   show_cloud_status();

  return;
}
Exemple #24
0
/**
 * The main function.
 */
int main( void )
{
    /* Stop the watchdog timer */
    WDTCTL = WDTPW + WDTHOLD;

    /* Setup the MSP430 micro-controller clock frequency: MCLK, SMCLK and ACLK */

    /* Set MCLK at 8MHz and SMCLK at 1MHz */
    set_mcu_speed_xt2_mclk_8MHz_smclk_1MHz();

	/* Set ACKL at 4096Hz (32 768Hz / 8) */
    set_aclk_div(8);

    /* Initialize the LEDs */
    LEDS_INIT();
    LEDS_OFF();

    /* Initialize the temperature sensor */
    ds1722_init();
    ds1722_set_res(12);
    ds1722_sample_cont();

    /* Initialize the Luminosity sensor */
    tsl2550_init();
    tsl2550_powerup();
    tsl2550_set_standard();
    tsl2550_read_adc0();

    /* Initialize the UART0 */

	/* We want 115kbaud, and SMCLK is running at 1MHz */
    uart0_init(UART0_CONFIG_1MHZ_115200);

	/* Set the UART callback function it will be called every time a character is received. */
    uart0_register_callback(char_rx);

    /* Print first message */
    printf("\n\nSenslab Simple Demo program\n");

    /* Enable Interrupts */
    eint();

    /* Print information */
    printf("Type command\n");
    printf("\tt:\ttemperature measure\n");
    printf("\tl:\tluminosity measure\n");

    /* Initialize the timer for the LEDs */
    timerA_init();

	/*  TimerA clock is at 512Hz (4096Hz / 8) */
    timerA_start_ACLK_div(TIMERA_DIV_8);

    /* Configure the first timerA period to 1s (periodic) */
    timerA_set_alarm_from_now(TIMERA_ALARM_CCR0, 512, 512);

	/* Set the first timerA callback */
    timerA_register_cb(TIMERA_ALARM_CCR0, alarm);

    // Declare 2 variables for storing the different values
    int16_t value_0=0, value_1=1;
    while (1) {
        printf("cmd > ");
        cmd = 0;

        while (cmd==0) {
            LPM0; // Low Power Mode 1: SMCLK remains active for UART
        }

        switch (cmd) {
        case 't':
            value_0 = ds1722_read_MSB();
            value_1 = ds1722_read_LSB();
            value_1 >>= 5;
            value_1 *= 125;
            printf("Temperature measure: %i.%i\n", value_0, value_1);
            break;
        case 'l':
            tsl2550_init();
            value_0 = tsl2550_read_adc0();
            value_1 = tsl2550_read_adc1();
            uart0_init(UART0_CONFIG_1MHZ_115200);
            uart0_register_callback(char_rx);
            printf("Luminosity measure: %i:%i\n", value_0, value_1);
            break;
        default:
            break;
        }
    }

    return 0;
}
Exemple #25
0
/**@brief       Configure leds to indicate required state.
 * @param[in]   indicate   State to be indicated.
 */
static uint32_t bsp_led_indication(bsp_indication_t indicate)
{
    uint32_t err_code   = NRF_SUCCESS;
    uint32_t next_delay = 0;

    switch (indicate)
    {
        case BSP_INDICATE_IDLE:
            LEDS_OFF(LEDS_MASK & ~ALERT_LED_MASK);
            m_stable_state = indicate;
            break;

        case BSP_INDICATE_SCANNING:
        case BSP_INDICATE_ADVERTISING:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_0_MASK & ~ALERT_LED_MASK);

            // in advertising blink LED_0
            if (LED_IS_ON(BSP_LED_0_MASK))
            {
                LEDS_OFF(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING ? ADVERTISING_LED_OFF_INTERVAL :
                             ADVERTISING_SLOW_LED_OFF_INTERVAL;
            }
            else
            {
                LEDS_ON(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING ? ADVERTISING_LED_ON_INTERVAL :
                             ADVERTISING_SLOW_LED_ON_INTERVAL;
            }

            m_stable_state = indicate;
            err_code       = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(next_delay), NULL);
            break;

        case BSP_INDICATE_ADVERTISING_WHITELIST:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_0_MASK & ~ALERT_LED_MASK);

            // in advertising quickly blink LED_0
            if (LED_IS_ON(BSP_LED_0_MASK))
            {
                LEDS_OFF(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING_WHITELIST ?
                             ADVERTISING_WHITELIST_LED_OFF_INTERVAL :
                             ADVERTISING_SLOW_LED_OFF_INTERVAL;
            }
            else
            {
                LEDS_ON(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING_WHITELIST ?
                             ADVERTISING_WHITELIST_LED_ON_INTERVAL :
                             ADVERTISING_SLOW_LED_ON_INTERVAL;
            }
            m_stable_state = indicate;
            err_code       = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(next_delay), NULL);
            break;

        case BSP_INDICATE_ADVERTISING_SLOW:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_0_MASK & ~ALERT_LED_MASK);

            // in advertising slowly blink LED_0
            if (LED_IS_ON(BSP_LED_0_MASK))
            {
                LEDS_OFF(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING_SLOW ? ADVERTISING_SLOW_LED_OFF_INTERVAL :
                             ADVERTISING_SLOW_LED_OFF_INTERVAL;
            }
            else
            {
                LEDS_ON(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING_SLOW ? ADVERTISING_SLOW_LED_ON_INTERVAL :
                             ADVERTISING_SLOW_LED_ON_INTERVAL;
            }
            m_stable_state = indicate;
            err_code       = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(next_delay), NULL);
            break;

        case BSP_INDICATE_ADVERTISING_DIRECTED:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_0_MASK & ~ALERT_LED_MASK);

            // in advertising very quickly blink LED_0
            if (LED_IS_ON(BSP_LED_0_MASK))
            {
                LEDS_OFF(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING_DIRECTED ?
                             ADVERTISING_DIRECTED_LED_OFF_INTERVAL :
                             ADVERTISING_SLOW_LED_OFF_INTERVAL;
            }
            else
            {
                LEDS_ON(BSP_LED_0_MASK);
                next_delay = indicate ==
                             BSP_INDICATE_ADVERTISING_DIRECTED ?
                             ADVERTISING_DIRECTED_LED_ON_INTERVAL :
                             ADVERTISING_SLOW_LED_ON_INTERVAL;
            }
            m_stable_state = indicate;
            err_code       = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(next_delay), NULL);
            break;

        case BSP_INDICATE_BONDING:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_0_MASK & ~ALERT_LED_MASK);

            // in bonding fast blink LED_0
            if (LED_IS_ON(BSP_LED_0_MASK))
            {
                LEDS_OFF(BSP_LED_0_MASK);
            }
            else
            {
                LEDS_ON(BSP_LED_0_MASK);
            }

            m_stable_state = indicate;
            err_code       =
                app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(BONDING_INTERVAL), NULL);
            break;

        case BSP_INDICATE_CONNECTED:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_0_MASK & ~ALERT_LED_MASK);
            LEDS_ON(BSP_LED_0_MASK);
            m_stable_state = indicate;
            break;

        case BSP_INDICATE_SENT_OK:
            // when sending shortly invert LED_1
            LEDS_INVERT(BSP_LED_1_MASK);
            err_code = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(SENT_OK_INTERVAL), NULL);
            break;

        case BSP_INDICATE_SEND_ERROR:
            // on receving error invert LED_1 for long time
            LEDS_INVERT(BSP_LED_1_MASK);
            err_code = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(SEND_ERROR_INTERVAL), NULL);
            break;

        case BSP_INDICATE_RCV_OK:
            // when receving shortly invert LED_1
            LEDS_INVERT(BSP_LED_1_MASK);
            err_code = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(RCV_OK_INTERVAL), NULL);
            break;

        case BSP_INDICATE_RCV_ERROR:
            // on receving error invert LED_1 for long time
            LEDS_INVERT(BSP_LED_1_MASK);
            err_code = app_timer_start(m_leds_timer_id, BSP_MS_TO_TICK(RCV_ERROR_INTERVAL), NULL);
            break;

        case BSP_INDICATE_FATAL_ERROR:
            // on fatal error turn on all leds
            LEDS_ON(LEDS_MASK);
            break;

        case BSP_INDICATE_ALERT_0:
        case BSP_INDICATE_ALERT_1:
        case BSP_INDICATE_ALERT_2:
        case BSP_INDICATE_ALERT_3:
        case BSP_INDICATE_ALERT_OFF:
            err_code   = app_timer_stop(m_alert_timer_id);
            next_delay = (uint32_t)BSP_INDICATE_ALERT_OFF - (uint32_t)indicate;

            // a little trick to find out that if it did not fall through ALERT_OFF
            if (next_delay && (err_code == NRF_SUCCESS))
            {
                if (next_delay > 1)
                {
                    err_code = app_timer_start(m_alert_timer_id, BSP_MS_TO_TICK(
                                                   (next_delay * ALERT_INTERVAL)), NULL);
                }
                LEDS_ON(ALERT_LED_MASK);
            }
            else
            {
                LEDS_OFF(ALERT_LED_MASK);
            }
            break;

        case BSP_INDICATE_USER_STATE_OFF:
            LEDS_OFF(LEDS_MASK);
            m_stable_state = indicate;
            break;

        case BSP_INDICATE_USER_STATE_0:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_0_MASK);
            LEDS_ON(BSP_LED_0_MASK);
            m_stable_state = indicate;
            break;

        case BSP_INDICATE_USER_STATE_1:
            LEDS_OFF(LEDS_MASK & ~BSP_LED_1_MASK);
            LEDS_ON(BSP_LED_1_MASK);
            m_stable_state = indicate;
            break;

        case BSP_INDICATE_USER_STATE_2:
            LEDS_OFF(LEDS_MASK & ~(BSP_LED_0_MASK | BSP_LED_1_MASK));
            LEDS_ON(BSP_LED_0_MASK | BSP_LED_1_MASK);
            m_stable_state = indicate;
            break;

        case BSP_INDICATE_USER_STATE_3:

        case BSP_INDICATE_USER_STATE_ON:
            LEDS_ON(LEDS_MASK);
            m_stable_state = indicate;
            break;

        default:
            break;
    }

    return err_code;
}
Exemple #26
0
int main(void)
{	
	NVIC_InitTypeDef NVIC_InitStruct;
  /* System Clocks Configuration */
  RCC_Configuration();

  /* GPIO Configuration */
  GPIO_Configuration();
	GPIO_PinRemapConfig(GPIO_PartialRemap2_TIM2, ENABLE);
	
	LEDS_OFF();

  /* -----------------------------------------------------------------------
    TIM3 Configuration: generate 4 PWM signals with 4 different duty cycles:
    TIM3CLK = 36 MHz, Prescaler = 0x0, TIM3 counter clock = 36 MHz
    TIM3 ARR Register = 999 => TIM3 Frequency = TIM3 counter clock/(ARR + 1)
    TIM3 Frequency = 36 KHz.
    TIM3 Channel1 duty cycle = (TIM3_CCR1/ TIM3_ARR)* 100 = 50%
    TIM3 Channel2 duty cycle = (TIM3_CCR2/ TIM3_ARR)* 100 = 37.5%
    TIM3 Channel3 duty cycle = (TIM3_CCR3/ TIM3_ARR)* 100 = 25%
    TIM3 Channel4 duty cycle = (TIM3_CCR4/ TIM3_ARR)* 100 = 12.5%
  ----------------------------------------------------------------------- */

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 19999;	//4999
  TIM_TimeBaseStructure.TIM_Prescaler = 8;//17
  TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV2;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  /* PWM1 Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = Pulse_value;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC4Init(TIM2, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);

//  /* PWM1 Mode configuration: Channel2 */
//  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

//  TIM_OC2Init(TIM3, &TIM_OCInitStructure);

//  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

//  /* PWM1 Mode configuration: Channel3 */
//  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

//  TIM_OC3Init(TIM3, &TIM_OCInitStructure);

//  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);

//  /* PWM1 Mode configuration: Channel4 */
//  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

//  TIM_OC4Init(TIM3, &TIM_OCInitStructure);

//  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);

  TIM_ARRPreloadConfig(TIM2, ENABLE);
	TIM_ITConfig(TIM2, TIM_IT_CC4,  ENABLE );  

  /* TIM3 enable counter */
  TIM_Cmd(TIM2, ENABLE);
	
//  NVIC_InitTypeDef NVIC_InitStructure;
//  
//  /* Configure one bit for preemption priority */
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
//////  
////  /* Enable the EXTI9_5 Interrupt */
  NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
  NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStruct);
  while (1)
  {}
}
Exemple #27
0
/**
 * The main function.
 */
int main( void )
{
    // Stop the watchdog timer.
    WDTCTL = WDTPW + WDTHOLD;

    // Setup MCLK 8MHz and SMCLK 1MHz
    set_mcu_speed_xt2_mclk_8MHz_smclk_1MHz();
    set_aclk_div(8); // ACKL is at 4096Hz

    // Initialize the LEDs
    LEDS_INIT();
    LEDS_OFF();

    // Initialize the temperature sensor
    ds1722_init();
    ds1722_set_res(12);
    ds1722_sample_cont();

    // Initialier the Luminosity sensor
    tsl2550_init();
    tsl2550_powerup();
    tsl2550_set_standard();
    tsl2550_read_adc0();

    // Initialize the UART0
    uart0_init(UART0_CONFIG_1MHZ_115200); // We want 115kbaud,
                                          // and SMCLK is running at 1MHz
    uart0_register_callback(char_rx);   // Set the UART callback function
                                        // it will be called every time a
                                        // character is received.

    // Print first message
    printf("Senslab TP Ex2: UART\n");

    // Enable Interrupts
    eint();

    // Print information
    printf("Type command\n");
    printf("\tt:\ttemperature measure\n");
    printf("\tl:\tluminosity measure\n");

    // Declare 2 variables for storing the different values
    int16_t value_0, value_1;
    while (1) {
        printf("cmd > ");
        cmd = 0;

        while (cmd==0) {
            LPM1; // Low Power Mode 1: SMCLK remains active for UART
        }

        switch (cmd) {
        case 't':
            value_0 = ds1722_read_MSB();
            value_1 = ds1722_read_LSB();
            value_1 >>= 5;
            value_1 *= 125;
            printf("Temperature measure: %i.%i\n", value_0, value_1);
            break;
        case 'l':
            tsl2550_init();
            value_0 = tsl2550_read_adc0();
            value_1 = tsl2550_read_adc1();
            uart0_init(UART0_CONFIG_1MHZ_115200);
            uart0_register_callback(char_rx);
            printf("Luminosity measure: %i:%i\n", value_0, value_1);
            break;
        default:
            break;
        }
    }

    return 0;
}
/****************************************************************************
  Function:
    static void InitializeBoard(void)

  Description:
    This routine initializes the hardware.  It is a generic initialization
    routine for many of the Microchip development boards, using definitions
    in HardwareProfile.h to determine specific initialization.

  Precondition:
    None

  Parameters:
    None - None

  Returns:
    None

  Remarks:
    None
  ***************************************************************************/
static void InitializeBoard(void)
{
    // Note: WiFi Module hardware Initialization handled by StackInit() Library Routine

    // Enable multi-vectored interrupts
    INTEnableSystemMultiVectoredInt();

    // Enable optimal performance
    SYSTEMConfigPerformance(GetSystemClock());

    // Use 1:1 CPU Core:Peripheral clocks
    mOSCSetPBDIV(OSC_PB_DIV_1);     

    // Disable JTAG port so we get our I/O pins back, but first
    // wait 50ms so if you want to reprogram the part with
    // JTAG, you'll still have a tiny window before JTAG goes away.
    // The PIC32 Starter Kit debuggers use JTAG and therefore must not
    // disable JTAG.
    DelayMs(50);
    DDPCONbits.JTAGEN = 0;

    // UART line configuration

    UARTConfigure(SENSOR_UART, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(SENSOR_UART, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(SENSOR_UART, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(SENSOR_UART, GetPeripheralClock(), 9600);
    UARTEnable(SENSOR_UART, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));


    UARTConfigure(SENSOR_UART2, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(SENSOR_UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(SENSOR_UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(SENSOR_UART2, GetPeripheralClock(), 9600);
    UARTEnable(SENSOR_UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));

    // ADC configuration

    // Define setup parameters for OpenADC10 function
    // Attention, the sample number need to be changed for multi sensor use, not 1
// Turn module on | Ouput in integer format | Trigger mode auto | Disable autosample    , manually controlled
#define config1     ADC_FORMAT_INTG | ADC_CLK_AUTO | ADC_AUTO_SAMPLING_ON | ADC_MODULE_ON | ADC_IDLE_STOP
// ADC ref external | Disable offset test | Disable scan mode | Perform 1 samples | Use dual buffers | Use alternate mode
#define config2     ADC_VREF_AVDD_AVSS | ADC_OFFSET_CAL_DISABLE | ADC_SCAN_ON | ADC_SAMPLES_PER_INT_2 | ADC_ALT_BUF_OFF | ADC_ALT_INPUT_OFF
// Use ADC internal clock | Set sample time
#define config3     ADC_CONV_CLK_INTERNAL_RC | ADC_SAMPLE_TIME_31
// Do not assign channels to scan
#define configscan  ~(ENABLE_AN2_ANA | ENABLE_AN3_ANA)
  // Define the port for ADC, need to be modified for practical prox sensors
 #define configport  ENABLE_AN2_ANA | ENABLE_AN3_ANA

    CloseADC10();
    // here use on-board potentiometer for testing, change pin configuration when for actually prox sensor use
    SetChanADC10( ADC_CH0_NEG_SAMPLEA_NVREF);
    // Configure ADC using the parameters defined above
    OpenADC10( config1, config2, config3, configport, configscan );

    EnableADC10(); // Enable the ADC

    // LEDs
    LEDS_OFF();
    LED0_TRIS = 0;
    LED1_TRIS = 0;
    LED2_TRIS = 0;

    // Push Button
    SW0_TRIS = 1;

        // MPU 9150 I2C Init and chip init
      Mpu_I2c_Init(I2C_NUM);      // config the I2C module on PIC32
        // wait at least 100 ms for sensor chip warm up, based on 40Mhz sysclk 4M times
     DelayMs(100);
    if (Mpu_Init(I2C_NUM)==I2C_ERROR)         // Initialize the 9150 chip
       // UARTTxBuffer("Sensor is not connected",strlen("Sensor is not connected"));
     LEDS_ON();
}
Exemple #29
0
/*---------------------------------------------------------------------------*/
static int
send_packet(void)
{
    rtimer_clock_t t0;
    rtimer_clock_t t;
    rtimer_clock_t encounter_time = 0;
    int strobes;
#if 0
    struct xmac_hdr *hdr;
#endif
    uint8_t got_strobe_ack = 0;
    uint8_t got_ack = 0;
    uint8_t strobe[MAX_STROBE_SIZE];
    int strobe_len, len;
    int is_broadcast = 0;
    int is_reliable;
    struct encounter *e;
    struct queuebuf *packet;
    int is_already_streaming = 0;
    uint8_t collisions;

    /* Create the X-MAC header for the data packet. */
    packetbuf_set_addr(PACKETBUF_ADDR_SENDER, &rimeaddr_node_addr);
    if(rimeaddr_cmp(packetbuf_addr(PACKETBUF_ADDR_RECEIVER), &rimeaddr_null)) {
        is_broadcast = 1;
        PRINTDEBUG("xmac: send broadcast\n");
    } else {
#if UIP_CONF_IPV6
        PRINTDEBUG("xmac: send unicast to %02x%02x:%02x%02x:%02x%02x:%02x%02x\n",
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[0],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[1],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[2],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[3],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[4],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[5],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[6],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[7]);
#else
        PRINTDEBUG("xmac: send unicast to %u.%u\n",
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[0],
                   packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[1]);
#endif /* UIP_CONF_IPV6 */
    }
    is_reliable = packetbuf_attr(PACKETBUF_ATTR_RELIABLE) ||
                  packetbuf_attr(PACKETBUF_ATTR_ERELIABLE);

    packetbuf_set_attr(PACKETBUF_ATTR_MAC_ACK, 1);
    len = NETSTACK_FRAMER.create();
    strobe_len = len + sizeof(struct xmac_hdr);
    if(len == 0 || strobe_len > (int)sizeof(strobe)) {
        /* Failed to send */
        PRINTF("xmac: send failed, too large header\n");
        return MAC_TX_ERR_FATAL;
    }
    memcpy(strobe, packetbuf_hdrptr(), len);
    strobe[len] = DISPATCH; /* dispatch */
    strobe[len + 1] = TYPE_STROBE; /* type */

    packetbuf_compact();
    packet = queuebuf_new_from_packetbuf();
    if(packet == NULL) {
        /* No buffer available */
        PRINTF("xmac: send failed, no queue buffer available (of %u)\n",
               QUEUEBUF_CONF_NUM);
        return MAC_TX_ERR;
    }

#if WITH_STREAMING
    if(is_streaming == 1 &&
            (rimeaddr_cmp(packetbuf_addr(PACKETBUF_ADDR_RECEIVER),
                          &is_streaming_to) ||
             rimeaddr_cmp(packetbuf_addr(PACKETBUF_ADDR_RECEIVER),
                          &is_streaming_to_too))) {
        is_already_streaming = 1;
    }
    if(packetbuf_attr(PACKETBUF_ATTR_PACKET_TYPE) ==
            PACKETBUF_ATTR_PACKET_TYPE_STREAM) {
        is_streaming = 1;
        if(rimeaddr_cmp(&is_streaming_to, &rimeaddr_null)) {
            rimeaddr_copy(&is_streaming_to, packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
        } else if(!rimeaddr_cmp(&is_streaming_to, packetbuf_addr(PACKETBUF_ADDR_RECEIVER))) {
            rimeaddr_copy(&is_streaming_to_too, packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
        }
        stream_until = RTIMER_NOW() + DEFAULT_STREAM_TIME;
    }
#endif /* WITH_STREAMING */

    off();

#if WITH_ENCOUNTER_OPTIMIZATION
    /* We go through the list of encounters to find if we have recorded
       an encounter with this particular neighbor. If so, we can compute
       the time for the next expected encounter and setup a ctimer to
       switch on the radio just before the encounter. */
    for(e = list_head(encounter_list); e != NULL; e = list_item_next(e)) {
        const rimeaddr_t *neighbor = packetbuf_addr(PACKETBUF_ADDR_RECEIVER);

        if(rimeaddr_cmp(neighbor, &e->neighbor)) {
            rtimer_clock_t wait, now, expected;

            /* We expect encounters to happen every DEFAULT_PERIOD time
            units. The next expected encounter is at time e->time +
             DEFAULT_PERIOD. To compute a relative offset, we subtract
             with clock_time(). Because we are only interested in turning
             on the radio within the DEFAULT_PERIOD period, we compute the
             waiting time with modulo DEFAULT_PERIOD. */

            now = RTIMER_NOW();
            wait = ((rtimer_clock_t)(e->time - now)) % (DEFAULT_PERIOD);
            if(wait < 2 * DEFAULT_ON_TIME) {
                wait = DEFAULT_PERIOD;
            }
            expected = now + wait - 2 * DEFAULT_ON_TIME;

#if WITH_ACK_OPTIMIZATION
            /* Wait until the receiver is expected to be awake */
            if(packetbuf_attr(PACKETBUF_ATTR_PACKET_TYPE) !=
                    PACKETBUF_ATTR_PACKET_TYPE_ACK &&
                    is_streaming == 0) {
                /* Do not wait if we are sending an ACK, because then the
                   receiver will already be awake. */
                while(RTIMER_CLOCK_LT(RTIMER_NOW(), expected));
            }
#else /* WITH_ACK_OPTIMIZATION */
            /* Wait until the receiver is expected to be awake */
            while(RTIMER_CLOCK_LT(RTIMER_NOW(), expected));
#endif /* WITH_ACK_OPTIMIZATION */
        }
    }
#endif /* WITH_ENCOUNTER_OPTIMIZATION */

    /* By setting we_are_sending to one, we ensure that the rtimer
       powercycle interrupt do not interfere with us sending the packet. */
    we_are_sending = 1;

    t0 = RTIMER_NOW();
    strobes = 0;

    LEDS_ON(LEDS_BLUE);

    /* Send a train of strobes until the receiver answers with an ACK. */

    /* Turn on the radio to listen for the strobe ACK. */
    //  on();
    collisions = 0;
    if(!is_already_streaming) {
        watchdog_stop();
        got_strobe_ack = 0;
        t = RTIMER_NOW();
        for(strobes = 0, collisions = 0;
                got_strobe_ack == 0 && collisions == 0 &&
                RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + xmac_config.strobe_time);
                strobes++) {

            while(got_strobe_ack == 0 &&
                    RTIMER_CLOCK_LT(RTIMER_NOW(), t + xmac_config.strobe_wait_time)) {
#if 0
                rtimer_clock_t now = RTIMER_NOW();

                /* See if we got an ACK */
                packetbuf_clear();
                len = NETSTACK_RADIO.read(packetbuf_dataptr(), PACKETBUF_SIZE);
                if(len > 0) {
                    packetbuf_set_datalen(len);
                    if(NETSTACK_FRAMER.parse()) {
                        hdr = packetbuf_dataptr();
                        if(hdr->dispatch == DISPATCH && hdr->type == TYPE_STROBE_ACK) {
                            if(rimeaddr_cmp(packetbuf_addr(PACKETBUF_ADDR_RECEIVER),
                                            &rimeaddr_node_addr)) {
                                /* We got an ACK from the receiver, so we can immediately send
                                   the packet. */
                                got_strobe_ack = 1;
                                encounter_time = now;
                            } else {
                                PRINTDEBUG("xmac: strobe ack for someone else\n");
                            }
                        } else { /*if(hdr->dispatch == DISPATCH && hdr->type == TYPE_STROBE)*/
                            PRINTDEBUG("xmac: strobe from someone else\n");
                            collisions++;
                        }
                    } else {
                        PRINTF("xmac: send failed to parse %u\n", len);
                    }
                }
#endif /* 0 */
            }

            t = RTIMER_NOW();
            /* Send the strobe packet. */
            if(got_strobe_ack == 0 && collisions == 0) {

                if(is_broadcast) {
#if WITH_STROBE_BROADCAST
                    NETSTACK_RADIO.send(strobe, strobe_len);
#else
                    /* restore the packet to send */
                    queuebuf_to_packetbuf(packet);
                    NETSTACK_RADIO.send(packetbuf_hdrptr(), packetbuf_totlen());
#endif
                    off();
                } else {
#if 0
                    rtimer_clock_t wt;
#endif
                    on();
                    NETSTACK_RADIO.send(strobe, strobe_len);
#if 0
                    /* Turn off the radio for a while to let the other side
                       respond. We don't need to keep our radio on when we know
                       that the other side needs some time to produce a reply. */
                    off();
                    wt = RTIMER_NOW();
                    while(RTIMER_CLOCK_LT(RTIMER_NOW(), wt + WAIT_TIME_BEFORE_STROBE_ACK));
#endif /* 0 */

                    if(detect_ack()) {
                        got_strobe_ack = 1;
                    } else {
                        off();
                    }
                }
            }
        }
    }

#if WITH_ACK_OPTIMIZATION
    /* If we have received the strobe ACK, and we are sending a packet
       that will need an upper layer ACK (as signified by the
       PACKETBUF_ATTR_RELIABLE packet attribute), we keep the radio on. */
    if(got_strobe_ack && (packetbuf_attr(PACKETBUF_ATTR_RELIABLE) ||
                          packetbuf_attr(PACKETBUF_ATTR_ERELIABLE) ||
                          packetbuf_attr(PACKETBUF_ATTR_PACKET_TYPE) ==
                          PACKETBUF_ATTR_PACKET_TYPE_STREAM)) {
        on(); /* Wait for ACK packet */
        waiting_for_packet = 1;
    } else {
        off();
    }
#endif /* WITH_ACK_OPTIMIZATION */

    /* restore the packet to send */
    queuebuf_to_packetbuf(packet);
    queuebuf_free(packet);

    /* Send the data packet. */
    if((is_broadcast || got_strobe_ack || is_streaming) && collisions == 0) {
        NETSTACK_RADIO.send(packetbuf_hdrptr(), packetbuf_totlen());

        if(!is_broadcast) {
            if(detect_ack()) {
                got_ack = 1;
            }
        }
    }
    off();

#if WITH_ENCOUNTER_OPTIMIZATION
    if(got_strobe_ack && !is_streaming) {
        register_encounter(packetbuf_addr(PACKETBUF_ADDR_RECEIVER), encounter_time);
    }
#endif /* WITH_ENCOUNTER_OPTIMIZATION */
    watchdog_start();

    PRINTF("xmac: send (strobes=%u,len=%u,%s), done\n", strobes,
           packetbuf_totlen(), got_strobe_ack ? "ack" : "no ack");

#if XMAC_CONF_COMPOWER
    /* Accumulate the power consumption for the packet transmission. */
    compower_accumulate(&current_packet);

    /* Convert the accumulated power consumption for the transmitted
       packet to packet attributes so that the higher levels can keep
       track of the amount of energy spent on transmitting the
       packet. */
    compower_attrconv(&current_packet);

    /* Clear the accumulated power consumption so that it is ready for
       the next packet. */
    compower_clear(&current_packet);
#endif /* XMAC_CONF_COMPOWER */

    we_are_sending = 0;

    LEDS_OFF(LEDS_BLUE);
    if(collisions == 0) {
        if(is_broadcast == 0 && got_ack == 0) {
            return MAC_TX_NOACK;
        } else {
            return MAC_TX_OK;
        }
    } else {
        someone_is_sending++;
        return MAC_TX_COLLISION;
    }

}
Exemple #30
0
/*---------------------------------------------------------------------------*/
void
leds_arch_init(void)
{
DDRE|=(1<<DDRE5);	// Set pins as output since leds are mounted on the VDD bus
LEDS_OFF();
}