GPIO子系统编写LED驱动

驱动程序

#include 
#include 
#include 
#include 
#include 
#include 
#include
#include
#include
#include
#include

int gpiono;
struct device_node *dnode;
char kbuf[128]={0};
struct class *cls;
unsigned int major;
struct device *dev;


ssize_t mycdev_write(struct file *file,const char *ubuf,size_t size,loff_t *iof)
{
    int ret;
    //从用户拷贝
    if(size>sizeof(kbuf))
        size=sizeof(kbuf);
    ret=copy_from_user(kbuf,ubuf,size);
    if(ret)
    {
        printk("copy from user filed\n");
        return -EIO;
    }
    //解析设备树节点
    dnode=of_find_node_by_name(NULL,"myleds");
    if(dnode==NULL)
    {
        printk("解析设备树节点失败\n");
        return -ENOMEM;
    }
    printk("解析设备数节点成功\n");
    //根据设备数节点解析出GPIO编号
    gpiono=of_get_named_gpio(dnode,kbuf,0);
    if(gpiono<0)
    {
        printk("解析设备号失败\n");
        return -EIO;
    }
    //申请GPIO编号
    ret=gpio_request(gpiono,NULL);
    if(ret)
    {
        printk("申请GPIO编号失败\n");
        return -EIO;
    }
    printk("申请GPIO编号成功%d\n",gpiono);
    //设置管脚为输出
    gpio_direction_output(gpiono,gpio_get_value(gpiono));
    //
    gpio_set_value(gpiono,!gpio_get_value(gpiono));
    //释放gpio编号
    gpio_free(gpiono);

    return 0;
}
struct file_operations fops={
    .write=mycdev_write,
};
static int __init mycdev_init(void)
{
    //字符设备驱动的注册
    major=register_chrdev(0,"mycdev",&fops);
    if(major<0)
    {
        printk("字符设备驱动注册失败\n");
        return major;
    }
    printk("字符设备驱动注册成功major=%d\n",major);
     //向上提交目录
    cls=class_create(THIS_MODULE,"mycdev");
    if(IS_ERR(cls))
    {
        printk("向上提交目录失败\n");
        return -PTR_ERR(cls);
    }
    printk("向上提交目录成功\n");
    //向上提交设备节点信息
    dev=device_create(cls,NULL,MKDEV(major,0),NULL,"mycdev");
    if(IS_ERR(dev))
    {
        printk("向上提交设备节点失败\n");
        return -PTR_ERR(dev);
    }
    printk("向上提交设备节点成功\n");
    return 0;
}
static void __exit mycdev_exit(void)
{
    //灭灯
    gpio_set_value(gpiono,0);
    //释放gpio编号
    gpio_free(gpiono);
    //销毁设备节点信息
    device_destroy(cls,MKDEV(major,0));
    //销毁目录空间
    class_destroy(cls);
    //字符设备驱动的注销
    unregister_chrdev(major,"mycdev");

}
module_init(mycdev_init);
module_exit(mycdev_exit);
MODULE_LICENSE("GPL");

应用程序

#include
#include
#include 
#include 
#include 
#include
#include

int main(int argc, char const *argv[])
{
    printf("输入led\n");
    char buf[128]={0};
    scanf("%s",buf);
    int fd=open("/dev/mycdev",O_RDWR);
    if(fd<0)
    {
        printf("设备文件打开失败\n");
        exit(-1);
    }
    write(fd,buf,sizeof(buf));
    return 0;
}

你可能感兴趣的:(linux,运维,服务器)