本帖最后由 fxyc87 于 2021-2-19 10:47 编辑
上一个例子【【树莓派Pico测评】-制作红外体温计( I2C接口测试+MLX90614)】
这次再来玩一玩PWM呼吸灯
micropython的PWM就不发了,太简单了,还是用SDK玩
直接上代码,代码注释我写的很清楚,(申明:我的 【树莓派Pico测评 】均为原创)
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pwm.h"
#define PIN_LED 25
#define PWM_M 4 //PWM模块号
#define PWM_top 10000 //pwm周期基准值
void PWM_Change(uint16_t value); //修改PWM占空比,100%值是10000
int main()
{
stdio_init_all();
//设置LED 25号引脚功能,PWM
gpio_set_function(PIN_LED, GPIO_FUNC_PWM);
//读取LED这个引脚是用的PWM A/B通道
//芯片共有8个PWM模块,每个模块分别有A/B两个通道,共16个PWM
//手册中 25脚是 PWM4-B
//通道4,周期 设置寄存器TOP值
pwm_set_wrap(PWM_M, PWM_top); //频率计算125M/(10000+1)=12,498hz 实测12.4988khz
//通道 占空比 设置寄存器CC值
//pwm_set_chan_level(PWM_M, PWM_CHAN_B, 2000);
PWM_Change(PWM_top/5);
//开启PWM
pwm_set_enabled(PWM_M, true);
sleep_ms(2000);
//闪烁频率约2S
int dir=0; //0从弱到亮 1从亮到暗
int step=PWM_top/50;
int value=0;
while(1){
puts("sleep led\n");
for(int i=0;i<50;i++)
{
PWM_Change(value);
sleep_ms(20); //2000/50
value+=(dir?-step:step);
}
dir=!dir;
}
return 0;
}
__inline void PWM_Change(uint16_t value){ //修改PWM占空比,100%值是10000
//通道 占空比 设置寄存器CC值
//pwm_set_chan_level(Channel, PWM_CHAN_B, 2000);
*(&pwm_hw->slice[PWM_M].cc)=value<<16;
//通道B是高16位,通道A是低16位
}
如果无法编译,则需要修改文件MAKE文件,以下是详细文件
# Generated Cmake Pico project file
cmake_minimum_required(VERSION 3.13)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
# initalize pico_sdk from installed location
# (note this can come from environment, CMake cache etc)
set(PICO_SDK_PATH "D:/ZL/RP2040/pico-sdk")
# Pull in Pico SDK (must be before project)
include(pico_sdk_import.cmake)
project(pwm_test2 C CXX ASM)
set(PICO_CXX_ENABLE_EXCEPTIONS 1)
set(PICO_CXX_ENABLE_RTTI 1)
# Initialise the Pico SDK
pico_sdk_init()
# Add executable. Default name is the project name, version 0.1
add_executable(pwm_test2 pwm_test2.c )
pico_set_program_name(pwm_test2 "pwm_test2")
pico_set_program_version(pwm_test2 "0.1")
pico_enable_stdio_uart(pwm_test2 1)
pico_enable_stdio_usb(pwm_test2 1)
# Add the standard library to the build
target_link_libraries(pwm_test2 pico_stdlib hardware_pwm)
pico_add_extra_outputs(pwm_test2)
PWM手册相关图片
PWM LED引脚位置
CC寄存器说明
实测20%占空比波形
实际视频