无操作系统下LED驱动:
#define led_ctrl_reg LED_CTRL_REG
#define led_data_reg LED_DATA_REG
/*初始化LED*/
void InitLight() {
led_ctrl_reg |= 1 << n;
}
/*点亮LED*/
void LightOn() {
led_data_reg |= 1 << n;
}
/*熄灭LED*/
void LightOff() {
led_data_reg &= ~(1 << n);
}
最后将上述函数提供给应用程序使用
有操作系统下LED驱动:
#include ... /*包含多个头文件*/
/*设备结构体*/
struct light_dev {
struct cdev cdev;
unsigned char val; /*LED亮时为1,灭时为0*/
}
/*Light设备实例、主设备号*/
struct light_dev *light_devp;
int light_major = LIGHT_MAJOR;
struct file_operations light_fops = {
.owner = THIS_MODULE;
.read = light_read;
.write = light_write;
.ioctl = light_ioctl;
.open = light_open;
.release = light_release;
}
/*模块初始化函数*/
static int __init light_init(void) {
dev_t dev = MKDEV(light_major, 0);
/*申请设备号*/
//1.静态申请(主设备号确定)
register_chrdev_region(dev, 1, "LED");
//2.动态申请(分配主设备号)
alloc_chrdev_region(&dev, 0, 1, "LED");
light_major = MAJOR(dev);
/*分配Lihgt设备结构体*/
light_devp = kmalloc(sizeof(struct light_dev), GFP_KERNEL);
memset(light_devp, 0, sizeof(struct light_dev));
/*注册字符设备*/
cdev_init(&dev->cdev, &light_fops);
cdev_add(&dev->cdev, dev ,1);
light_init();
return 0;
}
void light_cleanup(void) {
cdev_del(&light_devp->cdev);
kfree(light_devp);
unregister_chrdev_region(MKDEV(light_major, 0), 1);
}
module_init(light_init);
module_exit(light_cleanup);
下面是文件操作的实现:
/*Light设备的打开关闭函数*/
int light_open(struct inode *inode, struct file *filp) {
struct light_dev *dev;
dev = container_of(inode->i_cdev, struct light_dev, cdev);
filp->private_data = dev;
return 0;
}
int light_release(struct inode *inode, struct file *filp) {
return 0;
}
/*Light设备的读写函数*/
ssize_t light_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) {
struct light_dev *dev = filp->private_data;
if(copy_to_user(buf, &(dev->val), 1)) {
return -EFAULT;
}
return 1;
}
ssize_t light_write(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) {
struct light_dev *dev = filp->private_data;
if(copy_from_user( &(dev->val), buf, 1)) {
return -EFAULT;
}
if(dev->val == 1) {
light_on();
} else {
light_off();
}
return 1;
}
/*Light设备的控制函数*/
int light_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, usigned long arg) {
struct light_dev *dev = filp->private;
switch(cmd) {
case LIGHT_ON:
dev->val = 1;
light_on();
break;
case LIGHT_OFF:
dev-val = 0;
light_off();
break;
default:
return -ENOTTY;
}
return 0;
}
代码没有注重细节,而是在重在体现LED字符设备结构