說明:linux定時器是基於軟中斷實現的,不能進行休眠操作
一、標頭檔案、函數及說明
struct timer_list {
unsigned long expires;
void (*function)(unsigned long);
unsigned long data;
};
#ifdef CONFIG_LOCKDEP
#define init_timer(timer) \
do { \
static struct lock_class_key __key; \
init_timer_key((timer), #timer, &__key); \
} while (0)
else
#define init_timer(timer)\
init_timer_key((timer), NULL, NULL)
#endif
void add_timer(struct timer_list *timer);
int del_timer(struct timer_list * timer);
int mod_timer(struct timer_list *timer, unsigned long expires);
二、程式碼舉例
#include <linux/init.h>
#include <linux/module.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/gpio.h>
#include <cfg_type.h>
struct led_src {
char *name;
int gpio;
};
struct led_src led_info[] = {
{
.name = "LED1",
.gpio = PAD_GPIO_B + 26
},
{
.name = "LED2",
.gpio = PAD_GPIO_C + 11
},
{
.name = "LED3",
.gpio = PAD_GPIO_C + 7
},
{
.name = "LED4",
.gpio = PAD_GPIO_C + 12
}
};
static unsigned long g_data = 0xff;
static struct timer_list mytimer;
static void mytimer_func (unsigned long data){
int i = 0;
unsigned long *num = (unsigned long *) data;
for(; i < ARRAY_SIZE(led_info);i++){
gpio_set_value(led_info[i].gpio,\
1-gpio_get_value(led_info[i].gpio));
*num -= 1;
if(*num ==0)
*num = 255;
mod_timer(&mytimer,jiffies + 1 * HZ);
}
static int mytimer_init(void){
int i = 0;
for(; i< ARRAY_SIZE(led_info);i ++){
gpio_request(led_info[i].gpio, led_info[i].name);
gpio_direction_output(led_info[i].gpio,1);
}
init_timer(&mytimer);
mytimer.expires = jiffies + 2 * HZ;
mytimer.function = mytimer_func;
mytimer.data = (unsigned long *) &g_data;
add_timer(&mytimer);
return 0;
}
static void mytimer_exit(void){
int i = 0;
for(; i < ARRAY_SIZE(led_info); i++){
gpio_set_value(led_info[i].gpio,1);
gpio_free(led_info[i].gpio);
}
del_timer(&mytimer);
}
module_init(mytimer_init);
module_exit(mytimer_exit);
MODULE_LICENSE("GPL");