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

UART Implementation

I am using Nrf52 DK as a J link programmer to program  Laird BL-652  which is connected to NXP LPC 1519 via RX/TX Pins. I am trying to send commands from BL652 to NXP via UART but the BL652 is some times sending the commands and most of the time its says error. Also there is no response from the NXP. However the UART configurations are same on both NXP and BL652.

Here is my UART function-

static void uart_init(void)
{
    uint32_t err_code;
  
  {  const app_uart_comm_params_t comm_params =
      {
          RX_PIN_NUMBER,
          TX_PIN_NUMBER,
          RTS_PIN_NUMBER,
          CTS_PIN_NUMBER,
          UART_HWFC,
          false,
          NRF_UART_BAUDRATE_115200
      };

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

    APP_ERROR_CHECK(err_code);

} 
  static const app_uart_buffers_t comm_params = 
       {
          uart_rx_buf,
          UART_RX_BUF_SIZE,
          uart_rx_buf,
          UART_TX_BUF_SIZE
        };  
          
}

Event Handler-

void uart_error_handle(app_uart_evt_t * p_event)
{

    uint8_t				value;
    uint32_t				err_code;
    if (p_event->evt_type == APP_UART_DATA_READY)
      {
          err_code = app_uart_get(&value);
          APP_ERROR_CHECK(err_code);
          err_code = app_uart_put(value);
          APP_ERROR_CHECK(err_code);    
    }
    
    else if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_communication);
    }
    else if (p_event->evt_type == APP_UART_FIFO_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_code);
    }
}

And my write function-

static void send_uart(char* cmd)
{

    while(app_uart_put(*cmd) == NRF_SUCCESS)
    {
     cmd++;
        
        SEGGER_RTT_WriteString(0,"Success");
   }
    
}

void nxp_flashing(void)
{
 
    
    ret_code_t err_code;
    int* cmd;
   char rsp[5];
    uint8_t cr, i;
    

  if(init == 0)
    {
       
        console_printf("NXP flashing\n");
        nrf_delay_ms(1000);

        nrf_gpio_pin_clear(NXP_BOOT_PIN_NUMBER);
        nrf_gpio_pin_clear(NXP_RESET_PIN_NUMBER);
        nrf_delay_ms(1000);
        nrf_gpio_pin_set(NXP_RESET_PIN_NUMBER);
        nrf_delay_ms(3000);
        nrf_gpio_pin_set(NXP_BOOT_PIN_NUMBER);
        nrf_delay_ms(3000);
        SEGGER_RTT_WriteString(0,"BOOT mode\n");

        board_set_console_uart_baudrate(115200);
        
 
 
        app_uart_put(*cmd) == "?";     
  //  console_putc(63);
  app_uart_flush(); 
  }
  }

Here is my main.c (mostly copy paste)-


#include <stdint.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf.h"
#include "boards.h"
#include "app_error.h"
#include "ble.h"
#include "ble_err.h"
#include "ble_hci.h"
#include "ble_srv_common.h"
#include "ble_advdata.h"
#include "ble_conn_params.h"
#include "ble_conn_state.h"
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "app_timer.h"
//#include "app_button.h"
#include "nrf_soc.h"
#include "nrf_strerror.h"

#ifdef SCANNER_ADDED
#include "nrf_sdh_ble.h"
#include "nrf_sdh_soc.h"
#include "nrf_pwr_mgmt.h"
#include "ble_db_discovery.h"
#include "ble_muz_srv_c.h"
#endif

#ifdef ADD_SERIALIZATION
#include "nrf_sdm.h"
#include "nrf_soc.h"
#include "app_scheduler.h"
#include "ser_hal_transport.h"
#include "ser_conn_handlers.h"
#include "ser_phy_debug_comm.h"
#include "nrf_drv_clock.h"
#endif

#include "ble_muz_srv.h"
#include "nrf_ble_gatt.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "board.h"
#include "common.h"
#include "printf.h"
#include "consoleb.h"
#include "candb.h"
#include "utils.h"
#include "version.h"
#include "crc.h"
#include "uart.h"
#include "i2c.h"
#include "spi.h"
#include "spansion_spi_flash.h"
#include "app_nv.h"
#include "app_event.h"
//#include "app_led.h"
#include "app_scanner.h"
#include "app_pwm.h"            //for app_pwm_init
#include "timer_util.h"
#include "muz_ble_service.h"
#include "ble_muz.h"
#include "app_nv.h"
#include "timer.h"
#include "event.h"
#include "buttons.h"
#include "app_can.h"
#include "can_tunnel.h"
#include "can_default.h"
#include "bootloader.h"
#include "usb_uart_combo_dev.h"
#include "timer_util.h"
#include "app_uart.h"
#include "nrf_delay.h"
#if defined (UART_PRESENT)
#include "nrf_uart.h"
#endif
#if defined (UARTE_PRESENT)
#include "nrf_uarte.h"
#endif

//#define NRF_LOG_LEVEL_DEBUG             3
//#define NRF_LOG_DEFAULT_LEVEL           3
//#define NRF_LOG_LEVEL                   NRF_LOG_LEVEL_DEBUG

#define DEVICE_NAME                     "Nordic_Blinky"                         /**< Name of device. Will be included in the advertising data. */

#define APP_BLE_CONN_CFG_TAG            1                                       /**< A tag identifying the SoftDevice BLE configuration. */
#define LINK_TOTAL                      NRF_SDH_BLE_PERIPHERAL_LINK_COUNT + \
                                        NRF_SDH_BLE_CENTRAL_LINK_COUNT

//#define ADVERTISING_LED                 BSP_BOARD_LED_0                         /**< Is on when device is advertising. */
//#define CONNECTED_LED                   BSP_BOARD_LED_1                         /**< Is on when device has connected. */
//#define LEDBUTTON_LED                   BSP_BOARD_LED_2                         /**< LED to be toggled with the help of the LED Button Service. */
//#define LEDBUTTON_BUTTON                BSP_BUTTON_0                            /**< Button that will trigger the notification event with the LED Button Service */

