【rtthread设备】第四篇:pwm设备

一、pwm设备概念

rtthread将pwm设备抽象成rt_device_pwm

二、pwm api

设置pwm的周期和脉冲宽度时间后可以使/失能pwm设备。

//查找pwm设备
/*
name:pwm设备名称
*/
rt_device_t rt_device_find(const char* name);

//设置pwm设备的周期和占空比
/*
device:pwm设备句柄
channel:pwm通道
period:周期
pulse:脉冲宽度时间
*/
rt_err_t rt_pwm_set(struct rt_device_pwm *device,
                        int channel,
                        rt_uint32_t period,
                        rt_uint32_t pulse);

//使能pwm设备
/*
device:pwm设备句柄
channel:通道
*/
rt_err_t rt_pwm_enable(struct rt_device_pwm *device, int channel);

//关闭pwm设备
/*
device:pwm设备句柄
channel:通道
*/
rt_err_t rt_pwm_disable(struct rt_device_pwm *device, int channel);

三、pwm示例

/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-11-25     misonyo      first implementation.
 */
/*
 * 程序清单:这是一个 PWM 设备使用例程
 * 例程导出了 pwm_led_sample 命令到控制终端
 * 命令调用格式:pwm_led_sample
 * 程序功能:通过 PWM 设备控制 LED 灯的亮度,可以看到LED不停的由暗变到亮,然后又从亮变到暗。
*/

#include 
#include 

#define LED_PIN_NUM         57      /* LED PIN脚编号,查看驱动文件drv_gpio.c确定 */
#define PWM_DEV_NAME        "pwm3"  /* PWM设备名称 */
#define PWM_DEV_CHANNEL     4       /* PWM通道 */

struct rt_device_pwm *pwm_dev;      /* PWM设备句柄 */

static int pwm_led_sample(int argc, char *argv[])
{
    rt_uint32_t period, pulse, dir;

    period = 500000;    /* 周期为0.5ms,单位为纳秒ns */
    dir = 1;            /* PWM脉冲宽度值的增减方向 */
    pulse = 0;          /* PWM脉冲宽度值,单位为纳秒ns */

    /* 设置LED引脚脚模式为输出 */
    rt_pin_mode(LED_PIN_NUM, PIN_MODE_OUTPUT);
    /* 拉高LED引脚 */
    rt_pin_write(LED_PIN_NUM, PIN_HIGH);
    
    /* 查找设备 */
    pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
    if (pwm_dev == RT_NULL)
    {
        rt_kprintf("pwm sample run failed! can't find %s device!\n", PWM_DEV_NAME);
        return RT_ERROR;
    }

    /* 设置PWM周期和脉冲宽度默认值 */
    rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);
    /* 使能设备 */
    rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);
    
    while (1)
    {
        rt_thread_mdelay(50);
        if (dir)
        {
            pulse += 5000;      /* 从0值开始每次增加5000ns */
        }
        else
        {
            pulse -= 5000;      /* 从最大值开始每次减少5000ns */
        }
        if (pulse >= period)
        {
            dir = 0;
        }
        if (0 == pulse)
        {
            dir = 1;
        }

        /* 设置PWM周期和脉冲宽度 */
        rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);
    }
}
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(pwm_led_sample, pwm sample);

你可能感兴趣的:(rtthread设备,rtos)