这个程序主要参考韦东山的视频资料,不过他用的linux内核为2.6.22,和2.6.30的源码好多函数实现的不一样。譬如说,在这个例子中,需要创建类、类的设备等等这些函数,在2.6.22中是函数class_creat和class_devices_creat,不过,在2.6.30中却是class_creat和device_creat.废话不多说,上代码:
led_driver.c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
static struct class *firstdrv_class;
static struct class_device *firstdrv_class_dev;
volatile unsigned long *gpfcon = NULL;
volatile unsigned long *gpfdat = NULL;
static int first_drv_open(struct inode *inode, struct file *file)
{
//printk("first_drv_open\n");
/* 配置GPF4,5,6为输出 */
*gpfcon &= ~((0x3<<(5*2)) | (0x3<<(6*2)) | (0x3<<(7*2)) | (0x3<<(8*2)));
*gpfcon |= ((0x1<<(5*2)) | (0x1<<(6*2)) | (0x1<<(7*2)) | (0x1<<(8*2)));
return 0;
}
static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
int val;
//printk("first_drv_write\n");
copy_from_user(&val, buf, count); // copy_to_user();
if (val == 1)
{
// 点灯
*gpfdat &= ~((1<<5) | (1<<6) | (1<<7) | (1<<8));
}
else
{
// 灭灯
*gpfdat |= (1<<5) | (1<<6) | (1<<7) | (1<<8);
}
return 0;
}
static struct file_operations first_drv_fops = {
.owner = THIS_MODULE, /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
.open = first_drv_open,
.write = first_drv_write,
};
int major;
static int first_drv_init(void)
{
major = register_chrdev(0, "first_drv", &first_drv_fops); // 注册, 告诉内核
firstdrv_class = class_create(THIS_MODULE, "firstdrv");
firstdrv_class_dev = device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */
gpfcon = (volatile unsigned long *)ioremap(0x56000010, 16);
gpfdat = gpfcon + 1;
return 0;
}
static void first_drv_exit(void)
{
unregister_chrdev(major, "first_drv"); //
device_destroy(firstdrv_class,MKDEV(major,0));
class_destroy(firstdrv_class);
iounmap(gpfcon);
}
module_init(first_drv_init);
module_exit(first_drv_exit);
MODULE_LICENSE("GPL");
测试程序:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
/* firstdrvtest on
* firstdrvtest off
*/
int main(int argc, char **argv)
{
int fd;
int val = 1;
fd = open("/dev/xyz", O_RDWR);
if (fd < 0)
{
printf("can't open!\n");
}
if (argc != 2)
{
printf("Usage :\n");
printf("%s <on|off>\n", argv[0]);
return 0;
}
if (strcmp(argv[1], "on") == 0)
{
val = 1;
}
else
{
val = 0;
}
write(fd, &val, 4);
return 0;
}
在驱动程序中,首先用注册设备驱动,再创建class、class_device,udev机制会根据这两个内容自动创建设备节点,这样设备节点和设备驱动就通过设备号连接起来。操作设备节点/dev/xyz就会通过设备号连接到驱动。这个程序是控led灯的亮灭,天嵌开发板的led口是连在GPB5、6、7、8上,通过GPBCON、GPBDAT来控制各个位。GPBCON的地址为0x56000010,通过ioremap得到虚拟地址,然后操作虚拟地址即可。
测试程序:先执行./firsrdrvtest 主函数会判断变量的个数,此时变量个数为1,执行显示用法。然后./firsrdrvtest on/off时,变量为2,首先打开设备,得到fd,判断主函数第二个参数,当为on时,val为1,然后把fd、val用write函数写入即可调用相关的驱动。