#ifdef SCANNER_ADDED
//#define CENTRAL_SCANNING_LED            BSP_BOARD_LED_3                     /**< Scanning LED will be on when the device is scanning. */
//#define CENTRAL_CONNECTED_LED           BSP_BOARD_LED_1                     /**< Connected LED will be on when the device is connected. */

#define SCAN_INTERVAL                   (2*0x00A0)                              /**< Determines scan interval in units of 0.625 millisecond. */
#define SCAN_WINDOW                     (0x0050/2)                              /**< Determines scan window in units of 0.625 millisecond. */
#define SCAN_TIMEOUT                    0x0000                              /**< Timout when scanning. 0x0000 disables timeout. */

#define MIN_CONNECTION_INTERVAL         MSEC_TO_UNITS(7.5, UNIT_1_25_MS)    /**< Determines minimum connection interval in milliseconds. */
#define MAX_CONNECTION_INTERVAL         MSEC_TO_UNITS(500, UNIT_1_25_MS)     /**< Determines maximum connection interval in milliseconds. */
//#define SLAVE_LATENCY                   0                                   /**< Determines slave latency in terms of connection events. */
#define SUPERVISION_TIMEOUT             MSEC_TO_UNITS(4000, UNIT_10_MS)     /**< Determines supervision time-out in units of 10 milliseconds. */
#endif

#ifdef THROUGHPUT_CHANGES
#define APP_ADV_INTERVAL                300                                     /**< The advertising interval (in units of 0.625 ms; this value corresponds to 187.5 ms). */
#else
#define APP_ADV_INTERVAL                64                                      /**< The advertising interval (in units of 0.625 ms; this value corresponds to 40 ms). */
#endif
#define APP_ADV_TIMEOUT_IN_SECONDS      BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED   /**< The advertising time-out (in units of seconds). When set to 0, we will never time out. */

#define MIN_CONN_INTERVAL               MSEC_TO_UNITS(100, UNIT_1_25_MS)        /**< Minimum acceptable connection interval (0.5 seconds). */
#define MAX_CONN_INTERVAL               MSEC_TO_UNITS(200, UNIT_1_25_MS)        /**< Maximum acceptable connection interval (1 second). */
#define SLAVE_LATENCY                   0                                       /**< Slave latency. */
#define CONN_SUP_TIMEOUT                MSEC_TO_UNITS(4000, UNIT_10_MS)         /**< Connection supervisory time-out (4 seconds). */

#define FIRST_CONN_PARAMS_UPDATE_DELAY  APP_TIMER_TICKS(20000)                  /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (15 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(5000)                   /**< Time between each call to sd_ble_gap_conn_param_update after the first call (5 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT    3                                       /**< Number of attempts before giving up the connection parameter negotiation. */

//#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 APP_FEATURE_NOT_SUPPORTED       BLE_GATT_STATUS_ATTERR_APP_BEGIN + 2    /**< Reply when unsupported features are requested. */

#define DEAD_BEEF                       0xDEADBEEF                              /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */

/**@brief   Priority of the application BLE event handler.
 * @note    You shouldn't need to modify this value.
 */
#define APP_BLE_OBSERVER_PRIO    3

#define L2CAP_HDR_LEN                   4                                               /**< L2CAP header length. */

/* When UART is used for communication with the host do not use flow control.*/
#define UART_HWFC APP_UART_FLOW_CONTROL_DISABLED

uint32_t reset_reason = 0;
volatile bool SystemResetPending = false;
volatile bool SerializationRestartPending = false;

static ret_code_t scan_start(void);

static void init_data(void);
static void scanner_event_handler(void);
static void paired_event_handler(void);

event_control_t               scanner_event;
event_control_t               paired_event;

extern volatile uint64_t scanner_isr_time;

event_t events[] = {
	{&scanner_event,	scanner_event_handler},
	{&paired_event,	    paired_event_handler},
	{NULL,	NULL},
};

////__RODATA(Header) const file_header_t file_header = {
const file_header_t file_header = {
    {
        VERSION_SOFTWARE_VERSION_MAJOR,                /*major*/
        VERSION_SOFTWARE_VERSION_MINOR,                /*minor*/
        {VERSION_BUILD_NUMBER}        ,                /*build*/
        {VERSION_SVN_REVISION}        ,                /*revision*/
    },
    VERSION_BUILD_DATE_STR " " VERSION_BUILD_TIME_STR, /*build_time*/
    0xFFFFFFFF                                       , /*length - to be filled outside*/
    0xFFFFFFFF                                       , /*crc32  - to be filled outside*/
};

#if (1==UART_FOR_CONSOLE)

static uint8_t uart_rx_buf[UART_RX_BUF_SIZE];
static uint8_t uart_tx_buf[UART_TX_BUF_SIZE];
static const uart_init_params_t console_uart_params = {
    115200U,                //uint32_t baud;
    UART_DATABITS_8,        //uart_data_bits_t data_bits;
    UART_STOPBITS_1,        //uart_stop_bits_t stop_bits;
    UART_PARITY_NONE,       //uart_parity_t parity;
    UART_FLOWCONT_NONE,     //uart_flowcontrol_t flow_control;
    uart_rx_buf,            //uint8_t *rx_buf;
    uart_tx_buf,            //tx_buf
    sizeof(uart_rx_buf),    //uint16_t rx_buf_size;
    UART_TX_BUF_SIZE,       //tx_buf_size
    0,                      //uint8_t uart_number;
    UART_RX_BUF_SIZE,       //rx_fifo_size
};

#if (1==USB_FOR_CONSOLE) || (1==CAN_FOR_CONSOLE)
static const char_dev_t *uart = NULL;
#else
#define uart CONSOLE_DEV
#endif
#endif // #if (1==UART_FOR_CONSOLE)

#if (1==CAN_FOR_CONSOLE)
#if (1==UART_FOR_CONSOLE) || (1==USB_FOR_CONSOLE)
static const char_dev_t *can = NULL;
#else
#define can CONSOLE_DEV
#endif
#endif

volatile bool event_system_running = false;

///////////////////////////////////////////////////////////////////
////  Stub functions needed when can_default added to project  ////

bool app_can_get_daughter_id(can_identify_t *ci) {
    return false;
}

