驱动代码
#include <linux/init.h>
#include <linux/module.h>
#include <linux/of_gpio.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
#define LED_ON _IOW('l',1,int)
#define LED_OFF _IOW('l',0,int)
//封装probe函数,当设备和驱动匹配成功之后执行
struct class *cls;
struct device *devs;
struct resource *res;
int irqno,major;
struct gpio_desc *gpiono[3];
long mycdev_ioctl (struct file * file , unsigned int cmd, unsigned long arg)
{
int b;
copy_from_user(&b,(void *)arg,4);
switch(cmd)
{
case LED_ON:
switch(b)
{
case 1:
gpiod_set_value(gpiono[0],1);
break;
case 2:
gpiod_set_value(gpiono[1],1);
break;
case 3:
gpiod_set_value(gpiono[2],1);
break;
}
break;
case LED_OFF:
switch(b)
{
case 1:
gpiod_set_value(gpiono[0],0);
break;
case 2:
gpiod_set_value(gpiono[1],0);
break;
case 3:
gpiod_set_value(gpiono[2],0);
break;
}
}
return 0;
}
struct file_operations fops={
.unlocked_ioctl=mycdev_ioctl};
int pdrv_probe(struct platform_device *dev)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
irqno=platform_get_irq(dev,0);
if(irqno<0)
{
printk("获取中断资源失败\n");
return irqno;
}
printk("获取中断资源为%d\n",irqno);
major = register_chrdev(0, "mychrdev", &fops);
if (major < 0)
{
printk("字符设备驱动注册失败\n");
return major;
}
printk("字符设备驱动注册成功\n");
// 向上提交目录
cls = class_create(THIS_MODULE, "mychrdev");
if (IS_ERR(cls))
{
printk("向上提交目录失败\n");
return -PTR_ERR(cls);
}
printk("向上提交目录成功\n");
// 向上提交设备节点信息
devs=device_create(cls, NULL, MKDEV(major, 0),NULL,"myled");
if (IS_ERR(devs))
{
printk("向上提交设备节点失败\n");
return -PTR_ERR(devs);
}
printk("向上提交设备节点成功\n");
int i;
for(i=0;i<3;i++)
{
gpiono[i]=gpiod_get_from_of_node(dev->dev.of_node,"leds-gpio",i,GPIOD_OUT_LOW,NULL);
if(gpiono[i]==NULL)
{
printk("解析gpio编号失败\n");
return -ENXIO;
}
printk("解析gpio编号成功\n");
}
return 0;
}
//封装remove函数,用于驱动和设备卸载时执行
int pdrv_remove(struct platform_device *dev)
{
int i;
for(i=0;i<3;i++)
{
gpiod_put(gpiono[i]);
}
device_destroy(cls,MKDEV(major, 0));
class_destroy(cls);
unregister_chrdev(major, "mychrdev");
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
struct of_device_id oftable[]={
{.compatible="woc,yuan",},
{}
};
//分配驱动对象并初始化
struct platform_driver pdrv={
.probe=pdrv_probe,
.remove=pdrv_remove,
.driver={
.name="ccccc",
.of_match_table=oftable,
},
};
module_platform_driver(pdrv);
MODULE_LICENSE("GPL");
测试代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#define LED_ON _IOW('l',1,int)
#define LED_OFF _IOW('l',0,int)
int main()
{
int a,b;
printf("选择要控制的灯:");
scanf("%d",&b);
int fd=open("/dev/myled",O_RDWR);
while(1)
{
printf("输入控制:");
scanf("%d",&a);
switch (a)
{
case 0:
ioctl(fd,LED_OFF,&b);
break;
case 1:
ioctl(fd,LED_ON,&b);
break;
}
}
return 0;
}