This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

The device app doesn't work with dc adapter or battery, only work with pc, debugger

Hi Devzone!

The development is in the final stage and is now testing by connecting the dc adapter or battery, not by connecting the pc cable and the debugger.

However, when connected to the dc adapter or battery, it was discovered that it no longer worked after iis2dlpc_flag_data_ready_get(&dev_ctx); within the iirun() function.

because, without the iis2dlpc_flag_data_ready_get(&dev_ctx);, It can keep sending the message 'test'.

I thought that Uart and ble priority caused problems in interrupts, so I set the priority of twi, twis, and twim to zero, but the result is the same.

There is no problem when power is supplied from the usb port of the pc and logs are output to the RTT, but when connected to the dc adapter or battery, it is strange that it does not work.

Note that the output of the dc adapter is 5V, 3A.

This is our code.

/**
 * Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
/**
 * @brief BLE LED Button Service central and client application main file.
 *
 * This example can be a central for up to 8 peripherals.
 * The peripheral is called ble_app_blinky and can be found in the ble_peripheral
 * folder.
 */
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "nordic_common.h"
#include "compiler_abstraction.h"
#include "nrf.h"
#include "app_error.h"
#include "app_uart.h"
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "app_timer.h"
#include "bsp_btn_ble.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_db_discovery.h"
#include "app_timer.h"
#include "app_util.h"
#include "ble_nus_c.h"
#include "ble_conn_state.h"
#include "nrf_ble_gatt.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_ble_scan.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_saadc.h"
#include "nrf_drv_timer.h"
#include "nrf_delay.h"
#include "nrf_drv_twi.h"
#include "boards.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"

#include "nrf_twi_sensor.h"
#include "nrf_twi_mngr.h"
#include "nrf_twi.h"
#include "iis2dlpc.h"

#if defined (UART_PRESENT)
#include "nrf_uart.h"
#endif
#if defined (UARTE_PRESENT)
#include "nrf_uarte.h"
#endif

#define APP_BLE_CONN_CFG_TAG      1                                             /**< Tag that refers to the BLE stack configuration that is set with @ref sd_ble_cfg_set. The default tag is @ref APP_BLE_CONN_CFG_TAG. */
#define APP_BLE_OBSERVER_PRIO     3                                             /**< BLE observer priority of the application. There is no need to modify this value. */

#define UART_TX_BUF_SIZE        2048                                             /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE        2048                                             /**< UART RX buffer size. */

#define CENTRAL_SCANNING_LED      BSP_BOARD_LED_0
#define CENTRAL_CONNECTED_LED     BSP_BOARD_LED_1
#define LEDBUTTON_LED             BSP_BOARD_LED_2                               /**< LED to indicate a change of state of the Button characteristic on the peer. */

#define LEDBUTTON_BUTTON          BSP_BUTTON_0                                  /**< Button that writes to the LED characteristic of the peer. */
#define BUTTON_DETECTION_DELAY    APP_TIMER_TICKS(50)                           /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */
#define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN                      /**< UUID type for the Nordic UART Service (vendor specific). */
#define ECHOBACK_BLE_UART_DATA  0                                               /**< The flag whether central sends peripheral the received message again */  

#define NRF_POWER_EN 12
#define LM5_ONOFF_RESET

#define BAT_LIMIT 35

#define TIMECHECK                                                               /**< The flag of checking execution time. */

#define DIFF_SIZE 20                                                                /**< difference 0~2 arrays size. */
#define II_ADDR (0x33U >>1)                                                         /**< IIS2DLPC Sensor Adress. */
#define MAX_PENDING_TRANSACTIONS    4                                               /**< Maximum numbers of pending transactions. */


NRF_BLE_GATT_DEF(m_gatt);                                                       /**< GATT module instance. */
BLE_NUS_C_ARRAY_DEF(m_ble_nus_c, NRF_SDH_BLE_TOTAL_LINK_COUNT);
BLE_DB_DISCOVERY_ARRAY_DEF(m_db_disc, NRF_SDH_BLE_TOTAL_LINK_COUNT);            /**< Database discovery module instances. */
NRF_BLE_SCAN_DEF(m_scan);                                                       /**< Scanning Module instance. */
NRF_TWI_MNGR_DEF(m_nrf_twi_mngr, MAX_PENDING_TRANSACTIONS, 1);                          /**< TWI transaction manager instance. */
NRF_TWI_SENSOR_DEF(m_nrf_twi_sensor, &m_nrf_twi_mngr, NRF_TWI_SENSOR_SEND_BUF_SIZE);    /**< TWI sensor instance. */