bool app_can_get_2nd_daughter_id(can_identify_t *ci) {
    return false;
}

bool get_daughter_sw_version(swversion_t *ver) {
    return false;
}

bool get_daughter_hw_ver(hwversion_t *hw) {
    return false;
}

bool get_2nd_daughter_sw_version(swversion_t *ver) {
    return false;
}

bool get_2nd_daughter_hw_ver(hwversion_t *hw) {
    return false;
}

bool app_can_signal_id(void) {
    return false;
}

swversion_t *bootloader_version(void) {
    return NULL;
}

////                                                           ////
///////////////////////////////////////////////////////////////////

bool board_set_console_uart_baudrate(uint32_t baud) {
#if (1==UART_FOR_CONSOLE)
    return uart_set_baud(uart,baud);
#else
    return false;
#endif
}

bool board_reset_console_uart_baudrate(void) {
#if (1==UART_FOR_CONSOLE)
    return uart_set_baud(uart,console_uart_params.baud);
#else
    return false;
#endif
}

//override weak function in consoleb.c
//this function should print banner and then print the first prompt
//
void console_print_banner() {
    hwversion_t hwv         = {0};
    if (!get_hw_version(&hwv)) {
        return;
    }

    console_printf("\n" VERSION_PROJECT_NAME " SW: %u.%u.%u.%u\n",
    file_header.version.major,
    file_header.version.minor,
    file_header.version.revision_num,
    file_header.version.build_num);
    console_printf("Built: %s\n", file_header.build_time);
    console_printf("HW: %u.%u%c\n", hwv.version, hwv.revision, hwv.modification);
    console_printf("%s",console_prompt);
}    //console_print_banner()

#if defined(USE_EXTERNAL_FLASH) && 0!=USE_EXTERNAL_FLASH
static const spansion_spi_flash_init_params_t flash_params = {flash_lock,flash_unlock,NULL,NULL,6000000,0,0};
flash_handle_t     flash_h;
#endif


static void init_data(void) {
    scanner_event.status            = EVENT_INACTIVE;
    scanner_event.exe_time_ms       = 0;
    paired_event.status             = EVENT_INACTIVE;
    paired_event.exe_time_ms        = 0;
}

static void scanner_event_handler(void) {
    uint32_t timeout = xregRead(XREG_BUTTON_LONG_PRESS_TIME_MS) + 100;

    scanner_process();

    if (0 != scanner_isr_time) {
        if (timer_util_is_usec_expired(scanner_isr_time, timeout * MS_TO_US)) {
            scanner_isr_time = 0;
            scanner_event.status = EVENT_INACTIVE;
            dig_pin1_timer_expired();
        }
        else {
            event_set_delay_ms(&scanner_event, 20);
        }        
    }
}

static void paired_event_handler(void) {  
#ifdef SCANNER_ADDED
    if (NRF_SUCCESS == scan_start()) {
        DBG_LOG("BLE_STATE_PAIRED - Start Scan");
    }
    else {
        console_printf("ble_start_scan error\r\n");
    }
#endif
}

#ifdef SCANNER_ADDED
/**@brief Variable length data encapsulation in terms of length and pointer to data. */
typedef struct
{
    uint8_t * p_data;   /**< Pointer to data. */
    uint16_t  data_len; /**< Length of data. */
} data_t;
#endif


BLE_SETEC_DEF(m_muz);                                                         /**< Setec Service instance. */
NRF_BLE_GATT_DEF(m_gatt);                                                       /**< GATT module instance. */

#ifdef SCANNER_ADDED
BLE_SETEC_C_DEF(m_ble_muz_c);                                 /**< Main structure used by the LBS client module. */
BLE_DB_DISCOVERY_DEF(m_db_disc);                                /**< DB discovery module instance. */

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

/**@brief Parameters used when scanning. */
static ble_gap_scan_params_t const m_scan_params =
{
    .active   = 1,
    .interval = SCAN_INTERVAL,
    .window   = SCAN_WINDOW,
    .timeout  = SCAN_TIMEOUT,
    #if (NRF_SD_BLE_API_VERSION <= 2)
        .selective   = 0,
        .p_whitelist = NULL,
    #endif
    #if (NRF_SD_BLE_API_VERSION >= 3)
        .use_whitelist = 0,
    #endif
};

/**@brief Connection parameters requested for connection. */
static ble_gap_conn_params_t const m_connection_param =
{
    (uint16_t)MIN_CONNECTION_INTERVAL,
    (uint16_t)MAX_CONNECTION_INTERVAL,
    (uint16_t)SLAVE_LATENCY,
    (uint16_t)SUPERVISION_TIMEOUT
};
#endif

#ifdef THROUGHPUT_CHANGES
ble_gap_phys_t  phys = { .tx_phys = BLE_GAP_PHY_2MBPS | BLE_GAP_PHY_1MBPS, .rx_phys = BLE_GAP_PHY_2MBPS | BLE_GAP_PHY_1MBPS }; /**< Preferred PHYs. */


char const * phy_str(ble_gap_phys_t phys)
{
    static char const * str[] =
    {
        "1 Mbps",
        "2 Mbps",
        "Coded",
        "Unknown"
    };

    switch (phys.tx_phys)
    {
        case BLE_GAP_PHY_1MBPS:
            return str[0];

        case BLE_GAP_PHY_2MBPS:
        case BLE_GAP_PHY_2MBPS | BLE_GAP_PHY_1MBPS:
        case BLE_GAP_PHY_2MBPS | BLE_GAP_PHY_1MBPS | BLE_GAP_PHY_CODED:
            return str[1];

        case BLE_GAP_PHY_CODED:
            return str[2];

        default:
            return str[3];
    }
}
#endif

#ifndef ADD_SERIALIZATION
/**@brief Function for assert macro callback.
 *
 * @details This function will be called in case of an assert in the SoftDevice.
 *
 * @warning This handler is an example only and does not fit a final product. You need to analyze
 *          how your product is supposed to react in case of 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(DEAD_BEEF, line_num, p_file_name);
}
#endif


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


#ifdef SCANNER_ADDED
/**
 * @brief Parses advertisement data, providing length and location of the field in case
 *        matching data is found.
 *
 * @param[in]  type       Type of data to be looked for in advertisement data.
 * @param[in]  p_advdata  Advertisement report length and pointer to report.
 * @param[out] p_typedata If data type requested is found in the data report, type data length and
 *                        pointer to data will be populated here.
 *
 * @retval NRF_SUCCESS if the data type is found in the report.
 * @retval NRF_ERROR_NOT_FOUND if the data type could not be found.
 */
