#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/gpio.h>
#include<linux/uaccess.h>
struct resource *res;
unsigned int irqno;
struct gpio_desc *gpiono;
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;
}
if(strcmp(kbuf,"0") == 0)
{
gpiod_set_value(gpiono,0);
}
else if(strcmp(kbuf,"1") == 0)
{
gpiod_set_value(gpiono,1);
}
return 0;
}
//定义相关成员函数
//probe函数用于匹配设备成功后执行
struct file_operations fops={
.write=mycdev_write,
};
int pdrv_probe(struct platform_device *pdev)
{
//字符设备驱动的注册
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");
res=platform_get_resource(pdev,IORESOURCE_MEM,0);
if(res==NULL)
{
printk("解析资源失败%d\n",__LINE__);
return -ENOMEM;
}
irqno=platform_get_irq(pdev,0);
if(irqno<0)
{
printk("解析资源失败%d\n",__LINE__);
return -ENOMEM;
}
printk("mem:%llx irq:%d\n",res->start,irqno);
//解析出GPIO编号并申请
gpiono=gpiod_get_from_of_node(pdev->dev.of_node,"led1",0,GPIOD_OUT_LOW,NULL);
if(IS_ERR(gpiono))
{
printk("GPIO信息解析失败\n");
return -PTR_ERR(gpiono);
}
printk("GPIO信息解析成功\n");
return 0;
}
//remove用于和设备分离后执行
int pdrv_remove(struct platform_device *pdev)
{
//灭灯
gpiod_set_value(gpiono,0);
//释放GPIO编号
gpiod_put(gpiono);
printk("remove函数\n");
return 0;
}
//驱动中创建一个用于设备树匹配的表
struct of_device_id oftable[]={
{.compatible="hqyj,myplatform",},
{.compatible="hqyj,myplatform1",},
{.compatible="hqyj,myplatform2",},
{},
};
//分配对象并初始化
struct platform_driver pdrv={
.probe=pdrv_probe,
.remove=pdrv_remove,
.driver={
.name="aaaa",
.of_match_table=oftable,
},
};
module_platform_driver(pdrv);
MODULE_LICENSE("GPL");
#include<stdlib.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc, char const *argv[])
{
printf("输入1(开灯),0(关灯)\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;
}