【Linux驱动】TQ2440 LED驱动程序

★总体介绍

LED驱动程序主要实现了TQ2440开发板上的4个LED灯的硬件驱动,实现了对引脚GPIOB5、GPIOB6、GPIOB7、GPIOB8的高低电平设置(common-smdk.c中已经实现了对引脚的配置),利用测试程序调用该驱动程序,通过命令控制LED灯的亮灭。

★详细介绍

1、驱动程序代码:My_led.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
#include <linux/device.h>

#define DEVICE_NAME  "My_led" /**加载模块后执行cat/proc/devices中看到的设备名称**/
#define Led_MAJOR        103        /**主设备号**/
#define LED_ON        1
#define LED_OFF      0

/**Led的控制引脚**/
static unsigned long led_table[ ] =
{
    S3C2410_GPB5,
    S3C2410_GPB6, 
 S3C2410_GPB7,
 S3C2410_GPB8,
};

static int My_led_open(struct inode *inode,struct file *file)
{
    printk("My_led  open\n");
    return 0;
}

static int My_led_ioctl(struct inode * inode, struct file * file,unsigned int cmd,unsigned long arg)
{
 if(arg > 4)
 {
  return -1;           
      }
 switch(cmd)
 {
      case LED_ON:
    s3c2410_gpio_setpin(led_table[arg], 0);//设置指定引脚为输出电平为0
      return 0;
        case LED_OFF:
            s3c2410_gpio_setpin(led_table[arg], 1);//设置指定引脚为输出电平为1
            return 0;
    default:
    return  -1;
 }
}

static struct file_operations My_led_fops =
{
 .owner = THIS_MODULE,
 .open = My_led_open,
 .ioctl = My_led_ioctl,
};

static struct class *led_class;

static int __init My_led_init(void)
{
 int ret;
 printk("My_led start\n");

  /**注册字符设备驱动程序**/
  /**参数为主设备号、设备名字、file_operations结构**/
  /**这样主设备号就与file_operations联系起来**/
  ret = register_chrdev(Led_MAJOR, DEVICE_NAME, &My_led_fops);
  if(ret < 0)
  {
  printk("can't register major number\n");
  return ret;
  }

 //注册一个类,使mdev可以在"/dev/目录下建立设备节点"
 led_class = class_create(THIS_MODULE, DEVICE_NAME);
 if(IS_ERR(led_class))
 {
  printk("failed in My_led class.\n");
  return -1;
 }
 device_create(led_class, NULL, MKDEV(Led_MAJOR,0), NULL, DEVICE_NAME);
 printk(DEVICE_NAME "initialized\n");
 return 0;

}

static void __exit My_led_exit(void)
{
    unregister_chrdev(Led_MAJOR, DEVICE_NAME);
    device_destroy(led_class, MKDEV(Led_MAJOR,0));//注销设备节点
  class_destroy(led_class);//注销类
}

module_init(My_led_init);
module_exit(My_led_exit);

MODULE_LICENSE("GPL");

2、宏定义

#define DEVICE_NAME  "My_led" //加载模块后执行cat/proc/devices中看到的设备名称

#define Led_MAJOR        103        //主设备号

#define LED_ON        1

#define LED_OFF      0 My_led_ioctl函数中要输入的参数命令,LED_ON会执行打开灯的命令、LED_OFF执行关闭灯的命令

3、Led灯的引脚控制

定义一个led_table[ ] 数组,在后面调用时要方便些。

详细说明一下S3C2410_GPB5是什么意思:

【Linux驱动】TQ2440 LED驱动程序
【Linux驱动】TQ2440 LED驱动程序
【Linux驱动】TQ2440 LED驱动程序

如上图所示,是关于S3C2410_GPB5相关的所有代码。通过上面的代码可以得出S3C2410_GPB5为37。实际上S3C2410_GPB5就是端口的编号,bank是分组的基号码,offset是组内的偏移量。TQ2440开发板的GPIOB的第五个引脚为37。