在platform总线上注册设备并载入驱动控制led灯


开发板:龙芯1B

PC:Ubuntu 13.10

本程序自己定义一个设备注册到内核,然后再编写该设备驱动。最终实现开发板led灯控制,开发板led灯通过gpio口控制

/*************************************************************************
 > File Name: platform_test.c
 > Author: kid
 > Mail: 280197326@qq.com
 > Created Time: 2014年03月05日 星期三 11时17分02秒
 ************************************************************************/

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/device.h>

#define SET_GPIO (*(volatile unsigned *)0xbfd010C4)
#define SET_OUT (*(volatile unsigned *)0xbfd010D4)
#define SET_LED (*(volatile unsigned *)0xbfd010F4)

static int led_probe(struct platform_device *pdev)  //驱动加载时运行此函数,设置gpio控制led灯
{
    SET_GPIO = (SET_GPIO | 0x000000C0);
    SET_OUT = (SET_OUT & ~(0x000000C0));
    SET_LED = (SET_LED & ~(0x000000c0));
    printk(KERN_ALERT "hello\n");
 
    return 0;
}

static struct platform_device led_device = {  //添加设备结构体
    .name = "led",
    .id = 99,
};

static struct platform_driver led_driver = {  //添加驱动结构体
 .driver = {
  .name = "led",
  .owner = THIS_MODULE,
 },
 .probe  = led_probe,
};

static int __devinit led_init(void)  //初始化驱动
{
    int ret = 0;
    platform_device_register(&led_device);  //注册设备到内核
    ret = platform_driver_register(&led_driver);  //注册驱动到内核
    if (ret){
        printk(KERN_ERR "failed to register\n");
    }
       
    return ret;
}

static void __devexit led_exit(void)  //驱动退出
{
    platform_driver_unregister(&led_driver);  //卸载驱动
    platform_device_unregister(&led_device);  //卸载设备
    printk(KERN_ALERT "good bye\n");
}

module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL");

注意:必须要注册设备和驱动,调试过程中曾没有注册设备导致驱动初始化的时候不会执行probe函数,注册设备和驱动的顺序可以随意。但两者必须的设备名称必须匹配。

 

相关内容