Zephyr
This sample code shows how to use a slider component in a Zephyr project.
prj.conf
# Bluetooth
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_DEVICE_NAME="Bleboard"
CONFIG_BT_MAX_CONN=1
# Logging / console
CONFIG_SERIAL=y
CONFIG_CONSOLE=y
CONFIG_LOG=y
CONFIG_LOG_DEFAULT_LEVEL=3main.c
#include <zephyr/kernel.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/gatt.h>
#include <zephyr/sys/printk.h>
static struct bt_uuid_128 custom_service_uuid = BT_UUID_INIT_128(
BT_UUID_128_ENCODE(0x12345678, 0x1234, 0x5678, 0x1234, 0x56789abcdef0ULL)
);
static struct bt_uuid_128 custom_char_uuid = BT_UUID_INIT_128(
BT_UUID_128_ENCODE(0x12345678, 0x1234, 0x5678, 0x1234, 0x56789abcdef1ULL)
);
static uint8_t slider_value = 0;
/* Read callback: return current slider_value */
static ssize_t read_slider(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
const uint8_t *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset,
value, sizeof(*value));
}
/* Write callback: update slider_value from central */
static ssize_t write_slider(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
const void *buf, uint16_t len,
uint16_t offset, uint8_t flags)
{
if (offset != 0 || len < 1) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
const uint8_t *data = buf;
slider_value = data[0]; // 0–255 from UI slider
printk("New slider value from central: %u\n", slider_value);
/* If you later want notifications, you’d call
* bt_gatt_notify(conn, attr, &slider_value, sizeof(slider_value));
* here (and add NOTIFY to props + CCCD).
*/
return len;
}
/* GATT service definition */
BT_GATT_SERVICE_DEFINE(custom_svc,
BT_GATT_PRIMARY_SERVICE(&custom_service_uuid.uuid),
BT_GATT_CHARACTERISTIC(&custom_char_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_slider, write_slider, &slider_value),
);
/* Advertising data: flags + our custom service UUID */
static const struct bt_data ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA_BYTES(BT_DATA_UUID128_ALL,
BT_UUID_128_ENCODE(0x12345678, 0x1234, 0x5678, 0x1234,
0x56789abcdef0ULL)),
};
void main(void)
{
int err;
printk("Simple custom BLE slider (Zephyr)\n");
err = bt_enable(NULL);
if (err) {
printk("Bluetooth init failed (err %d)\n", err);
return;
}
printk("Bluetooth initialized, starting advertising...\n");
err = bt_le_adv_start(BT_LE_ADV_CONN, ad, ARRAY_SIZE(ad), NULL, 0);
if (err) {
printk("Advertising failed to start (err %d)\n", err);
return;
}
printk("Advertising started\n");
while (1) {
/* Value is driven by central writes; nothing to do here */
k_sleep(K_MSEC(250));
}
}
Last updated on