Contributed by Dachuizi, organized by Ai-Thinker
[WB2 BLE Learning-3] Implementing Connection Status Indication
The previous articles introduced the basics of BLE and callback functions. This time we'll implement BLE-controlled LEDs.
Indicate the BLE connection status through the blinking of the blue LED;
Control the on/off of the red LED after connecting;
Creating the Project
Here, directly copy the ble_slave project in the /Ai-Thinker-WB2/applications/bluetooth directory and rename it to ble_slave_led.
Compile and flash it to verify the project works; then add the required features on top of this project;
Adding the LED Blinking Task
Add two files in the /Ai-Thinker-WB2/applications/bluetooth/ble_slave_led/ble_slave_led directory:
led.c and led.h
led.h
Click to expand full code
#ifndef __LED_H_
#define __LED_H_
void blink_test(void *param);
#endif // !__LED_H_led.c
Click to expand full code
#include <stdio.h>
#include <string.h>
#include <FreeRTOS.h>
#include <task.h>
#include <bl_gpio.h>
#include "led.h"
#define GPIO_LED_PIN 3
void blink_test(void *param)
{
uint8_t value = 1;
while (1)
{
bl_gpio_enable_output(GPIO_LED_PIN, 0, 0);
printf("Turning the LED %s! \r\n", value == 1 ? "ON" : "OFF");
bl_gpio_output_set(GPIO_LED_PIN, value);
value = !value;
vTaskDelay(1000);
}
}Add the LED blinking task in the main.c file:
Click to expand full code
void main()
{
bl_sys_init();
puts("[OS] proc_main_entry task...\r\n");
xTaskCreate(TaskUart, "TaskUart", 2048, NULL, 15, NULL);
xTaskCreate(proc_main_entry, (char *)"main_entry", 1024, NULL, 15, NULL);
xTaskCreate(blink_test, "blink", 1024, NULL, 15, NULL);
}After this step, we'll have a BLE slave program with a blinking blue LED.
Next, we add the LED status indication code:
When the BLE connection succeeds, the LED stops blinking; when disconnected, the LED starts blinking again;
Adding LED Status Indication Code
Since the demo uses FreeRTOS, the LED blinking program added in the previous step was created as a FreeRTOS task. It needs to be implemented through inter-task communication: after a successful connection, a message is sent to the blinking task to pause blinking; if disconnected, a message is sent to start blinking again;
When the LED blinking task was created in the previous step, no task handle was specified, so there was no way to control the task's running state.
Declaring the Task Handle
Declare a task handle variable in led.h and use the handle to control the task's running state.

Creating the Task with the Handle Specified
According to the FreeRTOS API, when creating a task, the last parameter is the handle of the created task;

Using the Handle to Control the Task
Suspend the task in the connection-success callback

Resume the task in the disconnection callback

Adding LED Control Code
Add the LED control code:

Implement the LED control function in the characteristic write callback;

