Zephyr学习之PWM方式驱动LED灯记录
前言
- 继Zephyr学习之点亮LED文章。
- 本次使用的示例工程blinky_pwm
- 驱动的引脚为PF9
工程复制并打开项目
![]()
参考提供的设备树文件的PWM节点编写规则
![]()
![]()
![]()
找到我们这边使用的pf9对应的引脚定义
![]()
编写设备树覆盖配置文件
/{// 选择系统控制台和 shell UART 设备chosen{// 指定系统控制台使用 usart1zephyr,console=&usart1;// 指定 shell UART 使用 usart1zephyr,shell-uart=&usart1;};// GPIO LED 配置节点leds{// 兼容性字符串,表示使用 GPIO LED 驱动compatible="gpio-leds";// 第一个 LED 配置led0:led0{// 配置 GPIO 引脚为 PF9(GPIOF 端口第 9 号引脚),高电平有效gpios=<&gpiof9GPIO_ACTIVE_HIGH>;// PF9// 设置 LED 的标签名称label="User LED0";};// 第二个 LED 配置led1:led1{// 配置 GPIO 引脚为 PF10(GPIOF 端口第 10 号引脚),高电平有效gpios=<&gpiof10GPIO_ACTIVE_HIGH>;// PF10// 设置 LED 的标签名称label="User LED1";};};// PWM LED 配置节点pwmleds{// 启用 PWM LED 设备status="okay";// 兼容性字符串,表示使用 PWM LED 驱动compatible="pwm-leds";// PWM 控制的 LED 配置pwm_led0:pwm_led0{// 配置 PWM 属性:引用 PWM 设备、通道号、周期、极性// &pwm14: 引用 PWM 设备// 1: 使用通道 1// PWM_MSEC(100): 设置周期为 100 毫秒// PWM_POLARITY_INVERTED: 设置为反向极性pwms=<&pwm141PWM_MSEC(100)PWM_POLARITY_INVERTED>;// 设置 PWM LED 的标签名称label="PWM LED0";};};// 别名定义,简化设备引用aliases{// 将 uart0 映射到 usart1uart0=&usart1;// 将 led0 映射到 led0led0=&led0;// 将 led1 映射到 led1led1=&led1;// 将 pwmled0 映射到 pwm_led0pwmled0=&pwm_led0;};};&pinctrl{tim14_ch1_pf9:tim14_ch1_pf9{pinmux=<STM32_PINMUX('F',9,AF9)>;};};// 串口1&usart1{pinctrl-0=<&usart1_tx_pa9&usart1_rx_pa10>;pinctrl-names="default";current-speed=<115200>;status="okay";};// 定时器&timers14{status="okay";pwm14:pwm{status="okay";pinctrl-0=<&tim14_ch1_pf9>;pinctrl-names="default";};};
注意
![]()
编写测试函数
/* * Copyright (c) 2016 Intel Corporation * Copyright (c) 2020 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 *//** * @file Sample app to demonstrate PWM. */#include<zephyr/kernel.h>#include<zephyr/sys/printk.h>#include<zephyr/device.h>#include<zephyr/drivers/pwm.h>#include<zephyr/drivers/gpio.h>#include"autoconf.h"staticconststructpwm_dt_specpwm_led0=PWM_DT_SPEC_GET(DT_ALIAS(pwmled0));intmain(void){uint32_tmax_period=0;uint32_tperiod;uint8_tdir=0U;intret;if(!pwm_is_ready_dt(&pwm_led0)){printk("Error: PWM device %s is not ready\n",pwm_led0.dev->name);return0;}uint32_tpulse_width=0;max_period=1000;pwm_set_dt(&pwm_led0,max_period,pulse_width);while(1){ret=pwm_set_dt(&pwm_led0,max_period,pulse_width);if(ret){printk("Error %d: failed to set pulse width\n",ret);}printk("Using pulse_width %d\n",pulse_width);if(dir==0){if(pulse_width<max_period){pulse_width++;}else{dir=1;}}else{if(pulse_width>0){pulse_width--;}else{dir=0;}}k_sleep(K_MSEC(5U));}return0;}
测试结果
![]()
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1195823.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!