static uint32_t adv_report_parse(uint8_t type, data_t * p_advdata, data_t * p_typedata)
{
    uint32_t  index = 0;
    uint8_t * p_data;

    p_data = p_advdata->p_data;

    while (index < p_advdata->data_len)
    {
        uint8_t field_length = p_data[index];
        uint8_t field_type   = p_data[index + 1];

        if (field_type == type)
        {
            p_typedata->p_data   = &p_data[index + 2];
            p_typedata->data_len = field_length - 1;
            return NRF_SUCCESS;
        }
        index += field_length + 1;
    }
    return NRF_ERROR_NOT_FOUND;
}


/**@brief Function to start scanning.
 */
static ret_code_t scan_start(void)
{
    (void) sd_ble_gap_scan_stop();

    return sd_ble_gap_scan_start(&m_scan_params);
}


/**@brief Function for handling the advertising report BLE event.
 *
 * @param[in] p_ble_evt  Bluetooth stack event.
 */
static void on_adv_report(const ble_evt_t * const p_ble_evt)
{
    static uint8_t data_buff[32];
    static bool       busy = false;
    ret_code_t err_code;
    data_t     adv_data;
    data_t     dev_name;
    int        n;
    bool       do_connect = false;

    if (busy) return;
    busy = true;
    
    // For readibility.
    ble_gap_evt_t  const * p_gap_evt  = &p_ble_evt->evt.gap_evt;
    ble_gap_addr_t const * peer_addr  = &p_gap_evt->params.adv_report.peer_addr;
    adv_data.data_len = p_gap_evt->params.adv_report.dlen;

    // check length 
    if (adv_data.data_len > 32) {
        busy = false;
        return;
    }

    // make a copy of the data to prevent volatility
    memcpy(data_buff, (uint8_t *)p_gap_evt->params.adv_report.data, adv_data.data_len);

    // Initialize advertisement report for parsing
    adv_data.p_data   = data_buff;

    // Search for advertising names.
    bool name_found = false;
    err_code = adv_report_parse(BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, &adv_data, &dev_name);

    if (err_code != NRF_SUCCESS)
    {
        // Look for the short local name if it was not found as complete.
        err_code = adv_report_parse(BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME, &adv_data, &dev_name);
        if (err_code != NRF_SUCCESS)
        {
            busy = false;
            return;
        }
        else
        {
            name_found = true;
        }
    }
    else
    {
        name_found = true;
    }

    if ( name_found ) {
        dev_name.p_data[dev_name.data_len] = '\0';
        NRF_LOG_INFO("Discovered: %s", dev_name.p_data);
        printf("\r\nDiscovered: %s\r\n", dev_name.p_data);
#if 0
        console_printf("\r\nDiscovered: %s    (", dev_name.p_data);
        for ( n = 0; n < 6; n++ ) {
          console_printf("0x%02x%s", peer_addr->addr[n], (n == 5) ? "" : ":");
        }
        console_printf(")    Length = %d\r\n", adv_data.data_len);
        for ( n = 0; n < adv_data.data_len; n++ ) {
            console_printf("0x%02x ", adv_data.p_data[n]);
            if ( 0 == ((n+1) % 16) ) console_printf("\r\n");
        }
        console_printf("\r\n\r\n");
#endif
    }

    busy = false;

 
    if (name_found)
    {
        if (strlen(m_target_periph_name) != 0)
        {
            if (memcmp(m_target_periph_name, dev_name.p_data, dev_name.data_len )== 0)
            {
                do_connect = true;
            }
        }
    }

    if (do_connect)
    {
        // Initiate connection.
        err_code = sd_ble_gap_connect(peer_addr,
                                      &m_scan_params,
                                      &m_connection_param,
                                      APP_BLE_CONN_CFG_TAG);
        APP_ERROR_CHECK(err_code);
    }

}
#endif


/**@brief Function for the Timer initialization.
 *
 * @details Initializes the timer module.
 */