static char const m_target_periph_name[] = "Nordic_Blinky";                     /**< Name of the device to try to connect to. This name is searched for in the scanning report data. */

static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH;          /**< The maximum length of ble data. */
static uint8_t m_ble_nus_c_count;                                               /**< The instance of present connected count of ble devices. */

#ifdef TIMECHECK
static uint32_t start;                                                          /**< The time recorded when program starts. */
static uint32_t stop;                                                           /**< The time recorded when program terminates. */
static uint32_t elapsed;                                                        /**< The execution time. */
#endif

static uint8_t temp_array[BLE_NUS_MAX_DATA_LEN];
static uint8_t* temp_current = temp_array;
static bool lte_lock = false;
volatile uint16_t accel_counter = 0;                                       /**< The counter used for counting the excution counts of iss2dlpc. */

static axis3bit16_t          data_raw_acceleration;                                 /**< Load raw data from iis2dlpc sensor into this variable. */ 
static iis2dlpc_ctx_t        dev_ctx;                                               /**< Handle iis2dlpc sensor's read/write instance with this variable. */
static uint8_t               whoamI, rst;                                           /**< Validate iis2dlpc sensor address and status to use. */ 
static float acceleration_mg[3];                                                    /**< Convert raw data to float(usable) data into this variable by using iis2dlpc sdk. */
static int current_value[3];                                                        /**< Current data to use dto62 private function. */
static int previous_value[3] = {0};                                                 /**< Previous data to use dto62 private function. */
static char difference0[DIFF_SIZE];                                                 /**< X-axis Difference between Previous data and Current data converted by dto62 private function. */
static char difference1[DIFF_SIZE];                                                 /**< Y-axis Difference between Previous data and Current data converted by dto62 private function. */
static char difference2[DIFF_SIZE];                                                 /**< Z-axis Difference between Previous data and Current data converted by dto62 private function. */
static char m_buffer[DIFF_SIZE*3];                                                  /**< Buffer to print all the difference data. */

char x_input[1548] = "{\"data\": \"";
//char y_input[1548] = "{\"data\": \"";
//char z_input[1548] = "{\"data\": \"";

char* x_current = &x_input[10];
//char* y_current = &y_input[10];
//char* z_current = &z_input[10];


static ble_uuid_t const m_nus_uuid =                                            /**< Universally unique service identifiers. */
{
    .uuid = BLE_UUID_DEVICE_INFORMATION_SERVICE,
    .type = BLE_UUID_TYPE_BLE
};

enum {APP_CMD_NOCOMMAND = 0, APP_CMD_SINGLE_CAPTURE, APP_CMD_CHANGE_RESOLUTION};

//typedef struct
//{
//    float32_t   x_input[256];
//    float32_t   y_input[256];
//    float32_t   z_input[256];
//} m_fft_input_f32;
//
//static m_fft_input_f32 fft_accel_input;

void board_init(void)
{ 
    nrf_gpio_cfg_output(NRF_POWER_EN);
    nrf_gpio_pin_set(NRF_POWER_EN);
    nrf_gpio_cfg_output(11);
    nrf_gpio_pin_set(11);
//    nrf_gpio_cfg_output(32+3);
//    nrf_gpio_cfg_output(32+2);
////    nrf_gpio_pin_set(32+3);
////    nrf_gpio_pin_set(32+2);
//    nrf_delay_ms(200);
////    nrf_gpio_pin_clear(32+3);
//    nrf_gpio_pin_set(32+2);
//    nrf_delay_ms(300);
////    nrf_gpio_pin_set(32+3);
//    nrf_gpio_pin_clear(32+2);
//    nrf_delay_ms(5000);
}

/**@brief Function for handling asserts in the SoftDevice.
 *
 * @details This function is called in case of an assert in the SoftDevice.
 *
 * @warning This handler is only an example and is not meant for the final product. You need to analyze
 *          how your product is supposed to react in case of an assert.
 * @warning On assert from the SoftDevice, the system can only recover on reset.
 *
 * @param[in] line_num     Line number of the failing assert call.
 * @param[in] p_file_name  File name of the failing assert call.
 */
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
    app_error_handler(0xDEADBEEF, line_num, p_file_name);
}


/**@brief Function for initializing the LEDs.
 *
 * @details Initializes all LEDs used by the application.
 */
