platform平台设备驱动简化示例代码

时间:2022-01-14 08:17:27

driver.c:

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/platform_device.h> #define DRIVER_NAME "my_dev" static int my_probe(struct device *dev)
{
printk("driver found device !!\n");
return ;
} static int my_remove(struct device *dev)
{
printk("driver found device unpluged !!\n");
return ;
} struct platform_driver my_driver={
.probe=my_probe,
.remove=my_remove,
.driver={ //platform_driver内嵌device_driver
.owner=THIS_MODULE,
.name =DRIVER_NAME,//最重要的是对name的赋值,因为在匹配的时候要用!!!!
},
}; static int __init my_driver_init(void)
{
int ret =; /*注册平台驱动*/
ret=platform_driver_register(&my_driver); return ret;
} static void __exit my_driver_exit(void)
{
/*注销平台驱动*/
platform_driver_unregister(&my_driver);
} MODULE_AUTHOR("mhb@SEU");
MODULE_LICENSE("GPL"); module_init(my_driver_init);
module_exit(my_driver_exit);

device.c:

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/platform_device.h>
#include <linux/device.h> #define DEVICE_NAME "my_dev" struct platform_device *my_device; static int __init my_device_init(void)
{
int ret=; /*分配结构体内存*/
my_device=platform_device_alloc(DEVICE_NAME,-); /*注册平台设备*/
ret=platform_device_add(my_device);//在platform_device_alloc中已经init了,所以调用add而不是register
if(ret)
platform_device_put(my_device);/*注册失败,释放相关内存*/ return ret;
} static void __exit my_device_exit(void)
{
platform_device_unregister(my_device);
} MODULE_AUTHOR("mhb@SEU");
MODULE_LICENSE("GPL"); module_init(my_device_init);
module_exit(my_device_exit);