看了老罗的Android之旅介绍的Android硬件抽象层的学习后,这里总结和实现一个字符驱动程序,同时在Android层实现一个c的可执行文件来测试这个驱动程序,记录下来,以便查阅!
首先在kerner/drivers下创建一个目录memdev,然后在该目录下touch memdev.c文件
#include
#include
#include
#include
#include "memdev.h"
static int memdev_major = 0;
static int memdev_data = 0;
static ssize_t memRead(struct file*, char*, size_t, loff_t *);
static ssize_t memWrite(struct file*, const char *, size_t, loff_t *);
struct file_operations memdev_fops =
{
.owner = THIS_MODULE,
.read = memRead,
.write = memWrite
};
static int __init memdev_init()
{
int ret;
ret = register_chrdev(memdev_major, MEMDEV_NAME, &memdev_fops);
if(ret < 0)
{
printk(KERN_ALERT "memdev register fial!\n");
}
else
{
printk(KERN_ALERT "memdev register success!\n");
memdev_major = ret;
printk(KERN_ALERT "Major = %d\n", memdev_major);
}
return 0;
}
static void __exit memdev_exit()
{
unregister_chrdev(memdev_major, MEMDEV_NAME);
printk(KERN_ALERT "memdev exit now!");
}
static ssize_t memRead(struct file* filp, char* buf, size_t len, loff_t *off)
{
if(copy_to_user(buf, &memdev_data,sizeof(int)))
{
return -EFAULT;
}
return sizeof(int);
}
static ssize_t memWrite(struct file* filp, const char* buf, size_t len, loff_t *off)
{
if(copy_from_user(&memdev_data, buf, sizeof(int)))
{
return -EFAULT;
}
printk(KERN_ALERT "write = %d\n", memdev_data);
return sizeof(int);
}
MODULE_LICENSE("GEL");
module_init(memdev_init);
module_exit(memdev_exit);
然后在该目录下创建Kconfig和Makefile文件
在Kconfig中
config MEMDEV
tristate "Javen First Android Driver"
default n
help
This is the first Android Driver of Javen.tang
obj-$(CONFIG_MEMDEV)+=memdev.o
接着在上一层的drivers目录下的Kconfig和Makefile添加相关代码
在/drivers/Kconfig中的最后添加
source "drivers/memdev/Kconfig"
obj-$(CONFIG_MEMDEV) += memdev/
把memdev.ko拷贝到/system/lib/modules下,然后insmod memdev.ko
这里加载驱动成功后,分配的主设备号为248, 然后在/dev目录下穿件节点
cd /dev
mknod memdev c 248 0
这个时候驱动就加载完了,现在我们需要写一个测试程序来测试这个驱动的正确性
在ics/external中创建一个memdevapp目录
在这目录下创建memdevapp.c测试程序
#include
#include
#include
#include
#define DEVICE_NAME "/dev/memdev"
int main(int argc, char** argv)
{
int fd = -1;
int val = 1;
fd = open(DEVICE_NAME, O_RDWR);
if(fd == -1)
{
printf("Failed to open device %s\n", DEVICE_NAME);
return -1;
}
printf("Read original value:\n");
read(fd, &val, sizeof(val));
printf("value == %d\n",val);
val = 5;
printf("Write value %d to %s\n", val, DEVICE_NAME);
write(fd, &val, sizeof(val));
printf("Read the value again:\n");
read(fd, &val, sizeof(val));
printf("value == %d\n",val);
close(fd);
return 0;
}
同时创建Android.mk来编译这个可执行测试程序
LOCAL_PATH:=$(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS:=optional
LOCAL_MODULE:=memdevapp
LOCAL_SRC_FILES:=$(call all-subdir-c-files)
include $(BUILD_EXECUTABLE)
把这个可执行性文件memdevapp拷贝到板子的/system/bin下,然后./memdevapp