static void leds_init(void)
{
    bsp_board_init(BSP_INIT_LEDS);
}

/**@brief Function for handling Queued Write Module errors.
 *
 * @details A pointer to this function will be passed to each service which may need to inform the
 *          application about an error.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void scan_evt_handler(scan_evt_t const * p_scan_evt)
{
    ret_code_t err_code;

    switch(p_scan_evt->scan_evt_id)
    {
        case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
        {
            err_code = p_scan_evt->params.connecting_err.err_code;
            APP_ERROR_CHECK(err_code);
        } break;

        default:
            break;
    }
}


/**@brief Function for initializing the scanning and setting the filters. */
static void scan_init(void)
{
    ret_code_t          err_code;
    nrf_ble_scan_init_t init_scan;

    memset(&init_scan, 0, sizeof(init_scan));

    init_scan.connect_if_match = true;
    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;

    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for starting scanning. */
static void scan_start(void)
{
    ret_code_t ret;
    
    sd_ble_gap_scan_stop();
    NRF_LOG_INFO("Start scanning for device name %s.", (uint32_t)m_target_periph_name);
    ret = nrf_ble_scan_start(&m_scan);
    APP_ERROR_CHECK(ret);
    // Turn on the LED to signal scanning.
    bsp_board_led_on(CENTRAL_SCANNING_LED);
}

static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
{
    ret_code_t ret_val;

    NRF_LOG_DEBUG("Receiving data.");
    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);

    for (uint32_t i = 0; i < data_len; i++)
    {
        do
        {
            ret_val = app_uart_put(p_data[i]);
            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
            {
                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
                APP_ERROR_CHECK(ret_val);
            }
        } while (ret_val == NRF_ERROR_BUSY);
    }
    if (p_data[data_len-1] == '\r')
    {
        while (app_uart_put('\n') == NRF_ERROR_BUSY);
    }
}


/**@brief   Function for handling app_uart events.
 *
 * @details This function receives a single character from the app_uart module and appends it to
 *          a string. The string is sent over BLE when the last character received is a
 *          'new line' '\n' (hex 0x0A) or if the string reaches the maximum data length.
 */
void uart_event_handle(app_uart_evt_t * p_event)
{
    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
    static uint8_t index = 0;
    uint32_t       err_code;

    switch (p_event->evt_type)
    {
        case APP_UART_DATA_READY:

            UNUSED_VARIABLE(app_uart_get(&data_array[index]));
            index++;

            if ((data_array[index - 1] == '\n') ||
                (index >= (m_ble_nus_max_data_len)))
            {
                if(index >= 1)
                {
                    NRF_LOG_INFO("%s", NRF_LOG_PUSH(data_array));
                    if(data_array[1]=='C' || data_array[2]==':') temp_current += sprintf(temp_current, "%s", data_array);

                    memset(data_array,0,BLE_NUS_MAX_DATA_LEN);
                    index = 0;
                }
            }
            break;

        case APP_UART_COMMUNICATION_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_communication);
            break;

        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_code);
            break;

        default:
            break;
    }
}


/**@brief Callback handling Nordic UART Service (NUS) client events.
 *
 * @details This function is called to notify the application of NUS client events.
 *
 * @param[in]   p_ble_nus_c   NUS client handle. This identifies the NUS client.
 * @param[in]   p_ble_nus_evt Pointer to the NUS client event.
 */

/**@snippet [Handling events from the ble_nus_c module] */
static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
{
    ret_code_t err_code;

    switch (p_ble_nus_evt->evt_type)
    {
        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:
            NRF_LOG_INFO("Discovery complete.");
            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
            APP_ERROR_CHECK(err_code);
            NRF_LOG_INFO("Connected to device with Nordic UART Service.");

            if(err_code != NRF_ERROR_BUSY)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;

        case BLE_NUS_C_EVT_NUS_TX_EVT:
//            printf(p_ble_nus_evt->p_data);
            break;

        case BLE_NUS_C_EVT_DISCONNECTED:
            NRF_LOG_INFO("Disconnected.");
            scan_start();
            break;
    }
}

/**
 * @brief Function for handling shutdown events.
 *
 * @param[in]   event       Shutdown type.
 */
static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
{
    ret_code_t err_code;

    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
    APP_ERROR_CHECK(err_code);

    switch (event)
    {
        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
            // Prepare wakeup buttons.
            err_code = bsp_btn_ble_sleep_mode_prepare();
            APP_ERROR_CHECK(err_code);
            break;

        default:
            break;
    }

    return true;
}

NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);

/**@brief Function for initializing nRF uart service that will be used by ble.
 */
static void nus_c_init(void)
{
    ret_code_t       err_code;
    ble_nus_c_init_t init;

    init.evt_handler = ble_nus_c_evt_handler;

    for (m_ble_nus_c_count = 0; m_ble_nus_c_count < NRF_SDH_BLE_TOTAL_LINK_COUNT; m_ble_nus_c_count++)
    {
        err_code = ble_nus_c_init(&m_ble_nus_c[m_ble_nus_c_count], &init);
        APP_ERROR_CHECK(err_code);
    }
    m_ble_nus_c_count = 0;
}

/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
    ret_code_t err_code;

    // For readability.
    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 is connected, initiate DB
        // discovery, update LEDs status, and resume scanning, if necessary.
        case BLE_GAP_EVT_CONNECTED:
        {
            NRF_LOG_INFO("Connection 0x%x established, starting DB discovery.",
                         p_gap_evt->conn_handle);

            APP_ERROR_CHECK_BOOL(p_gap_evt->conn_handle < NRF_SDH_BLE_CENTRAL_LINK_COUNT);
            err_code = ble_nus_c_handles_assign(&m_ble_nus_c[p_gap_evt->conn_handle], p_gap_evt->conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
            err_code = ble_db_discovery_start(&m_db_disc[p_gap_evt->conn_handle],
                                              p_gap_evt->conn_handle);
            if (err_code != NRF_ERROR_BUSY)
            {
                APP_ERROR_CHECK(err_code);
            }

            // Update LEDs status and check whether it is needed to look for more
            // peripherals to connect to.
            bsp_board_led_on(CENTRAL_CONNECTED_LED);
            if (ble_conn_state_central_conn_count() == NRF_SDH_BLE_CENTRAL_LINK_COUNT)
            {
                bsp_board_led_off(CENTRAL_SCANNING_LED);
            }
            else
            {
                // Resume scanning.
                bsp_board_led_on(CENTRAL_SCANNING_LED);
                scan_start();
            }
        } break; // BLE_GAP_EVT_CONNECTED

        // Upon disconnection, reset the connection handle of the peer that disconnected, update
        // the LEDs status and start scanning again.
        case BLE_GAP_EVT_DISCONNECTED:
        {
            NRF_LOG_INFO("LBS central link 0x%x disconnected (reason: 0x%x)",
                         p_gap_evt->conn_handle,
                         p_gap_evt->params.disconnected.reason);

            if (ble_conn_state_central_conn_count() == 0)
            {
                // Turn off the LED that indicates the connection.
                bsp_board_led_off(CENTRAL_CONNECTED_LED);
            }

            // Start scanning.
            scan_start();

            // Turn on the LED for indicating scanning.
            bsp_board_led_on(CENTRAL_SCANNING_LED);

        } break;
        
        case BLE_GAP_EVT_TIMEOUT:
        {
            // Timeout for scanning is not specified, so only the connection requests can time out.
            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
            {
                scan_start();
                NRF_LOG_DEBUG("Connection request timed out.");
            }
        } break;

        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
        {
            NRF_LOG_DEBUG("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST.");
            // Accept parameters requested by peer.
            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;

        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
            NRF_LOG_DEBUG("PHY update request.");
            ble_gap_phys_t const phys =
            {
                .rx_phys = BLE_GAP_PHY_AUTO,
                .tx_phys = BLE_GAP_PHY_AUTO,
            };
            err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTC_EVT_TIMEOUT:
        {
            // Disconnect on GATT client timeout event.
            NRF_LOG_DEBUG("GATT client timeout.");
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTS_EVT_TIMEOUT:
        {
            // Disconnect on GATT server timeout event.
            NRF_LOG_DEBUG("GATT server timeout.");
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
        } break;

        default:
            // No implementation needed.
            break;
    }
}


/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupts.
 */
static void ble_stack_init(void)
{
    ret_code_t err_code;

    err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(err_code);

    // Configure the BLE stack using the default settings.
    // Fetch the start address of the application RAM.
    uint32_t ram_start = 0;
    err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
    APP_ERROR_CHECK(err_code);

    // Enable BLE stack.
    err_code = nrf_sdh_ble_enable(&ram_start);
    APP_ERROR_CHECK(err_code);

    // Register a handler for BLE events.
    NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}



/**@brief Function for handling database discovery events.
 *
 * @details This function is a callback function to handle events from the database discovery module.
 *          Depending on the UUIDs that are discovered, this function forwards the events
 *          to their respective services.
 *
 * @param[in] p_event  Pointer to the database discovery event.
 */
static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
{
    ble_nus_c_on_db_disc_evt(&m_ble_nus_c[p_evt->conn_handle], p_evt);
}


/** @brief Database discovery initialization.
 */
static void db_discovery_init(void)
{
    ret_code_t err_code = ble_db_discovery_init(db_disc_handler);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing power management.
 */
static void power_management_init(void)
{
    ret_code_t err_code;
    err_code = nrf_pwr_mgmt_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling the idle state (main loop).
 *
 * @details This function handles any pending log operations, then sleeps until the next event occurs.
 */
static void idle_state_handle(void)
{
    if (NRF_LOG_PROCESS() == false)
    {
        nrf_pwr_mgmt_run();
    }
}


/** @brief Function for initializing the log module.
 */
static void log_init(void)
{
    ret_code_t err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    NRF_LOG_DEFAULT_BACKENDS_INIT();
}


/** @brief Function for initializing the timer.
 */
static void timer_init(void)
{
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);
}

/**@brief Application main function.
 */
void timer_handler(nrf_timer_event_t event_type, void * p_context)
{

}

/**@brief Function for initializing the GATT module.
 */
void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
{
    if (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
    {
        NRF_LOG_INFO("ATT MTU exchange completed.");

        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
    }
}

/**@brief Function for initializing the GATT library. */
void gatt_init(void)
{
    ret_code_t err_code;

    err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_ble_gatt_att_mtu_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
    APP_ERROR_CHECK(err_code);
}

/**@snippet [Handling the data received over UART] */
/**@brief  Function for initializing the UART module.
 */
static void uart_init(void)
{
    ret_code_t err_code;

    app_uart_comm_params_t const comm_params =
    {
        .rx_pin_no    = RX_PIN_NUMBER,
        .tx_pin_no    = TX_PIN_NUMBER,
        .rts_pin_no   = RTS_PIN_NUMBER,
        .cts_pin_no   = CTS_PIN_NUMBER,
        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
        .use_parity   = false,
        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud115200
    };

    APP_UART_FIFO_INIT(&comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_event_handle,
                       APP_IRQ_PRIORITY_HIGHEST,
                       err_code);

    APP_ERROR_CHECK(err_code);
}
/**@snippet [UART Initialization] */

static bool at_send(uint8_t * data, uint32_t size)
{
//    memset(temp_array,0,BLE_NUS_MAX_DATA_LEN);
    ret_code_t ret_val;

    for (uint32_t i = 0; i < size; i++)
    {
        do
        {
            ret_val = app_uart_put(data[i]);
            if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
            {
                NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
                APP_ERROR_CHECK(ret_val);
            }
        } while (ret_val == NRF_ERROR_BUSY);
    }
    nrf_delay_ms(1000);

    return true;
}

static void lte_reboot(void)
{
    uint8_t msg[] = "AT+CFUN=1,1\r";
    at_send(msg, sizeof(msg));
    app_uart_close();
    uart_init();
}

static void open_mqtt(void)
{
    uint8_t msg[] = "AT+QMTOPEN=0,\"avq1xsl5cm8b-ats.iot.us-west-2.amazonaws.com\",8883\r";
    nrf_delay_ms(5000);
    at_send(msg, sizeof(msg));
}

static void connect_mqtt(void)
{
    uint8_t msg[] = "AT+QMTCONN=0,\"mqtttest2\"\r";

    at_send(msg, sizeof(msg));
}

void close_mqtt(void)
{
    uint8_t msg[] = "AT+QMTCLOSE=0\r";

    at_send(msg, sizeof(msg));
}

void publish_mqtt(uint8_t * data)
{
    lte_lock = true;
    uint8_t msg[] = "AT+QMTPUB=0,1,1,0,\"topic2\"\r";

    at_send(msg, sizeof(msg));

//    at_send(data, strlen(data));
    nrf_delay_ms(5000); //1500, 5000
//    NRF_LOG_INFO("length : %d\n",strlen(data));
    at_send(data, strlen(data));
    app_uart_put(0x1A);
    app_uart_put('\r');
    nrf_delay_ms(5000);
}

void lte_psm_enable(void)
{
    lte_lock = false;
    uint8_t lte_down[] = "AT+CPSMS=1,,,\"10100101\",\"00100100\"\r";

    while(lte_lock);

    at_send(lte_down, sizeof(lte_down));

//    app_uart_close();
}

void lte_psm_disable(void)
{
    lte_lock = true;
    uint8_t lte_up[] = "AT+CFUN=1,1\r";

    at_send(lte_up, sizeof(lte_up));

    nrf_delay_ms(2000);
}

void lte_check(void)
{
    uint8_t qcds[] = "AT+QCDS\r";

    at_send(qcds, sizeof(qcds));
}

void lte_setup()
{
    uint8_t disc[] = "AT+QMTDISC=0\r";
    uint8_t close[] = "AT+QMTCLOSE=0\r";
    uint8_t SSL[] = "AT+QMTCFG=\"SSL\",0,1,2\r";
    uint8_t version[] = "AT+QMTCFG=\"version\",0,4\r";
    uint8_t cacert[] = "AT+QSSLCFG=\"cacert\",2,\"UFS:root.pem\"\r";
    uint8_t clientcert[] = "AT+QSSLCFG=\"clientcert\",2,\"UFS:cert.pem\"\r";
    uint8_t clientkey[] = "AT+QSSLCFG=\"clientkey\",2,\"UFS:key.pem\"\r";
    uint8_t seclevel[] = "AT+QSSLCFG=\"seclevel\",2,2\r";
    uint8_t sslversion[] = "AT+QSSLCFG=\"sslversion\",2,4\r";
    uint8_t ciphersuite[] = "AT+QSSLCFG=\"ciphersuite\",2,0xffff\r";
    uint8_t ignorelocaltime[] = "AT+QSSLCFG=\"ignorelocaltime\",1\r";

    at_send(close, sizeof(close));
    nrf_delay_ms(10000);
    at_send(disc, sizeof(disc));
    nrf_delay_ms(10000);
    at_send(SSL, sizeof(SSL));
    at_send(version, sizeof(version));
    at_send(cacert, sizeof(cacert));
    at_send(clientcert, sizeof(clientcert));
    at_send(clientkey, sizeof(clientkey));
    at_send(seclevel, sizeof(seclevel));
    at_send(sslversion, sizeof(sslversion));
    at_send(ciphersuite, sizeof(ciphersuite));
    at_send(ignorelocaltime, sizeof(ignorelocaltime));
}

void lte_connect()
{
    open_mqtt();
    nrf_delay_ms(30000);
//    while(!(temp_array[10]=='0' && temp_array[12]=='0'))
    connect_mqtt();
    nrf_delay_ms(5000); //3000
}

//#ifdef TIMECHECK
//void time_check(void)
//{
//    if(counter == 1023)
//    {
//        stop=DWT->CYCCNT;
//        elapsed=stop-start;
//        printf("%d\n", elapsed);
//        counter = 0;
//        start = DWT->CYCCNT;
//    }
//    counter++;
//}
//#endif

/**@brief Function for TWI (with transaction manager and twi_sensor) initialization.
 */
static void twi_init(void)
{
    uint32_t err_code;
    
    const nrf_drv_twi_config_t ii_config = {
       .scl                = ARDUINO_SCL_PIN,
       .sda                = ARDUINO_SDA_PIN,
       .frequency          = NRF_DRV_TWI_FREQ_100K,
       .interrupt_priority = APP_IRQ_PRIORITY_HIGHEST,
       .clear_bus_init     = false
    };

    err_code = nrf_twi_mngr_init(&m_nrf_twi_mngr, &ii_config);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_twi_sensor_init(&m_nrf_twi_sensor);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for TWI Reset (with transaction manager and twi_sensor) reset.
 */
static void twi_reset(void)
{
    uint32_t err_code;
    
    const nrf_drv_twi_config_t ii_config = {
       .scl                = ARDUINO_SCL_PIN,
       .sda                = ARDUINO_SDA_PIN,
       .frequency          = NRF_DRV_TWI_FREQ_100K,
       .interrupt_priority = APP_IRQ_PRIORITY_HIGHEST,
       .clear_bus_init     = true
    };

    nrf_twi_mngr_uninit(&m_nrf_twi_mngr);
    
    err_code = nrf_twi_mngr_init(&m_nrf_twi_mngr, &ii_config);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_twi_sensor_init(&m_nrf_twi_sensor);
    APP_ERROR_CHECK(err_code);  
}

/**@brief Function for converting decimal to 62 numtype notation.
 */
char* dto62(int decimal)
{
static char hexabindecimal[20] = {0, };
static char minus_hexabindecimal[20];
int position = 0;
int minus_flag = 0;

    while (1)
        {
          if(decimal<0)
            {
             minus_flag=1;
             decimal=decimal*-1;
            }
            int mod = decimal % 62; 
            if (mod < 10)
            {
               hexabindecimal[position] = 48 + mod;
            }
            else if(mod < 36)
            {
               hexabindecimal[position] = 65 + (mod - 10);
            }
            else
            {
               hexabindecimal[position] = 97 + (mod - 36);
            }

            decimal = decimal / 62;

            position++;

            if (decimal == 0)
                break;
        }

  reverseString(hexabindecimal);

  if(minus_flag==1)
  {
    sprintf(minus_hexabindecimal,"-%s",hexabindecimal);
    return minus_hexabindecimal;
  }
  return hexabindecimal;
}


/**@brief Function for connection with the iis2dlpc_read_reg function and nrf52840 SDK.
 * @param[out] return Should be 0.
 */
int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp, uint16_t len)
{
 nrf_twi_sensor_reg_read(&m_nrf_twi_sensor, II_ADDR, reg, NULL, bufp, len);
 nrf_delay_us(1000);
 NRF_LOG_FLUSH();
 return 0;
}

/**@brief Function for connection with the iis2dlpc_write_reg function and nrf52840 SDK.
 * @param[out] return Should be 0.
 */
int32_t platform_write(void *handle, uint8_t reg, uint8_t *bufp, uint16_t len)
{
 nrf_twi_sensor_reg_write(&m_nrf_twi_sensor, II_ADDR, reg, bufp, len);  
 nrf_delay_us(1000);
 NRF_LOG_FLUSH();
 return 0;
}

/**@brief Function for initializing iis2dlpc sensor.
 * @details This function sets states of the iis2dlpc sensor and can affect
 *          the sensitivity of the sensor.
 *          If you failed to get device ID, you can push reset button to solve the issue easily
 */
 void platform_init(void)
{
  twi_init();
  dev_ctx.write_reg = platform_write;
  dev_ctx.read_reg = platform_read;
  dev_ctx.handle = NULL;
  iis2dlpc_device_id_get(&dev_ctx, &whoamI);
  while(whoamI != IIS2DLPC_ID)
  {
      printf("\n\rdevice_id_get failed\n\r");
      twi_reset();
      iis2dlpc_device_id_get(&dev_ctx, &whoamI);
  }
  iis2dlpc_reset_set(&dev_ctx, PROPERTY_ENABLE);
  do {
    iis2dlpc_reset_get(&dev_ctx, &rst);
  } while (rst);
  iis2dlpc_block_data_update_set(&dev_ctx, PROPERTY_ENABLE);
  iis2dlpc_full_scale_set(&dev_ctx, IIS2DLPC_16g);
  iis2dlpc_filter_path_set(&dev_ctx, IIS2DLPC_LPF_ON_OUT);
  iis2dlpc_filter_bandwidth_set(&dev_ctx, IIS2DLPC_ODR_DIV_20);
  iis2dlpc_power_mode_set(&dev_ctx, IIS2DLPC_HIGH_PERFORMANCE_LOW_NOISE);
  iis2dlpc_data_rate_set(&dev_ctx, IIS2DLPC_XL_ODR_1k6Hz);
  printf("\n\rall settings are completed\n\r");
}

void fft_generate_samples(float * input_data)
{
    x_current += sprintf(x_current, " %d %d %d", (int)input_data[0], (int)input_data[1], (int)input_data[2]);
//    y_current += sprintf(y_current, " %d", (int)input_data[1]);
//    z_current += sprintf(z_current, " %d", (int)input_data[2]);
}

/**@brief Function for activating main function of iis2dlpc sensor.
 * @details This function takes raw data from the sensor register and transmits it to the MCU,
 *          converts the data into readable and outputs it.
 *          If the state of the sensor is not ready to get new raw data, initialize all the 
 *          variables' value in this function every time. (except with current/previous_value)
 *          It can judge situations of DIGGING and TILT as well.
 * @param[out] return can be anything.
 */
int iirun(void)
{  
    publish_mqtt("test\r");
  uint8_t reg;
//  iis2dlpc_flag_data_ready_get(&dev_ctx, &reg);

//  if(reg)
//  {    
//        memset(data_raw_acceleration.u8bit, 0x00, 3 * sizeof(int16_t));
//
//        iis2dlpc_acceleration_raw_get(&dev_ctx, data_raw_acceleration.u8bit);
//
//        acceleration_mg[0] = iis2dlpc_from_fs2_to_mg(data_raw_acceleration.i16bit[0]);
//        acceleration_mg[1] = iis2dlpc_from_fs2_to_mg(data_raw_acceleration.i16bit[1]);
//        acceleration_mg[2] = iis2dlpc_from_fs2_to_mg(data_raw_acceleration.i16bit[2]);
//
////        current_value[0] = (int)(acceleration_mg[0]);
////        current_value[1] = (int)(acceleration_mg[1]);
////        current_value[2] = (int)(acceleration_mg[2]);
////    
////        memcpy(difference0,dto62(current_value[0]-previous_value[0]),sizeof(dto62(current_value[0]-previous_value[0])));
////        memcpy(difference1,dto62(current_value[1]-previous_value[1]),sizeof(dto62(current_value[1]-previous_value[1])));
////        memcpy(difference2,dto62(current_value[2]-previous_value[2]),sizeof(dto62(current_value[2]-previous_value[2])));
////
////        memset(m_buffer, 0, sizeof(difference0)+sizeof(difference1)+sizeof(difference2)+3);
////        
////        sprintf(m_buffer, "%s %s %s\n\r", difference0, difference1, difference2);
//
//
//        fft_generate_samples(acceleration_mg);
////        NRF_LOG_INFO("%d\n", strlen(x_input));
//
//        accel_counter++;
//
//        if(accel_counter == 50) //100
//        {
//            at_send("AT+CCLK?\r",10);
//            temp_current = &temp_array[7];
//            x_current += sprintf(x_current, "\", \"date\": %s %s", temp_current, "}\r");
//            publish_mqtt(x_input);
////            NRF_LOG_INFO("%s\n", x_input);
////            publish_mqtt("test\r");
//            x_current = &x_input[10];
//            temp_current = temp_array;
//            accel_counter = 0;
//        }
//
////        NRF_LOG_INFO("               %s\n\r",m_buffer);
//  }
//
//  else
//  {
//  memset(data_raw_acceleration.u8bit, 0x00, 3 * sizeof(int16_t));
//  }
//
//  memcpy(previous_value,current_value,sizeof(current_value));
//  memset(m_buffer, 0x00, DIFF_SIZE*3); 
//  memset(difference0, 0x00, DIFF_SIZE);
//  memset(difference1, 0x00, DIFF_SIZE);
//  memset(difference2, 0x00, DIFF_SIZE);

  return 0;
}

int main(void)
{
    CoreDebug->DEMCR |= 0x1000000;
    DWT->CYCCNT = 0;
    DWT->CTRL |= 0x1;
    // Initialize.
    board_init();
    log_init();
    timer_init(); 
    uart_init();
//    leds_init();
    power_management_init();
    ble_stack_init();
    sd_power_dcdc_mode_set(NRF_POWER_DCDC_ENABLE);
    gatt_init();
    db_discovery_init();
    nus_c_init();
    ble_conn_state_init();
    scan_init();
    platform_init();

    lte_setup();
    lte_connect();
    publish_mqtt("dc adapter test\r");
    nrf_delay_ms(5000);
//    lte_psm_enable();

    // Start execution.
    NRF_LOG_INFO("Multilink example started.");
    scan_start();

    // cycle counter setup
//    #ifdef TIMECHECK
//    CoreDebug->DEMCR |= 0x1000000;
//    DWT->CYCCNT = 0;
//    DWT->CTRL |= 0x1;
//    #endif


     for (;;)
    {
        iirun();
        nrf_delay_us(10);
        idle_state_handle();
    }
}

and this is the MQTT message, As you can see before for(), I sent the message with publish_mqtt("dc adapter test\r"); and after enter the iirun(), I keep sending the message with publish_mqtt("test\r");

and you can see that there are "dc adapter test" and "test" messages. But only once.

Without the iis2dlpc_flag_data_ready_get(&dev_ctx);, It can keep sending the message 'test'.

By the way, When I insert nrf_delay_ms(5000); below publish_mqtt("test\r"); Again, the test message is sent only once. I don't know why It happens.

and with PC cable, not dc adapter, the whole code is running very well including the function of reading value from accelerometer and publishing the message this value.

What would be the problem?

Best regards,

Baek

Related