mycdev.c
#include
#include
#include
#include
#include
#include
/* myled
{
led1-gpio=<&gpioe 10 0>;
led2-gpio=<&gpiof 10 0>;
led3-gpio=<&gpioe 8 0>;
};
*/
struct device_node *dnode;
unsigned int gpiono1;
unsigned int gpiono2;
unsigned int gpiono3;
struct timer_list mytimer;
//定时器处理函数
void mytimer_function(struct timer_list *timer)
{
//LED1状态取反
gpiod_set_value(gpiono1,!gpiod_get_value(gpiono1));
//LED2状态取反
gpiod_set_value(gpiono2,!gpiod_get_value(gpiono2));
//LED3状态取反
gpiod_set_value(gpiono3,!gpiod_get_value(gpiono3));
printf("hello world\n");
//再次启用定时器
mod_timer(timer,jiffies+500);
}
static int __init mycdev_init(void)
{
//解析设备树节点信息
dnode=of_find_node_by_path("/myled");
if(dnode==NULL)
{
printk("解析设备树节点失败\n");
return -ENXIO;
}
//获取LED1 GPIO编号
gpiono1=gpiod_get_from_of_node(dnode,"led1-gpio",0,GPIOD_OUT_LOW,NULL);
if(IS_ERR(gpiono1))
{
printk("申请gpio信息失败\n");
return -PTR_ERR(gpiono1);
}
//获取LED2 GPIO编号
gpiono2=gpiod_get_from_of_node(dnode,"led2-gpio",0,GPIOD_OUT_LOW,NULL);
if(IS_ERR(gpiono2))
{
printk("申请gpio信息失败\n");
return -PTR_ERR(gpiono2);
}
//获取LED3 GPIO编号
gpiono3=gpiod_get_from_of_node(dnode,"led3-gpio",0,GPIOD_OUT_LOW,NULL);
if(IS_ERR(gpiono3))
{
printk("申请gpio信息失败\n");
return -PTR_ERR(gpiono3);
}
//初始化定时器对象
timer_setup(&mytimer,mytimer_function,0);
mytimer.expires=jiffies+500;//定时5s;
//注册定时器
add_timer(&mytimer);
return 0;
}
static void __exit mycdev_exit(void)
{
//注销定时器
del_timer(&mytimer);
gpio_set_value(gpiono1,0);
//释放GPIO编号1
gpio_free(gpiono1);
gpio_set_value(gpiono2,0);
//释放GPIO编号2
gpio_free(gpiono2);
gpio_set_value(gpiono3,0);
//释放GPIO编号
gpio_free(gpiono3);
}
module_init(mycdev_init);
module_exit(mycdev_exit);
MODULE_LICENSE("GPL");
led.c
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc,const char * argv[])
{
int a=0;
char buf[128] = "";
char buf1[128] = "";
int fd1=open("/dev/myled0",O_RDWR);
int fd2=open("/dev/myled1",O_RDWR);
int fd3=open("/dev/myled2",O_RDWR);
if(fd1<0)
{
printf("打开设备文件1失败\n");
exit(-1);
}
if(fd2<0)
{
printf("打开设备文件2失败\n");
exit(-1);
}
if(fd3<0)
{
printf("打开设备文件3失败\n");
exit(-1);
}
memset(buf,0,sizeof(buf));
while(1)
{
printf("请输入灯的控制(1开灯/0关灯) => ");
scanf("%d",&a);
write(fd1,buf,sizeof(buf));
write(fd2,buf,sizeof(buf));
write(fd3,buf,sizeof(buf));
if(a == 1)
{
strcpy(buf,"on");
write(fd1,buf,sizeof(buf));
write(fd2,buf,sizeof(buf));
write(fd3,buf,sizeof(buf));
}
else if(a == 0)
{
strcpy(buf,"off");
write(fd1,buf,sizeof(buf));
write(fd2,buf,sizeof(buf));
write(fd3,buf,sizeof(buf));
}
read(fd1,buf1,sizeof(buf));
printf("buf1:%s\n",buf1);
}
return 0;
}