Error occuring during bt_gatt_write as central device

Hello,

I have completed a project based on nrf52840 as a peripheral device.

These days, i am expirementing with nrf52840 as a central device. I have successfully scanned advertisement data and established connection on device. Furthermore, i have discovered services/characteristics and reading values from them.

The specific characteristic has write property and permision enable.

The issue occurs when i am trying to write to characteristic,  the bt_gatt_write() returns no error but the write callback function returns err = 3.

I am using zephyrOS.

I appreciate if you could help me to solve this issue.

Thanks in advance guys!

static uint8_t discover_func(struct bt_conn *conn, const struct bt_gatt_attr *attr, struct bt_gatt_discover_params *params)
{
	int i=0;
	int err;
	if (!attr)
	{
		printk("Discover complete\n");
		(void)memset(params, 0, sizeof(*params));
		return BT_GATT_ITER_STOP;
	}
	printk("[ATTRIBUTE] handle %u\n", attr->handle);


	if(!bt_uuid_cmp(discover_params.uuid, BT_UUID_GAP_DEVICE_NAME))
	{
		static uint8_t data[] = {0x0a, 0x0b};
		write_params.data = data;	
		write_params.length = (uint16_t)sizeof(data);
		write_params.handle = attr->handle;
		write_params.func = writeCallback;
		write_params.offset = 0;

		err = bt_gatt_write(conn, &write_params);
		if(err)
		{
			printk("write error!\n");
		}
		else
		{
			printk("write request succeeded\n");
		}	
	}
	
	return BT_GATT_ITER_STOP;
}

Parents Reply Children
  • Yes i found the solution for my issue.

    The above example is wrong.

    First you need to discover the service as well as the characteristic for writing. 

    When you found the characteristic, you need to get the handler (returned value) using the function:

    uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr). Since you have done this process, you should complete the struct bt_gatt_write_params write_params accordingly.
  • Thanks thanosPr! Your solution worked for me as well.

    I had discovered the characteristic and and was attempting to write directly to that handle. After calling bt_gatt_attr_value_handle() on the discovered characteristic attribute then using that returned value handle with bt_gatt_write() the data is written without issue.

    Appreciate the quick response!

  • Hey,

    I was looking for the procedure to do the GATT write. I found this discussion intuitive.

    Should I do it like this?

    		static uint8_t data[] = {0x0a, 0x0b};
    		write_params.data = data;	
    		write_params.length = (uint16_t)sizeof(data);
    		write_params.handle = bt_gatt_attr_value_handle(attr);
    		write_params.offset = 0;
    
    		err = bt_gatt_write(conn, &write_params);
    		if(err)
    		{
    			printk("write error!\n");
    		}
    		else
    		{
    			printk("write request succeeded\n");
    		}

    Thanks,

    Pranathi

Related