内核定时器

1.驱动代码

#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/ide.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/errno.h> 
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <asm/mach/map.h>
#include <linux/timer.h>
#include <linux/jiffies.h>

#define TIMER_CNT       1
#define TIMER_NAME      "timerDev"
#define LEDOFF          0            /* 关灯 */
#define LEDON           1            /* 开灯 */

/* timer设备结构体 */
struct timer_dev{
    dev_t           devid;          /* 设备号 */
    struct cdev     cdev;           /* 字符设备 */
    struct class    *class;         /* 类 */
    struct device   *device;        /* 设备 */
    int             major;          /* 注设备号 */
    int             minor;          /* 次设备号 */
    struct device_node *nd;         /* 设备节点 */
    int             led_gpio;       /* 设备树里面的编号 */

    struct timer_list timer;        /* 设备里面定义一个定时器 */
};

struct timer_dev timerDev; /* 定义LED结构体 */

/* 初始化led */
static int led_init(struct timer_dev *dev)
{
    int ret = 0;

    /* 1. 获取设备节点 */
    dev->nd = of_find_node_by_path("/gpioled");
    if( dev->nd == NULL){
        ret = -EINVAL;
        printk("gpioled node can not found!\r\n");
        goto fail_findnd;
    }

    /* 2. 获取设备所对应的gpio */
    /* 注意第三个参数,因为只有一个索引,所以是0 */
    dev->led_gpio = of_get_named_gpio(dev->nd, "led-gpios", 0);
    if( dev->led_gpio < 0) {
        printk("Can't find led gpio \r\n");
        ret = -EINVAL;
        goto fail_findnd;
    }
    printk("Led gpio num = %d. \r\n", dev->led_gpio);
    
    /* 3. 获取到IO之后,申请IO */
    /* 作用是申请之后,就能知道该IO是否被其他函数占用 */
    /* 如果申请失败,说明被战用啦 */
    /* 解决方法:1.搜索所需管脚 2.在搜索复用管脚,例如 &gpio1 3 */
    ret = gpio_request(dev->led_gpio, "led-gpio");
    if(ret) {
        printk("Failed to request the led gpio! \r\n");
        ret = -EINVAL;
        goto fail_findnd;
    }

    /* 4. 使用IO */
    ret = gpio_direction_output(dev->led_gpio, 1); /* 设置输出,默认高电平不点亮 */
    if(ret < 0){
        printk("Failed to set input or output! \r\n");
        goto fail_set_output;
    }

    /* 5. 输出低电平,点亮LED */
    gpio_set_value(dev->led_gpio, 0);

    return 0;

/* 错误处理 */
fail_set_output:
    gpio_free(dev->led_gpio);
fail_findnd:
    return ret;
}

/* 定时器处理函数 */
static void timer_func(unsigned long arg)
{
    /* 先取得函数传递的参数 */
    struct timer_dev *dev =(struct timer_dev *)arg; 
    static int sta = 1;

    sta = !sta;
    gpio_set_value(dev->led_gpio, sta);

    /* 这里是再加500ms,每进一次中断就会把中断时间提升500ms,这样可以一直运行 */
    mod_timer(&dev->timer, jiffies + msecs_to_jiffies(500));
}

/* 初始化定时器 */
static void mytimer_init(void)
{
    /* 初始化定时器 */
    init_timer(&timerDev.timer);
    /* 定义定时器的中断函数 */
    timerDev.timer.function = timer_func;
    /* 函数传递的参数 */
    timerDev.timer.data = (unsigned long)&timerDev;
    /* 定义定时器的周期 */
    /* 当前系统定时+500ms周期 */
    /* 设定好了之后,过了500ms之后就会进入function */
    timerDev.timer.expires = jiffies + msecs_to_jiffies(500);
    /* 添加定时器 */
    add_timer(&timerDev.timer);
}

static void led_switch(struct timer_dev *dev, u8 sta)
{
    if(sta == LEDON) {
        gpio_set_value(dev->led_gpio, 0);
    }else if(sta == LEDOFF) {
        gpio_set_value(dev->led_gpio, 1);
    } else {
        printk("Error Number! \r\n");
    }
}

