Harmony OS 设备开发学习记录(六)-- 通过PWM模块播放音乐
基于hispark wifi套件采用harmony os 2.0全量代码
一、看原理图确定硬件电路
本例采用红绿灯扩展版上的蜂鸣器
注:可以发现由于红绿灯的蜂鸣器与GPIO9相连而核心板上的led也是与GPIO9相连的,所以控制蜂鸣器时核心板板载的led也会发生变化。
二、在源码中建立demo文件
在app下建立pwmdemo文件夹并创建BUILD.gn和pwm_buz_music.c文件
三、编写代码
在pwmdemo/pwm_buz_music.c中写入
#include <stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_pwm.h"
#include "hi_time.h"
// 音符对应的分频系数
static const uint16_t g_tuneFreqs[] = {
0, //40MHz时钟源
38223, // 1 1046.5
34052, // 2 1174.7
30338, // 3 1318.5
28635, // 4 1396.4
25511, // 5 1568
22728, // 6 1760
20249, // 7 1975.5
};
//曲谱音符
static const uint8_t g_scoreNotes[] = {
// 《两只老虎》简谱
1, 2, 3, 1, 1, 2, 3, 1, 3, 4, 5, 3, 4, 5,
5, 6, 5, 4, 3, 1, 5, 6, 5, 4, 3, 1, 1, 5, 1, 1, 5, 1,
};
// 曲谱时值
static const uint8_t g_scoreDurations[] = {
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 4, 4, 8,
3, 1, 3, 1, 4, 4, 3, 1, 3, 1, 4, 4, 4, 4, 8, 4, 4, 8,
};
static void PwmGpioTask(void *arg){
(void)arg;
uint32_t tune;
uint16_t freqDivisor;
uint32_t tuneInterval;
for (size_t i = 0; i < sizeof(g_scoreNotes)/sizeof(g_scoreNotes[0]); i++)
{
tune = g_scoreNotes[i];
freqDivisor = g_tuneFreqs[tune];
tuneInterval = g_scoreDurations[i] * (125 * 1000); // 时间
printf("%d %d %d\r\n", tune, freqDivisor, tuneInterval);
hi_pwm_start(HI_PWM_PORT_PWM0, freqDivisor/2, freqDivisor);
hi_udelay(tuneInterval);
hi_pwm_stop(HI_PWM_PORT_PWM0);
}
}
static void PwmGpioEntry(void){
osThreadAttr_t attr;
hi_gpio_init();
hi_io_set_func(9, HI_IO_FUNC_GPIO_9_PWM0_OUT);
hi_pwm_init(HI_PWM_PORT_PWM0);
hi_pwm_set_clock(PWM_CLK_XTAL);
attr.name = "PwmGpioTask";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = 1024;
attr.priority = 25;
if (osThreadNew(PwmGpioTask, NULL, &attr) == NULL) {
printf("[LedExample] Falied to create LedTask!\n");
}
}
SYS_RUN(PwmGpioEntry);
这里的pwm相关函数用法参考源码
在pwmdemo/BUILD.gn中写入
static_library("pwmdemo") {
sources = [
"pwm_buz_music.c"
]
include_dirs = [
"//utils/native/lite/include",
"//kernel/liteos_m/components/cmsis/2.0",
"//base/iot_hardware/peripheral/interfaces/kits",
"//device/hisilicon/hispark_pegasus/sdk_liteos/include"
]
}
在上级目录的app/BUILD.gn中写入
import("//build/lite/config/component/lite_component.gni")
lite_component("app") {
features = [
"pwmdemo",
]
}
注:为了保证编译通过请修改配置文件
修改device/hisilicon/hispark_pegasus/sdk_liteos/build/config/usr_config.mk
加上
CONFIG_PWM_SUPPORT=y
四、在Linux下使用hb工具进行编译
root@DESKTOP-QAO2AOK:~/harmonyos/code-2.0-canary# hb set
[OHOS INFO] Input code path: .
OHOS Which product do you need? wifiiot_hispark_pegasus
root@DESKTOP-QAO2AOK:~/harmonyos/code-2.0-canary# hb build
如果曾经设置过hb set就不需要再设置了,直接这样就可以了
root@DESKTOP-QAO2AOK:~/harmonyos/code-2.0-canary# hb build
看到success字样即为编译成功
五、将编译好的固件烧录到开发板
将linux中的源码文件夹中的out拷贝到Windows下替换原有out文件夹就可以了,但是要先删除原有out文件夹
打开vscode使用DevEco Device Tool打开源码文件夹
选择对应的开发板型号
这里选择的是hi3861
然后在项目设置中按照实际端口情况进行如下设置
保存项目并打开
点击upload进行烧录,烧录时需要根据提示按下开发板的rst键,稍等片刻,看到success代表烧录成功。
按下rst键重启开发板,可以听到蜂鸣器播放儿歌两只老虎