实验环境:
操作系统:Ubuntu Gnome 16.04.2
硬件——tiny4412
android版本——5.0.2
linux kernel版本——3.0.86
androidst stdio版本——3.1
开发步骤:
- 编写驱动
- 编写驱动测试程序
- 编写jni层代码
- 编写APP
1、编写驱动
用于android的驱动与ubuntu上使用的驱动没有区别,为了简单这里不注册字符设备,仅注册杂项设备。
word_count_drv.c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/miscdevice.h>
#include <asm/uaccess.h>
#include <linux/fs.h>
#define DEVICE_NAME "word_count"
#define POOL_SIZE 1024
static unsigned char pool[POOL_SIZE];
static int count_result;
static int misc_minor = 222;
static int word_count_drv_open(struct inode *inode_p, struct file *file_p);
static int word_count_drv_release(struct inode *inode_p, struct file *file_p);
static ssize_t word_count_drv_write(struct file *file_p, const char __user *buf, size_t size, loff_t *loff);
static ssize_t word_count_drv_read(struct file *file_p, char __user *buf, size_t size, loff_t *loff);
static struct file_operations word_count_fops = {
.owner = THIS_MODULE,
.open = word_count_drv_open,
.release = word_count_drv_release,
.read = word_count_drv_read,
.write = word_count_drv_write
};
static struct miscdevice word_count_misc_dev = {
// .minor = misc_minor,
.name = DEVICE_NAME,
.fops = &word_count_fops
};
static _Bool is_letter(char c)
{
if(c >= 'a' && c <= 'z')
return 1;
else if(c >= 'A' && c <= 'Z')
return 1;
return 0;
}
static int word_count(const char *c)
{
int count = 0;
unsigned int flag = 0;/* the last character is letter*/
while(*c != '\0')
{
if(is_letter(*c) == 1)
{
if(flag == 0)
{
count++;
flag = 1;
}
}
else
{
flag = 0;
}
c++;
}
return count;
}
/* miscdevice fops */
static int word_count_drv_open(struct inode *inode_p, struct file *file_p)
{
printk("%s open\n", DEVICE_NAME);
return 0;
}
static int word_count_drv_release(struct inode *inode_p, struct file *file_p)
{
printk("%s release\n", DEVICE_NAME);
return 0;
}
static ssize_t word_count_drv_write(struct file *file_p, const char __user *buf, size_t size, loff_t *loff)
{
printk("%s write\n", DEVICE_NAME);
if(size > POOL_SIZE)
size = POOL_SIZE - 1;
copy_from_user(pool, buf, size);
pool[size] = '\0';
count_result = word_count(pool);
printk("word count is %d\n", count_result);
return size;
}
static ssize_t word_count_drv_read(struct file *file_p, char __user *buf, size_t size, loff_t *loff)
{
printk("%s read\n", DEVICE_NAME);
copy_to_user(buf, &count_result, sizeof(count_result));