static int timer_open(struct inode *inode, struct file *filp)
{
    filp->private_data = &timerDev;
    return 0;
}

static int timer_release(struct inode *inode, struct file *filp)
{
    //struct timer_dev *dev = (struct timer_dev *)filp->private_data;
    return 0;
}

static ssize_t timer_write(struct file *filp, const char __user *buf, size_t count, loff_t *ppos)
{
    int retvalue;
    unsigned char databuf[1];
    // unsigned char ledstat; 
    struct timer_dev *dev = (struct timer_dev *)filp->private_data;

    retvalue = copy_from_user(databuf, buf, count);
    if(retvalue < 0) {
        printk("kernel write failed!\r\n");
        return -EFAULT;
    }
    led_switch(dev, databuf[0]);   
    
    return 0;
}

static ssize_t timer_read(struct file *filp, char __user *buf,
size_t cnt, loff_t *offt)
{
    return 0;
}

/* 字符设备操作集 */
static const struct file_operations timer_fops = {
    .owner = THIS_MODULE,
    .write = timer_write,
    .open = timer_open,
    .read = timer_read,
    .release = timer_release,
};

/* 模块入口函数 */
static int __init timer_init(void)
{
    /* 定义一些所需变量 */
    int ret = 0;

    /* 1. 注册字符设备驱动 */
    timerDev.major = 0;
    if(timerDev.major) {
        timerDev.devid = MKDEV(timerDev.major, 0);
        ret = register_chrdev_region(timerDev.devid, TIMER_CNT, TIMER_NAME);  
    } else {
        alloc_chrdev_region(&timerDev.devid, 0, TIMER_CNT, TIMER_NAME);
        timerDev.major = MAJOR(timerDev.devid);
        timerDev.minor = MINOR(timerDev.devid);
    }
    if(ret < 0){
        goto fail_devid;
    }
    printk("Make devid success! \r\n");
    printk("major = %d, minor = %d \r\n", timerDev.major, timerDev.minor);

    /* 2. 初始化cdev */
    timerDev.cdev.owner = THIS_MODULE;
    cdev_init(&timerDev.cdev, &timer_fops);
    ret = cdev_add(&timerDev.cdev, timerDev.devid, TIMER_CNT);
    if (ret < 0){
        goto fail_cdev;
    } else {
        printk("Cdev add sucess! \r\n");
    }

    /* 3. 自动创建设备节点 */
    timerDev.class = class_create(THIS_MODULE, TIMER_NAME);
    if(IS_ERR(timerDev.class)) {
        ret = PTR_ERR(timerDev.class);
        goto fail_class;
    } else {
        printk("Class create sucess! \r\n");
    }

    timerDev.device = device_create(timerDev.class, NULL, timerDev.devid, NULL, TIMER_NAME);
    if(IS_ERR(timerDev.device)) {
        ret = PTR_ERR(timerDev.device);
        goto fail_device;
    } else {
        printk("Device create sucess! \r\n");
    }

    /* 初始化Led */
    ret = led_init(&timerDev);
    if(ret < 0) {
        goto fail_led_init;
    }
    
    /* 初始化定时器 */
    mytimer_init();

    printk("timerDev init! \r\n");
    return 0;

/* 错误处理 */
fail_led_init:
fail_device:
    class_destroy(timerDev.class);
fail_class:
    cdev_del(&timerDev.cdev);
fail_cdev:
    unregister_chrdev_region(timerDev.devid, TIMER_CNT);
fail_devid:
    return ret;
}

/* 模块出口函数 */
static void __exit timer_exit(void)
{
    /* 关闭定时器 */
    del_timer(&timerDev.timer);
    /* 关灯 */
    gpio_set_value(timerDev.led_gpio, 1);

    /* 1. 释放设备号 */
    cdev_del(&timerDev.cdev);
    /* 2. 注销设备号 */
    unregister_chrdev_region(timerDev.devid, TIMER_CNT);
    /* 3. 摧毁设备 */
    device_destroy(timerDev.class, timerDev.devid);
    /* 4.摧毁类 */
    class_destroy(timerDev.class);

    /* 释放IO, 和上面的申请IO对应 */
    gpio_free(timerDev.led_gpio);

    printk("timerDev exit! \r\n");
}

