Create a BLE Peripheral Project:
Start by creating a new C++ project for the Raspberry Pi Pico W. Here’s an example of how you can set up a simple BLE peripheral which sets up a BLE GATT server on the Pico W to send data.
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "hardware/gpio.h"
#include "btstack.h"
static btstack_packet_callback_registration_t hci_event_callback_registration;
static const uint16_t gatt_service_uuid = 0x181D;
static const uint16_t gatt_characteristic_uuid = 0x2A19;
static uint8_t adv_data[] = {
0x02, 0x01, 0x06,
0x0B, 0x09, 'P', 'i', 'c', 'o', 'W', '-', 'B', 'L', 'E',
0x03, 0x03, 0x1D, 0x18
};
static uint8_t value = 42;
static int att_read_callback(hci_con_handle_t connection_handle, uint16_t attribute_handle,
uint16_t offset, uint8_t * buffer, uint16_t buffer_size) {
if (buffer) {
buffer[0] = value;
}
return sizeof(value);
}
static int att_write_callback(hci_con_handle_t connection_handle, uint16_t attribute_handle,
uint16_t transaction_mode, uint16_t offset, const uint8_t * buffer, uint16_t buffer_size) {
if (buffer_size == 1) {
value = buffer[0];
}
return 0;
}
void setup_gatt_server() {
static const uint8_t gatt_service[] = {
0x09, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x04, 0x00,
0x00, 0x00, 0x00, 0x18, 0x1D, 0x00
};
static const uint8_t gatt_characteristic[] = {
0x08, 0x00, 0x00, 0x02, 0x00, 0x19, 0x2A, 0x02,
0x00, 0x01, 0x00, 0x19, 0x2A, 0x08, 0x00
};
static uint16_t att_handle = 0x0001;
att_server_init(att_read_callback, att_write_callback);
att_db_util_add_service_uuid16(gatt_service_uuid);
att_db_util_add_characteristic_uuid16(gatt_characteristic_uuid, ATT_PROPERTY_READ | ATT_PROPERTY_WRITE, ATT_SECURITY_NONE, &att_handle, sizeof(value), &value);
}
void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
if (packet_type == HCI_EVENT_PACKET && hci_event_packet_get_type(packet) == HCI_EVENT_LE_META) {
if (hci_event_le_meta_get_subevent_code(packet) == HCI_SUBEVENT_LE_CONNECTION_COMPLETE) {
printf("Connected\n");
}
}
}
int main() {
stdio_init_all();
if (cyw43_arch_init()) {
printf("Failed to initialize\n");
return -1;
}
l2cap_init();
sm_init();
setup_gatt_server();
hci_event_callback_registration.callback = &packet_handler;
hci_add_event_handler(&hci_event_callback_registration);
hci_power_control(HCI_POWER_ON);
gap_advertisements_set_params(0x0800, 0x0800, 0x00, 0x00, 0x00, 0x00, 0x07);
gap_advertisements_set_data(sizeof(adv_data), adv_data);
gap_advertisements_enable(1);
while (true) {
cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, 1);
sleep_ms(1000);
cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, 0);
sleep_ms(1000);
}
return 0;
}
This C++ code initializes the Pico W, sets up BLE advertising, and sends a simple “Hello from Pico W” message whenever a device connects.