字符设备驱动控制LED灯

开发板:龙芯1B

PC:Ubuntu 13.10

本程序为字符设备驱动,提供控制led灯功能,如要实现控制需要自己写应用程序,打开驱动文件就可控制led灯,led灯通过gpio控制

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/ioctl.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/fcntl.h>
#include <linux/cdev.h>

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

struct led_dev
{
 struct cdev cdev;
};

static int my_start (struct inode *, struct file *);
//static ssize_t left (struct file *, char __user *, size_t, loff_t *);

struct class *led_class;
struct led_dev *led_devices;

static struct file_operations led_fops =
{
 .owner = THIS_MODULE,
 .open = my_start,
// .read = left,
};

static int my_start(struct inode * node, struct file * fil)
{
 SET_GPIO = (SET_GPIO | 0x000000C0);
 SET_OUT = (SET_OUT & ~(0x000000C0));
 SET_LED = (SET_LED & ~(0x000000c0));
 printk("Here is open\n");
 return 0;
}

static int __init led_init(void)
{
 int ret;
 dev_t dev = 0;
 dev = MKDEV(LED_MAJOR, LED_MINOR);
 ret = register_chrdev_region(dev, 1, "led");
 if(ret)
 {
  printk("register_fail\n");
 }else{
  printk("register_succeed\n");
 }
 led_devices = kmalloc(sizeof(struct led_dev), GFP_KERNEL);
 if(led_devices == NULL)
 {
  printk("malloc_fail\n");
 }else{
  printk("malloc_succeed\n");
 }
 memset(led_devices, 0, sizeof(struct led_dev));
 cdev_init(&led_devices->cdev, &led_fops);
 led_devices->cdev.owner = THIS_MODULE;
 led_devices->cdev.ops = &led_fops;
 ret = cdev_add(&led_devices->cdev, dev, 1);

 if(ret)
 {
  printk("add_fail\n");
 }else{
  printk("add_succeed\n");
 }
 led_class = class_create(THIS_MODULE, "led_class");
 device_create(led_class, NULL, dev, NULL, "led");
 return ret;
}

static void __exit led_exit(void)
{
 dev_t devno = MKDEV(LED_MAJOR, LED_MINOR);
 unregister_chrdev_region(devno,1);
 device_destroy(led_class, devno);
 printk("exit_succeed\n");
 class_destroy(led_class);
}

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

相关推荐