一般情况下,我们的手机在息屏状态,当收到消息处于未读状态时,会有呼吸灯提醒,这次有幸抽中XR806开发板的试用,经过九牛二虎之力终于将环境搞好了,中间遇到各种问题,在我的另一篇文章中已详细描述--【X806开发板试用】WSL环境搭建问题及解决措施,本文主要介绍使用PWM模块模拟手机呼吸灯功能
1、实现思路
思路比较简单,就是将接有LED灯的IO配置为PWM输出,然后控制PWM的占空比随时间变化,不同的占空比对应不用的灯光亮度,适当调整变化周期,从而实现想要的呼吸灯功能;
从原理图看,LE灯接在PA21引脚(如下图)
根据XR806手册中引脚复用功能配置,该IO对应PWM2
PWM配置可以参考自带例程
/home/jackie/device/xradio/xr806/ohosdemo/iot_peripheral/src/test_pwm.c
初始化完成后,应用层可以按自己的思路控制PWM的占空比,实现呼吸灯(详见实现代码)。
2、实现代码
在/home/jackie/device/xradio/xr806/ohosdemo路径下新建一个文件夹led_breath,目录结构如下
/home/jackie/device/xradio/xr806/ohosdemo/led_breath/
├── BUILD.gn
└── main.c
BUILD.gn文件内容
import("/home/jackie/device/xradio/xr806/liteos_m/config.gni")
static_library("app_led_breath"){
configs = []
sources = [
"main.c",
]
cflags = board_cflags
include_dirs = board_include_dirs
include_dirs +=[
"/home/jackie/base/iot_hardware/peripheral/interfaces/kits",
"/home/jackie/kernel/liteos_m/kernel/arch/include",
]
}
main.c文件内容
#include <stdio.h>
#include "ohos_init.h"
#include "kernel/os/os.h"
#include "iot_gpio.h"
#include "iot_pwm.h"
static OS_Thread_t g_main_thread;
#define GPIO_ID_PA21 21
#define GPIO_ID_PA11 11
static void MainThread(void *arg)
{
// unsigned int pwm_delay_cnt = 0;
unsigned int pwm_channl = 2;
unsigned int pwm_duty_ratio = 30;
unsigned int pwm_freq = 2000;
unsigned int dir_add_flag = 0;
printf("pwm test ch%d start\r\n", pwm_channl);
printf("pwm ch%d output duty ratio = %d, freq = %d\r\n", pwm_channl,
pwm_duty_ratio, pwm_freq);
IoTPwmInit(pwm_channl);
IoTPwmStart(pwm_channl, pwm_duty_ratio, pwm_freq);
while(1)
{
if(pwm_duty_ratio >= 99)
{
dir_add_flag = 0;
}
else if(pwm_duty_ratio <= 0)
{
dir_add_flag = 1;
OS_MSleep(1000);//灭500ms
}
if(dir_add_flag)
{
pwm_duty_ratio ++;
}
else
{
pwm_duty_ratio --;
}
IoTPwmStart(pwm_channl, pwm_duty_ratio, pwm_freq);
OS_MSleep(5);
printf("freq=%d,duty=%d\n", pwm_freq, pwm_duty_ratio);
}
}
void led_breathMain(void)
{
printf("Ctrl led start\r\n");
if(OS_ThreadCreate(&g_main_thread, "MainThread", MainThread, NULL, OS_THREAD_PRIO_APP, 4 * 1024) != OS_OK)
{
printf("[ERR] Create MainThread Failed\r\n");
}
}
SYS_RUN(led_breathMain);
3、常规操作及注意事项
3.1 运行后会反复打印max_duty_ratio =
可以将该打印屏蔽掉,路径 /home/jackie/device/xradio/xr806/adapter/hals/iot_hardware/wifiiot_lite/iot_pwm.c,如下截图