3.1. PWM - 呼吸灯

本 demo 基于 PWM 外设轮询模式编写。

3.1.1. 硬件连接

本 demo 基于BL706_IOT开发板,连接方式如下

   GPIO function         GPIO pin
----------------------------------
    PWM_CH2      <-->     GPIO22

3.1.2. 软件实现

  • 软件代码见 examples/pwm/pwm_breath_led

1
2
#define BSP_PWM_CLOCK_SOURCE  ROOT_CLOCK_SOURCE_XCLK
#define BSP_PWM_CLOCK_DIV  1
  • 配置 PWM 设备时钟源,见 bsp/board/bl706_iot/clock_config.h

1
#define CONFIG_GPIO22_FUNC GPIO_FUN_PWM
  • 配置 PWM 设备复用引脚,见 bsp/board/bl706_iot/pinmux_config.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#define BSP_USING_PWM_CH2

#if defined(BSP_USING_PWM_CH2)
#ifndef PWM_CH2_CONFIG
#define PWM_CH2_CONFIG \
{   \
    .ch = 2, \
    .frequency = 1000000, \
    .dutycycle = 0, \
    .it_pulse_count = 0,\
}
#endif
#endif
  • 使能 BSP_USING_PWM_CH2 并配置 PWM 设备配置,见 bsp/board/bl706_iot/peripheral_config.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
pwm_register(PWM_CH2_INDEX, "led_breath");

struct device *led_breath = device_find("led_breath");

if (led_breath) {
    PWM_DEV(led_breath)->period = 32; //frequence = 32M/1/32 = 1Mhz
    PWM_DEV(led_breath)->threshold_low = 16;
    PWM_DEV(led_breath)->threshold_high = 32;
    device_open(led_breath, DEVICE_OFLAG_STREAM_TX);
    pwm_channel_start(led_breath);
}
  • 首先调用 pwm_register 函数注册 PWM 设备的一个通道,当前注册 PWM_CH2

  • 然后通过 find 函数找到设备对应的句柄,保存于 led_breath 句柄中

  • 设置 PWM_CH2 的频率为 1Mhz,占空比为50%

  • 使用 device_open 以轮询模式来打开 led_breath 设备

1
2
3
4
5
6
7
8
9
    for (pwm_cfg.threshold_high = 0; pwm_cfg.threshold_high <= 32; pwm_cfg.threshold_high++) {
        device_control(led_breath, DEVICE_CTRL_PWM_DUTYCYCLE_CONFIG, &pwm_cfg);
        bflb_platform_delay_ms(50);
    }

    for (pwm_cfg.threshold_high = 32; 0 <= pwm_cfg.threshold_high && pwm_cfg.threshold_high <= 32; pwm_cfg.threshold_high--) {
        device_control(led_breath, DEVICE_CTRL_PWM_DUTYCYCLE_CONFIG, &pwm_cfg);
        bflb_platform_delay_ms(50);
    }
  • 使用 device_contorl 函数,配合 DEVICE_CTRL_PWM_DUTYCYCLE_CONFIG 指令,可以修改当前 PWM 通道的占空比。

3.1.3. 编译和烧录

1
2
 $ cd <sdk_path>/bl_mcu_sdk
 $ make BOARD=bl706_iot APP=pwm_breath_led

3.1.4. 实验现象

pwm breath led!

见视频展示: