nRF Peripheral NUS sample, receiving message from nRF Toolbox UART service

Hi, I have been experimenting with the peripheral NUS sample program with an nRF9160 DK which has the nRF52840 Bluetooth chip.

The sample program sends simple Hello World responses which I am able to receive using nRF Toolbox for Android. My intention is to modify the code so that I can send a message from nRF Toolbox, receive the message and then send a response back. There is the following function already defined in main.c:

static void received(struct bt_conn *conn, const void *data, uint16_t len, void *ctx)
{
	char message[CONFIG_BT_L2CAP_TX_MTU + 1] = "";

	ARG_UNUSED(conn);
	ARG_UNUSED(ctx);

	memcpy(message, data, MIN(sizeof(message) - 1, len));
	printk("%s() - Len: %d, Message: %s\n", __func__, len, message);
}

However, I have not been successful in getting the message to the pointer 'data', or at least getting a message other than an empty string to the pointer, even though the printk command prints the message totally normally. I am also wondering where is the 'message' string operated such that it is no longer an empty string?

I would like some clarity with this. Is there an example code on how to use this function, or maybe some other function, so the messages sent from nRF Toolbox UART service can be received?

  • Hi,

    If you want to modify the sample so it sends back a response when receiving data, you can try something like this:

    peripheral_nus -> main.c

    struct nus_rx_data {
    	char message[CONFIG_BT_L2CAP_TX_MTU + 1];
    };
    
    /* 
     * Create message queue to pass NUS rx data to the main thread 
     */
    K_MSGQ_DEFINE(nus_msgq, sizeof(struct nus_rx_data), 1, 1);
    
    ....
    
    static void received(struct bt_conn *conn, const void *data, uint16_t len, void *ctx)
    {
    	int err;
    	struct nus_rx_data rx_data;
    
    	ARG_UNUSED(conn);
    	ARG_UNUSED(ctx);
    
    	memset(rx_data.message, 0x0, sizeof(rx_data.message));
    	memcpy(rx_data.message, data, MIN(sizeof(rx_data.message) - 1, len));
    	
    	printk("%s() - Len: %d, Message: %s\n", __func__, len, rx_data.message);
    
    	/* Forward received NUS RX data to main thread */
    	err = k_msgq_put(&nus_msgq, &rx_data, K_NO_WAIT);
    	if (err) {
    		printk("k_msgq_put() failed. (err %d)\n", err);
    	}
    }
    
    
    ....
    
    int main(void) 
    {
        ...
        while (true) {
    
    		/* Wait for NUS Command */
    		k_msgq_get(&nus_msgq, &rx_data, K_FOREVER);
    
    		//TODO: process received command?
    
    		/* Send back response */
    		err = bt_nus_send(NULL, rx_data.message, strlen(rx_data.message));
    		printk("Data send - Result: %d\n", err);
    
    		if (err < 0 && (err != -EAGAIN) && (err != -ENOTCONN)) {
    			return err;
    		}
    	}
    

    Best regards,

    Vidar

Related