/* 模块入口和出口注册 */
module_init(timer_init);
module_exit(timer_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Shao Zheming");

2.使用ioctl

  • unlocked_ioctl
    提供对程序的控制功能,与应用函数的ioctl对应
  • compat_ioctl
    64位系统上的unlocked_ioctl
  • ioctl中的cmd
    内核定时器
    命令是自己定义的,但是要符合linux规则。
    一个cmd被分为了4个段,每一段都有各自的意义,cmd的定义在<linux/ioctl.h>。注:但实际上<linux/ioctl.h>中只是包含了<asm/ioctl.h>,这说明了这是跟平台相关的,ARM的定义在<arch/arm/include/asm/ioctl.h>,但这文件也是包含别的文件<asm-generic/ioctl.h>。
    内核定时器
    内核定时器
    内核定时器
    内核定时器
#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/ide.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/errno.h> 
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <asm/mach/map.h>
#include <linux/timer.h>
#include <linux/jiffies.h>

#define TIMER_CNT       1
#define TIMER_NAME      "timerDev"
#define CLOSE_CMD       (_IO(0XEF, 0x1))            /* 关闭定时器 */
#define OPEN_CMD        (_IO(0XEF, 0x2))            /* 打开定时器 */
#define SETPERIOD_CMD   (_IO(0XEF, 0x3))            /* 设置定时器周期命令 */
#define LEDOFF          0                           /* 关灯 */
#define LEDON           1                           /* 开灯 */

/* timer设备结构体 */
struct timer_dev{
    dev_t               devid;          /* 设备号 */
    struct cdev         cdev;           /* 字符设备 */
    struct class        *class;         /* 类 */
    struct device       *device;        /* 设备 */
    int                 major;          /* 注设备号 */
    int                 minor;          /* 次设备号 */
    struct device_node  *nd;            /* 设备节点 */
    int                 led_gpio;       /* 设备树里面的编号 */

    struct timer_list   timer;          /* 设备里面定义一个定时器 */

    int                 timeperiod;     /* 定时周期,单位为 ms */
    spinlock_t          lock;           /* 定义自旋锁 */
};

struct timer_dev timerDev; /* 定义LED结构体 */

/* 初始化led */
static int led_init(struct timer_dev *dev)
{
    int ret = 0;

    /* 1. 获取设备节点 */
    dev->nd = of_find_node_by_path("/gpioled");
    if( dev->nd == NULL){
        ret = -EINVAL;
        printk("gpioled node can not found!\r\n");
        goto fail_findnd;
    }

    /* 2. 获取设备所对应的gpio */
    /* 注意第三个参数,因为只有一个索引,所以是0 */
    dev->led_gpio = of_get_named_gpio(dev->nd, "led-gpios", 0);
    if( dev->led_gpio < 0) {
        printk("Can't find led gpio \r\n");
        ret = -EINVAL;
        goto fail_findnd;
    }
    printk("Led gpio num = %d. \r\n", dev->led_gpio);
    
    /* 3. 获取到IO之后,申请IO */
    /* 作用是申请之后,就能知道该IO是否被其他函数占用 */
    /* 如果申请失败,说明被战用啦 */
    /* 解决方法:1.搜索所需管脚 2.在搜索复用管脚,例如 &gpio1 3 */
    ret = gpio_request(dev->led_gpio, "led-gpio");
    if(ret) {
        printk("Failed to request the led gpio! \r\n");
        ret = -EINVAL;
        goto fail_findnd;
    }

    /* 4. 使用IO */
    ret = gpio_direction_output(dev->led_gpio, 1); /* 设置输出,默认高电平不点亮 */
    if(ret < 0){
        printk("Failed to set input or output! \r\n");
        goto fail_set_output;
    }

    /* 5. 输出低电平,点亮LED */
    gpio_set_value(dev->led_gpio, 0);

    return 0;

/* 错误处理 */
fail_set_output:
    gpio_free(dev->led_gpio);
fail_findnd:
    return ret;
}

/* 定时器处理函数 */
static void timer_func(unsigned long arg)
{
    /* 先取得函数传递的参数 */
    struct timer_dev *dev =(struct timer_dev *)arg; 
    static int sta = 1;

    sta = !sta;
    gpio_set_value(dev->led_gpio, sta);

    /* 这里是再加500ms,每进一次中断就会把中断时间提升500ms,这样可以一直运行 */
    mod_timer(&dev->timer, jiffies + msecs_to_jiffies(timerDev.timeperiod));
}

/* 初始化定时器 */
static void mytimer_init(void)
{
    /* 初始化定时器 */
    init_timer(&timerDev.timer);
    /* 初始化定时器的周期为500ms */
    timerDev.timeperiod = 500;
    /* 定义定时器的中断函数 */
    timerDev.timer.function = timer_func;
    /* 函数传递的参数 */
    timerDev.timer.data = (unsigned long)&timerDev;
    /* 定义定时器的周期 */
    /* 当前系统定时+500ms周期 */
    /* 设定好了之后,过了500ms之后就会进入function */
    timerDev.timer.expires = jiffies + msecs_to_jiffies(timerDev.timeperiod);
    /* 添加定时器 */
    add_timer(&timerDev.timer);
}

static int timer_open(struct inode *inode, struct file *filp)
{
    filp->private_data = &timerDev;
    return 0;
}

static int timer_release(struct inode *inode, struct file *filp)
{
    //struct timer_dev *dev = (struct timer_dev *)filp->private_data;
    return 0;
}

static long timer_ioctl (struct file *filp, unsigned int cmd, 
                         unsigned long arg)
{
    struct timer_dev *dev = (struct timer_dev *)filp->private_data;
    int timerperiod;
    unsigned long flags;

    switch (cmd) {
        case CLOSE_CMD: /* 关闭定时器 */
            del_timer_sync(&dev->timer);
            break;
        case OPEN_CMD: /* 打开定时器 */
            spin_lock_irqsave(&dev->lock, flags);
            timerperiod = dev->timeperiod;
            spin_unlock_irqrestore(&dev->lock, flags);
            mod_timer(&dev->timer, jiffies + msecs_to_jiffies(timerperiod));
            break;
        case SETPERIOD_CMD: /* 设置定时器周期 */
            spin_lock_irqsave(&dev->lock, flags);
            dev->timeperiod = arg;
            spin_unlock_irqrestore(&dev->lock, flags);
            mod_timer(&dev->timer, jiffies + msecs_to_jiffies(arg));
            break;
        default:
            break;
    }
    return 0;
}
/* 字符设备操作集 */
static const struct file_operations timer_fops = {
    .owner = THIS_MODULE,
    .open = timer_open,
    .release = timer_release,
    .unlocked_ioctl = timer_ioctl,
};

/* 模块入口函数 */
static int __init timer_init(void)
{
    /* 定义一些所需变量 */
    int ret = 0;

    /* 1. 注册字符设备驱动 */
    timerDev.major = 0;
    if(timerDev.major) {
        timerDev.devid = MKDEV(timerDev.major, 0);
        ret = register_chrdev_region(timerDev.devid, TIMER_CNT, TIMER_NAME);  
    } else {
        alloc_chrdev_region(&timerDev.devid, 0, TIMER_CNT, TIMER_NAME);
        timerDev.major = MAJOR(timerDev.devid);
        timerDev.minor = MINOR(timerDev.devid);
    }
    if(ret < 0){
        goto fail_devid;
    }
    printk("Make devid success! \r\n");
    printk("major = %d, minor = %d \r\n", timerDev.major, timerDev.minor);

    /* 2. 初始化cdev */
    timerDev.cdev.owner = THIS_MODULE;
    cdev_init(&timerDev.cdev, &timer_fops);
    ret = cdev_add(&timerDev.cdev, timerDev.devid, TIMER_CNT);
    if (ret < 0){
        goto fail_cdev;
    } else {
        printk("Cdev add sucess! \r\n");
    }

    /* 3. 自动创建设备节点 */
    timerDev.class = class_create(THIS_MODULE, TIMER_NAME);
    if(IS_ERR(timerDev.class)) {
        ret = PTR_ERR(timerDev.class);
        goto fail_class;
    } else {
        printk("Class create sucess! \r\n");
    }

    timerDev.device = device_create(timerDev.class, NULL, timerDev.devid, NULL, TIMER_NAME);
    if(IS_ERR(timerDev.device)) {
        ret = PTR_ERR(timerDev.device);
        goto fail_device;
    } else {
        printk("Device create sucess! \r\n");
    }

    /* 初始化Led */
    ret = led_init(&timerDev);
    if(ret < 0) {
        goto fail_led_init;
    }
    
    /* 初始化定时器 */
    mytimer_init();

    printk("timerDev init! \r\n");
    return 0;

/* 错误处理 */
fail_led_init:
fail_device:
    class_destroy(timerDev.class);
fail_class:
    cdev_del(&timerDev.cdev);
fail_cdev:
    unregister_chrdev_region(timerDev.devid, TIMER_CNT);
fail_devid:
    return ret;
}

/* 模块出口函数 */
static void __exit timer_exit(void)
{
    /* 关闭定时器 */
    del_timer(&timerDev.timer);
    /* 关灯 */
    gpio_set_value(timerDev.led_gpio, 1);

    /* 1. 释放设备号 */
    cdev_del(&timerDev.cdev);
    /* 2. 注销设备号 */
    unregister_chrdev_region(timerDev.devid, TIMER_CNT);
    /* 3. 摧毁设备 */
    device_destroy(timerDev.class, timerDev.devid);
    /* 4.摧毁类 */
    class_destroy(timerDev.class);

    /* 释放IO, 和上面的申请IO对应 */
    gpio_free(timerDev.led_gpio);

    printk("timerDev exit! \r\n");
}

/* 模块入口和出口注册 */
module_init(timer_init);
module_exit(timer_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Shao Zheming");

3.应用代码

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "linux/ioctl.h"

/* 
 * argc: 应用程序参数个数
 * argv[]: 参数是什么,具体的参数,说明参数是字符串的形式
 * .chrdevbaseApp <filename> <0:1> 0表示关灯,1表示开灯
 * .chrdevbaseApp /dev/led 0 关灯
 * .chrdevbaseApp /dev/led 1 开灯
 * */

#define CLOSE_CMD       (_IO(0XEF, 0x1))        /* 关闭定时器 */
#define OPEN_CMD        (_IO(0XEF, 0x2))        /* 打开定时器 */
#define SETPERIOD_CMD   (_IO(0XEF, 0x3))        /* 设置定时器周期命令 */

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Error Usage!\r\n");
        return -1;
    }
    
    int fd, ret;
    char *filename;
    unsigned int cmd;
    unsigned int arg;
    unsigned char str[100];

    filename = argv[1];
    fd = open(filename, O_RDWR);
    if(fd < 0)
    {
        printf("file %s open failed! \r\n", filename);
        return -1;
    }

    while (1) {
        printf("Input CMD:");
        ret = scanf("%d", &cmd);
        if (ret != 1) { /* 参数输入错误 */
            /* 输入参数错误的时候会有错误的字符串卡死在缓冲区里,所以使用get */
            gets(str); /* 防止卡死 */
        }

        if(cmd == 1) /* 关闭 LED 灯 */
            cmd = CLOSE_CMD;
        else if(cmd == 2) /* 打开 LED 灯 */
            cmd = OPEN_CMD;
        else if(cmd == 3) {
            cmd = SETPERIOD_CMD; /* 设置周期值 */
            printf("Input Timer Period:");
            ret = scanf("%d", &arg);
            if (ret != 1) { /* 参数输入错误 */
                gets(str); /* 防止卡死 */
            }
        }
        ioctl(fd, cmd, arg); /* 控制定时器的打开和关闭 */
    }

    close(fd);
    return 0;
}

4.注意

也可以用IOW来说明要写数据,但是在驱动中,就只能用copy_from_user,里面的&arg应该以地址的形式传递。但是应用程序传递过来的就可以是地址,所以里面的arg直接就是指针,前面强制转化成(int*)就可以了

上一篇:第十七届智能车竞赛英飞凌专题培训 ——无线充电组浅析及LED驱动方案讲解


下一篇:ESPIDF添加自定义组件(创建C和H文件)