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

nrf UART app receive value sent from uart app

Hi, I am using the nrf uart app to communicate with a smart phone and the NRF52. I am trying to detect whenever it is sent a value between 0 and 60 from the phone, and save it to an int. I know that I get a callback from the function nus_data_handler whenever something is received on the nrf, but I dont really know how to convert that data to type int.

(I am using the smart phone app NRF UART)

-Erblin

  • 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 >= (BLE_NUS_MAX_DATA_LEN)))
            {
    						
                err_code = ble_nus_string_send(&m_nus, data_array, index);
                if (err_code != NRF_ERROR_INVALID_STATE)
                {
                    APP_ERROR_CHECK(err_code);
               ......
    

    I see that this function runs through the array of characters, till it gets a new line \n or is at maximum data length. How am i able to check if this array of characters contains a number between 0 and 60, and then save it to a type int?

  • One solution to store the number sent from the phone, could be something like this:

    static void nus_data_handler(ble_nus_t * p_nus, uint8_t * p_data, uint16_t length)
    {
        uint32_t myNumber = 0;
        for (uint32_t i = 0; i < length; i++)
        {
            while (app_uart_put(p_data[i]) != NRF_SUCCESS);
            myNumber = myNumber + ((p_data[i]-'0')*pow(10,length-i-1));
        }
        while (app_uart_put('\r') != NRF_SUCCESS);
        while (app_uart_put('\n') != NRF_SUCCESS);
        printf("myNumber is: %d\n",myNumber);
    }
    

    You will need to add #include "math.h" for the pow()-function.

  • uart_event_handle(..) is used to send data to the phone, while nus_data_handler(..) is used to receive data sent from the phone.

  • Thank you for answering, my code is now working :)

Related