目的:学习sysfs文件系统,直接在应用层使用cat 和echo命令来控制LED。
===============================================
驱动:
- #include <linux/module.h>
- #include <asm/uaccess.h>
- #include <linux/version.h>
- #include <linux/io.h>
- #include <linux/gpio.h>
- #include <plat/gpio-cfg.h>
- #include <mach/regs-gpio.h>
- #include <asm/mach/arch.h>
- #include <linux/kobject.h>
- #include <linux/string.h>
- #define GPIO_LED1 S5PV210_GPH1(3)
- struct kobject *kobj;
- const static char *str_ledon = "ledon";
- const static char *str_ledoff= "ledoff";
- static ssize_t led_show(struct kobject *kobj, struct kobj_attribute *attr,char *buf )
- {
- char *s= buf;
- int len;
- if(gpio_get_value(GPIO_LED1))
- s += sprintf(s,"%s\n",str_ledon);
- else
- s += sprintf(s,"%s\n",str_ledoff);
- if (s != buf)
- *(s-1) = '\n';
- return (s - buf);
- }
- static ssize_t led_store(struct kobject *kobj,struct kobj_attribute *attr,const char* buf, size_t n)
- {
- char *p;
- int len;
- p = memchr(buf, '\n', n);
- len = p ? p - buf : n;
- printk(KERN_INFO "%s:enter\n",__func__);
- s3c_gpio_cfgpin(GPIO_LED1,S3C_GPIO_OUTPUT );
- s3c_gpio_setpull(GPIO_LED1,S3C_GPIO_PULL_UP );
- if(gpio_request(GPIO_LED1,"led_sysfs")> 0)
- {
- if(!strncmp(buf,str_ledon,len ))
- {
- printk(KERN_INFO "%s:1\n",__func__);
- gpio_set_value(GPIO_LED1,0);
- }
- else if(!strncmp(buf,str_ledoff,len ))
- {
- printk(KERN_INFO "%s:2\n",__func__);
- gpio_set_value(GPIO_LED1,1);
- }
- }
- else
- printk(KERN_INFO "%s:3\n",__func__);
- return len ;
- }
- //具体属性参数
- static struct kobj_attribute kobj_attr ={
- .attr = {
- .name = __stringify(ledstate), //把ledstate转换成字符串
- .mode = 0666, //表示此属性可读可写
- },
- .show = led_show, //对应读
- .store= led_store, //对应写
- };
- //属性数组
- static struct attribute *attr_g[] ={
- &kobj_attr.attr,
- NULL,// 必须包含NULL
- };
- //对属性数组的封装。
- static struct attribute_group grp ={
- .attrs = attr_g,
- };
- static int __init led_init(void)
- {
- kobj = kobject_create_and_add("led_sysfs",NULL);
- if(!kobj )
- {
- printk(KERN_INFO "kobject don't create \n");
- return -ENOMEM;
- }
- return sysfs_create_group(kobj, &grp);
- }
- static void __exit led_exit(void)
- {
- printk(KERN_INFO "%s:enter\n",__func__);
- sysfs_remove_group(kobj, &grp);
- kobject_del(kobj);
- }
- module_init(led_init);
- module_exit(led_exit);
- MODULE_LICENSE("GPL");
Makefile:
- OBJ = /home/xhy/kernel
- all :
- make -C $(OBJ) M=`pwd` modules
- clean:
- make -C $(OBJ) M=`pwd` clean
- obj-m += led_sysfs.o
--------------------------------------------------
make后把生成的led_sysfs.ko文件push到小机上,
adb shell
insmod led_sysfs.ko
cd /sys/
- # lsmod
- led_sysfs 1432 0 - Live 0xbf02a000
cd led_sysfs
- # cat ledstate
- ledoff