static void timers_init(void)
{
    // Initialize timer module, making it use the scheduler
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for the GAP initialization.
 *
 * @details This function sets up all the necessary GAP (Generic Access Profile) parameters of the
 *          device including the device name, appearance, and the preferred connection parameters.
 */
static void gap_params_init(void)
{
    ret_code_t              err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;

    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);

    err_code = sd_ble_gap_device_name_set(&sec_mode,
                                          (const uint8_t *)DEVICE_NAME,
                                          strlen(DEVICE_NAME));
    APP_ERROR_CHECK(err_code);

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

    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;

    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the GATT module.
 */
static void gatt_init(void)
{
    ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the Advertising functionality.
 *
 * @details Encodes the required advertising data and passes it to the stack.
 *          Also builds a structure to be passed to the stack when starting advertising.
 */
static void advertising_init(void)
{
    ret_code_t    err_code;
    ble_advdata_t advdata;
    ble_advdata_t srdata;
    uint16_t      muz_uuid = SETEC_SERVICE_UUID[12]<<8 + SETEC_SERVICE_UUID[13]; /**< 16-bit UUID value or octets 12-13 of 128-bit UUID. */

//    ble_uuid_t adv_uuids[] = {{LBS_UUID_SERVICE, m_lbs.uuid_type}};
    ble_uuid_t adv_uuids[] = {{muz_uuid, m_muz.uuid_type}};

    // Build and set advertising data
    memset(&advdata, 0, sizeof(advdata));

    advdata.name_type          = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance = true;
    advdata.flags              = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;


    memset(&srdata, 0, sizeof(srdata));
    srdata.uuids_complete.uuid_cnt = sizeof(adv_uuids) / sizeof(adv_uuids[0]);
    srdata.uuids_complete.p_uuids  = adv_uuids;

    err_code = ble_advdata_set(&advdata, &srdata);
    APP_ERROR_CHECK(err_code);
}

static void auth_write_handler(uint16_t conn_handle, ble_muz_t * p_muz, uint8_t *data, uint16_t len)
{
    muz_auth_char_changed_event(conn_handle, &muz_auth_service_handler, data, len, authentication_in_progress);
}

static void can_write_handler(uint16_t conn_handle, ble_muz_t * p_muz, uint8_t *data, uint16_t len)
{
    muz_can_char_changed_event(conn_handle, &muz_can_service_handler, data, len, authentication_in_progress);
}

/**@brief Function for initializing services that will be used by the application.
 */
static void services_init(void)
{
    ret_code_t     err_code;
    ble_muz_init_t init;

    init.auth_write_handler = auth_write_handler;
    init.can_write_handler = can_write_handler;

    err_code = ble_muz_init(&m_muz, &init);
    APP_ERROR_CHECK(err_code);

    ble_conn_state_init();
}


/**@brief Function for handling a Connection Parameters error.
 *
 * @param[in] nrf_error  Error code containing information about what went wrong.
 */
static void conn_params_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}


/**@brief Function for initializing the Connection Parameters module.
 */
static void conn_params_init(void)
{
    ret_code_t             err_code;
    ble_conn_params_init_t cp_init;

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

    cp_init.p_conn_params                  = NULL;
    cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
    cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
    cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
    cp_init.disconnect_on_fail             = true;
    cp_init.error_handler                  = conn_params_error_handler;

    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for starting advertising.
 */
void advertising_start(void)
{
    ret_code_t           err_code;
    ble_gap_adv_params_t adv_params;

    // Start advertising
    memset(&adv_params, 0, sizeof(adv_params));

    adv_params.type        = BLE_GAP_ADV_TYPE_ADV_IND;
    adv_params.p_peer_addr = NULL;
    adv_params.fp          = BLE_GAP_ADV_FP_ANY;
    adv_params.interval    = APP_ADV_INTERVAL;
    adv_params.timeout     = APP_ADV_TIMEOUT_IN_SECONDS;

    err_code = sd_ble_gap_adv_start(&adv_params, APP_BLE_CONN_CFG_TAG);
    APP_ERROR_CHECK(err_code);
//    bsp_board_led_on(ADVERTISING_LED);
}


/**@brief Function for handling the Connected event.
 *
 * @param[in] p_gap_evt GAP event received from the BLE stack.
 */
static void on_connected(const ble_gap_evt_t * const p_gap_evt)
{
    ret_code_t  err_code;
    uint32_t    periph_link_cnt = ble_conn_state_n_peripherals(); // Number of peripheral links.
 
    if ( 0 == p_gap_evt->conn_handle ) {
#ifdef DEBUG
        console_printf("INVALID: on_connected called with conn_handle = 0.\r\n", p_gap_evt->conn_handle);
#endif
        return;
    }

    NRF_LOG_INFO("Connection with link 0x%x established.", p_gap_evt->conn_handle);
#ifdef DEBUG
    console_printf("Connection with link 0x%x established.\r\n", p_gap_evt->conn_handle);
#endif

#ifdef THROUGHPUT_CHANGES

    if (p_gap_evt->params.connected.role == BLE_GAP_ROLE_PERIPH)
    {
        NRF_LOG_INFO("Connected as a peripheral.");
    }
    else if (p_gap_evt->params.connected.role == BLE_GAP_ROLE_CENTRAL)
    {
        NRF_LOG_INFO("Connected as a central.");
    }

    // Stop scanning and advertising.
    (void) sd_ble_gap_scan_stop();
    (void) sd_ble_gap_adv_stop();

//    bsp_board_leds_off();

//    NRF_LOG_INFO("Discovering GATT database...");
//    err_code  = ble_db_discovery_start(&m_db_disc, p_gap_evt->conn_handle);
//    APP_ERROR_CHECK(err_code);

    if (p_gap_evt->params.connected.role == BLE_GAP_ROLE_PERIPH)
    {
    #if defined(S140)
        err_code = sd_ble_gap_phy_request(p_gap_evt->conn_handle, &phys);
        APP_ERROR_CHECK(err_code);
    #else
////        err_code = sd_ble_gap_phy_update(p_gap_evt->conn_handle, &phys);
///        APP_ERROR_CHECK(err_code);
    #endif
    }
#endif

//    err_code = app_button_enable();
//    APP_ERROR_CHECK(err_code);

    // Update LEDs
//    bsp_board_led_on(CONNECTED_LED);
    if (periph_link_cnt == NRF_SDH_BLE_PERIPHERAL_LINK_COUNT)
    {
//        bsp_board_led_off(ADVERTISING_LED);
    }
    else
    {
        // Continue advertising. More connections can be established because the maximum link count has not been reached.
        advertising_start();
    }

    // Start scanning for peripherals and initiate connection to devices which
    // advertise.

#ifdef THROUGHPUT_CHANGES
#ifdef SCANNER_ADDED
    scan_start();
#endif
#endif

    muz_connected = true;
    muz_connection_handle = p_gap_evt->conn_handle;
#if !BLE_PAIR_ENABLE
    ble_paired_app_event(p_gap_evt);
#else
    ALL_UNUSED(param);
#endif

    // See if this device's MAC address is already known
    if ( !appNvReadBleDevice() ) {
        return;
    }

    if ( !muz_authenticated ) {
        authentication_requested = false;
        authentication_in_progress = true;
        auth_retries = 0;
        authentication_timer = timer_get_timestamp_usec();
        memcpy(&connected_addr, &p_gap_evt->params.connected.peer_addr, sizeof(ble_gap_addr_t));
    }
}


/**@brief Function for handling the Disconnected event.
 *
 * @param[in] p_gap_evt GAP event received from the BLE stack.
 */
static void on_disconnected(ble_gap_evt_t const * const p_gap_evt)
{
    ret_code_t  err_code;
    uint32_t    periph_link_cnt = ble_conn_state_n_peripherals(); // Number of peripheral links.

    console_printf("Connection 0x%x has been disconnected. Reason: 0x%X\n",
                 p_gap_evt->conn_handle,
                 p_gap_evt->params.disconnected.reason);

    if (periph_link_cnt == 0)
    {
//        bsp_board_led_off(CONNECTED_LED);
//        err_code = app_button_disable();
//        APP_ERROR_CHECK(err_code);
    }

    muz_connected = false;
    muz_authenticated = false;
    prev_muz_authenticated = false;
    authentication_requested = false;
    authentication_in_progress = false;

//    if (periph_link_cnt == (NRF_SDH_BLE_PERIPHERAL_LINK_COUNT - 1))
//    {
        // Advertising is not running when all connections are taken, and must therefore be started.
        muz_service_advertise();
//    }
}


/**@brief Function for handling the Read/Write Authorization request event.
 *
 * @param[in] p_ble_evt Event received from the BLE stack.
 */
static void on_authorize_request(ble_evt_t const * p_ble_evt)
{
    ret_code_t                            err_code;
    ble_gatts_evt_rw_authorize_request_t  req;
    ble_gatts_rw_authorize_reply_params_t auth_reply;

    req = p_ble_evt->evt.gatts_evt.params.authorize_request;

    if (req.type != BLE_GATTS_AUTHORIZE_TYPE_INVALID)
    {
        if ((req.request.write.op == BLE_GATTS_OP_PREP_WRITE_REQ)     ||
            (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) ||
            (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
        {
            if (req.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
            {
                auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
            }
            else
            {
                auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_READ;
            }
            auth_reply.params.write.gatt_status = APP_FEATURE_NOT_SUPPORTED;
            err_code = sd_ble_gatts_rw_authorize_reply(p_ble_evt->evt.gatts_evt.conn_handle,
                                                       &auth_reply);
            APP_ERROR_CHECK(err_code);
        }
    }
}


/**@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)
{
#if 0
    ret_code_t err_code;

#if defined(SCANNER_ADDED) || defined(THROUGHPUT_CHANGES)
    // For readability.
    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
#endif

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            on_connected(&p_ble_evt->evt.gap_evt);
            break;

        case BLE_GAP_EVT_DISCONNECTED:
            on_disconnected(&p_ble_evt->evt.gap_evt);
            break;

        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
            // Pairing not supported
            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle,
                                                   BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP,
                                                   NULL,
                                                   NULL);
            APP_ERROR_CHECK(err_code);
            break;

#ifndef S140
        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;
#endif

#ifdef THROUGHPUT_CHANGES
        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
        {
            NRF_LOG_INFO("Connection interval updated: 0x%x, 0x%x.",
                p_gap_evt->params.conn_param_update.conn_params.min_conn_interval,
                p_gap_evt->params.conn_param_update.conn_params.max_conn_interval);
        } break;

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

            NRF_LOG_INFO("Connection interval updated (upon request): 0x%x, 0x%x.",
                p_gap_evt->params.conn_param_update_request.conn_params.min_conn_interval,
                p_gap_evt->params.conn_param_update_request.conn_params.max_conn_interval);
        } break;
#endif

#ifdef SCANNER_ADDED
        case BLE_GAP_EVT_ADV_REPORT:
        {
            on_adv_report(p_ble_evt);
        } break;

        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)
            {
                NRF_LOG_DEBUG("Connection request timed out.");
            }
        } break;
#endif

        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
            // No system attributes have been stored.
            err_code = sd_ble_gatts_sys_attr_set(p_ble_evt->evt.gap_evt.conn_handle, NULL, 0, 0);
            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;

        case BLE_EVT_USER_MEM_REQUEST:
            err_code = sd_ble_user_mem_reply(p_ble_evt->evt.gattc_evt.conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
            on_authorize_request(p_ble_evt);
            break;

#ifdef THROUGHPUT_CHANGES
        case BLE_GAP_EVT_PHY_UPDATE:
        {
            ble_gap_evt_phy_update_t const * p_phy_evt = &p_ble_evt->evt.gap_evt.params.phy_update;

            if (p_phy_evt->status == BLE_HCI_STATUS_CODE_LMP_ERROR_TRANSACTION_COLLISION)
            {
                // Ignore LL collisions.
                NRF_LOG_DEBUG("LL transaction collision during PHY update.");
                break;
            }

            ble_gap_phys_t phys = {0};
            phys.tx_phys = p_phy_evt->tx_phy;
            phys.rx_phys = p_phy_evt->rx_phy;
            NRF_LOG_INFO("PHY update %s. PHY set to %s.",
                         (p_phy_evt->status == BLE_HCI_STATUS_CODE_SUCCESS) ?
                         "accepted" : "rejected",
                         phy_str(phys));
        } break;
#endif

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


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

#ifdef ADD_SERIALIZATION
    /* Initialize SoftDevice.
     * SoftDevice Event IRQ is not scheduled but immediately copies BLE events to the application
     * scheduler queue */
    err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(err_code);

    /* Open serialization HAL Transport layer and subscribe for HAL Transport events. */
    err_code = ser_hal_transport_open(ser_conn_hal_transport_event_handle);
    APP_ERROR_CHECK(err_code);
#else
    err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(err_code);
#endif

    // 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);
}

#ifdef SCANNER_ADDED
/**@brief Function for handling database discovery events.
 *
 * @details This function is callback function to handle events from the database discovery module.
 *          Depending on the UUIDs that are discovered, this function should forward 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_muz_on_db_disc_evt(&m_ble_muz_c, 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);
}
#endif


/**@brief Function for initializing the logging 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 the Power Manager.
 */
void power_manage(void)
{
    ret_code_t err_code = sd_app_evt_wait();
    APP_ERROR_CHECK(err_code);
}


#ifdef THROUGHPUT_CHANGES
void gatt_mtu_set(uint16_t att_mtu)
{
    ret_code_t err_code;

    err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, att_mtu);
    APP_ERROR_CHECK(err_code);

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


static void conn_evt_len_ext_set(bool status)
{
    ret_code_t err_code;
    ble_opt_t  opt;

    memset(&opt, 0x00, sizeof(opt));
    opt.common_opt.conn_evt_ext.enable = status ? 1 : 0;

    err_code = sd_ble_opt_set(BLE_COMMON_OPT_CONN_EVT_EXT, &opt);
    APP_ERROR_CHECK(err_code);
}


void data_len_ext_set(bool status)
{
    uint8_t data_length = status ? (NRF_SDH_BLE_GATT_MAX_MTU_SIZE + L2CAP_HDR_LEN) : (23 + L2CAP_HDR_LEN);
    (void) nrf_ble_gatt_data_length_set(&m_gatt, BLE_CONN_HANDLE_INVALID, data_length);
}


void preferred_phy_set(ble_gap_phys_t * p_phy)
{
#if defined(S140)
    ble_opt_t opts;
    memset(&opts, 0x00, sizeof(ble_opt_t));
    memcpy(&opts.gap_opt.preferred_phys, p_phy, sizeof(ble_gap_phys_t));
    ret_code_t err_code = sd_ble_opt_set(BLE_GAP_OPT_PREFERRED_PHYS_SET, &opts);
    APP_ERROR_CHECK(err_code);
#endif
    memcpy(&phys, p_phy, sizeof(ble_gap_phys_t));
}
#endif


#if defined(USE_I2C) && 0!=USE_I2C
static void startup_i2c( void ) {
    // Initialize the I2C driver
    const nrf_drv_twi_config_t twi_config = {
       .scl                = TWI_SCL_M,           // Setec: GPIO Config done in gpio_init.c
       .sda                = TWI_SDA_M,           // Setec: GPIO Config done in gpio_init.c
       .frequency          = NRF_TWI_FREQ_100K,
       .interrupt_priority = APP_IRQ_PRIORITY_HIGH,
       .clear_bus_init     = false
    };

//    nordic_i2c_master_init(0, &twi_config);
    nordic_i2c_master_init(1, &twi_config);
}
#endif

void do_background_tasks( void ) {

    app_event_check(events);

    muz_manage_connection();

#if defined(USE_EXTERNAL_FLASH) && 0!=USE_EXTERNAL_FLASH
    app_flash_test(&flash_h);
#endif
    
    // If a Fatal Error Occurred requiring a Reset, allow Console 1 second to output debug info before resetting.
    uint64_t start_msec = timer_get_timestamp_msec();
    do {
        console_service();    // This is the normal console service call, called always

        if ( timer_util_is_msec_expired(start_msec, 1000) ) {
            if ( SystemResetPending ) {
                NVIC_SystemReset();
                SystemResetPending = false;
            }
            if ( SerializationRestartPending ) {
              ser_hal_transport_close();
              /* Open serialization HAL Transport layer and subscribe for HAL Transport events. */
              ret_code_t err_code = ser_hal_transport_open(ser_conn_hal_transport_event_handle);
              APP_ERROR_CHECK(err_code);
              SerializationRestartPending = false;
            }
        }
    } while (SystemResetPending || SerializationRestartPending);

#if (defined(CAN_FOR_CONSOLE) && 0!=CAN_FOR_CONSOLE)
    can_tunnel_service();
#endif
}

/** @brief SPI slave driver instance data structure. */
typedef struct
{
    NRF_SPIS_Type * p_reg;          //!< SPIS instance register.
    uint8_t         instance_id;    //!< SPIS instance ID.
    IRQn_Type       irq;            //!< IRQ of the specific instance.
} nrf_drv_spis_t;

nrf_drv_spis_t *get_p(void);

void print_restart_reason(uint32_t restart_flags) {
    console_printf("Last Restart Cause:\r\n");
    if ( 0 == restart_flags ) console_printf("No Reason Recorded.\r\n");
    if ( restart_flags & POWER_RESETREAS_NFC_Msk ) console_printf("Reset due to wake up from System OFF mode by NFC field detect\r\n");
    if ( restart_flags & POWER_RESETREAS_DIF_Msk ) console_printf("Reset due to wake up from System OFF mode when wakeup is triggered from entering into debug interface mode\r\n");
    if ( restart_flags & POWER_RESETREAS_LPCOMP_Msk ) console_printf("Reset due to wake up from System OFF mode when wakeup is triggered from ANADETECT signal from LPCOMP\r\n");
    if ( restart_flags & POWER_RESETREAS_OFF_Msk ) console_printf("Reset due to wake up from System OFF mode when wakeup is triggered from DETECT signal from GPIO\r\n");
    if ( restart_flags & POWER_RESETREAS_LOCKUP_Msk ) console_printf("Reset from CPU lock-up detected\r\n");
    if ( restart_flags & POWER_RESETREAS_SREQ_Msk ) console_printf("Reset from soft reset detected\r\n");
    if ( restart_flags & POWER_RESETREAS_DOG_Msk ) console_printf("Reset from watchdog detected\r\n");
    if ( restart_flags & POWER_RESETREAS_RESETPIN_Msk ) console_printf("Reset from pin-reset detected\r\n");
}

void uart_error_handle(app_uart_evt_t * p_event)
{

    uint8_t				value;
    uint32_t				err_code;
    if (p_event->evt_type == APP_UART_DATA_READY)
      {
          err_code = app_uart_get(&value);
          APP_ERROR_CHECK(err_code);
          err_code = app_uart_put(value);
          APP_ERROR_CHECK(err_code);    
    }
    
    else if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_communication);
    }
    else if (p_event->evt_type == APP_UART_FIFO_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_code);
    }
}

static void uart_muz_init()
{
    uint32_t err_code;
  
  {  const app_uart_comm_params_t comm_params =
      {
          RX_PIN_NUMBER,
          TX_PIN_NUMBER,
          RTS_PIN_NUMBER,
          CTS_PIN_NUMBER,
          UART_HWFC,
          false,
          NRF_UART_BAUDRATE_115200
      };

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

    APP_ERROR_CHECK(err_code);

} 
  static const app_uart_buffers_t comm_params = 
       {
          uart_rx_buf,
          UART_RX_BUF_SIZE,
          uart_rx_buf,
          UART_TX_BUF_SIZE
        };  
          
}

/** UART Initialization */

void app_uart_put_string(const char* s)
{
    uint32_t err_code;
    uint8_t len = strlen(s);
    
    
       
        console_printf("NXP flashing\n");
        nrf_delay_ms(1000);

        nrf_gpio_pin_clear(NXP_BOOT_PIN_NUMBER);
        nrf_gpio_pin_clear(NXP_RESET_PIN_NUMBER);
        nrf_delay_ms(1000);
        nrf_gpio_pin_set(NXP_RESET_PIN_NUMBER);
        nrf_delay_ms(3000);
        nrf_gpio_pin_set(NXP_BOOT_PIN_NUMBER);
        nrf_delay_ms(3000);

        board_set_console_uart_baudrate(115200);

    app_uart_put(*cmd) == "?";     
  //  console_putc(63);
  app_uart_flush(); 

}





/**@brief Function for application main entry.
 */
int main(void)
{
    // Force the counter to be placed into memory
    static volatile int i = 0;

    sd_power_reset_reason_get(&reset_reason);
    sd_power_reset_reason_clr(reset_reason);

    // Initialize.
    leds_init();
    timers_init();
    timer_init();
    log_init();
    nordic_gpio_init(false);

#ifdef ADD_SERIALIZATION
    if (nrf_drv_clock_init() != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    nrf_drv_clock_hfclk_request(NULL);
    while (!nrf_drv_clock_hfclk_is_running())
    {}

    /* Force constant latency mode to control SPI slave timing */
    NRF_POWER->TASKS_CONSTLAT = 1;

    /* Initialize scheduler queue. */
    //lint -save -e666
    APP_SCHED_INIT(SER_CONN_SCHED_MAX_EVENT_DATA_SIZE, SER_CONN_SCHED_QUEUE_SIZE);
    //lint -restore
#endif

#if defined(USE_EXTERNAL_FLASH) && 0!=USE_EXTERNAL_FLASH
    // Initialize the SPI driver
    if (FLASH_RC_OK!=spansion_spi_flash_init(&flash_params,&flash_h)) {
        while(1);
    }
#endif

#if defined(USE_NV) && 1==USE_NV
    /* Initialize NV */
    if (!appNvInit()) {
        while(1);
    }
    i = appNvRead();
    if (0>i) {
        while(1);
    }
#endif
    
    // Initialize xregister values
    xregInit();

    /* Initialize console outputs */

#if (defined(UART_FOR_CONSOLE) && (1==UART_FOR_CONSOLE))
    if(UART_RC_OK!=uart_init(&console_uart_params,&uart)) {
        while(1);
    }
#endif

#if defined(USE_CAN) && 0!=USE_CAN
    app_can_init();
#if (defined(CAN_FOR_CONSOLE) && 0!=CAN_FOR_CONSOLE)
    can_tunnel_init(&can);
#endif
#endif

#if (defined(UART_FOR_CONSOLE) && 0!=UART_FOR_CONSOLE) || (defined(CAN_FOR_CONSOLE) && 0!=CAN_FOR_CONSOLE)
if (!usb_uart_combo_init(can, uart, &CONSOLE_DEV)) {
    while(1);
}
#endif

#if (defined(UART_FOR_CONSOLE) && 0!=UART_FOR_CONSOLE) || (defined(USB_FOR_CONSOLE) && 0!=USB_FOR_CONSOLE) || (defined(CAN_FOR_CONSOLE) && 0!=CAN_FOR_CONSOLE)
    /* Initialize Console - must be after outputs and XREGs*/
    console_init();
    console_initialised = true;
#ifdef DEBUG
    print_restart_reason(reset_reason);
#endif
#endif
    
#if 0!=USE_PWM
    /* Initialize PWM */
    if (!app_pwm_init()) {
        while(1);
    }
#endif

#if defined(USE_I2C) && 0!=USE_I2C
    // Initialize the I2C driver
    startup_i2c();
#endif

    app_scanner_init();
    timer_util_msec_delay(100);

    ble_stack_init();
    gap_params_init();
    gatt_init();
#ifdef SCANNER_ADDED
    db_discovery_init();
#endif
    services_init();
    advertising_init();

#ifdef THROUGHPUT_CHANGES
    gatt_mtu_set(NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
    data_len_ext_set(true);
    conn_evt_len_ext_set(true);
    preferred_phy_set(&phys);
#else
    conn_params_init();
#endif
        
    ble_stack_running = true;
	
    app_event_init();
    event_system_update(events);

    event_system_running = true;

uart_muz_init();
app_uart_put_string("?");
//app_uart_get()
//app_uart_flush();

    // Start execution.
    //console_printf("Multiperipheral example started.\n");
    //advertising_start();

#ifdef SCANNER_ADDED
    // Start scanning for peripherals and initiate connection to devices which
    // advertise.
//    scan_start();
#endif

//nrf_drv_spis_t *m_spis = get_p();
//NRF_SPIS_Type * p_reg = m_spis->p_reg;
//console_printf("PSELSCK = 0x%08x, PSELMOSI = 0x%08x, PSELMISO = 0x%08x, PSELCSN = 0x%08x\r\n", p_reg->PSELSCK, p_reg->PSELMOSI, p_reg->PSELMISO, p_reg->PSELCSN);

    // Enter main loop.
    for (;;)
    {
        if (NRF_LOG_PROCESS() == false)
        {
////            power_manage();   // Disable going to sleep as Serialization commands were not getting through from NXP to Nordic
        }

#ifdef ADD_SERIALIZATION
        /* Process SoftDevice events. */
        app_sched_execute();
        if (nrf_sdh_is_suspended())
        {
            // Resume pulling new events if queue utilization drops below 50%.
            if (app_sched_queue_space_get() > (SER_CONN_SCHED_QUEUE_SIZE >> 1))
            {
                nrf_sdh_resume();
            }
        }

        /* Process received packets.
         * We can NOT add received packets as events to the application scheduler queue because
         * received packets have to be processed before SoftDevice events but the scheduler queue
         * does not have priorities. */
        APP_ERROR_CHECK(ser_conn_rx_process());
#endif

//        NRF_LOG_INFO("%d", ++i);

        do_background_tasks();
    }



}


/**
 * @}
 */

Can anyone suggest where I am going wrong and what is the best way to send and receive commands through UART (app_uart_get/put  or somethings else).

Thanks

Related