驱动程序
cs
#include<linux/init.h>
#include<linux/module.h>
#include<linux/fs.h>
#include<linux/uaccess.h>
#include<linux/io.h>
#include"head.h"
unsigned int major;
unsigned int *vir_moder;
unsigned int *vir_odr;
unsigned int *vir_rcc;
char kbuf[128] = {0};
int mycdev_open(struct inode *inode, struct file *file){
printk("%s:%s:%d\n",__FILE__, __func__, __LINE__);
return 0;
}
ssize_t mycdev_read(struct file *file, char *ubuf, size_t size, loff_t *lof){
if( copy_to_user(ubuf, kbuf, size) ){
printk("copy_to_user fail\n");
}
printk("%s:%s:%d\n",__FILE__, __func__, __LINE__);
return 0;
}
ssize_t mycdev_write(struct file *file, const char *ubuf, size_t size, loff_t *lof){
if( copy_from_user(kbuf, ubuf, size) ){
printk("copy_from_user fail\n");
}
printk("%s:%s:%d\n",__FILE__, __func__, __LINE__);
if(kbuf[0] == '0'){
//灭灯
(*vir_odr) &= ~(0x1 << 10);
}
else if(kbuf[0] == '1'){
//亮灯
(*vir_odr) |= (0x1 << 10);
}
return 0;
}
int mycdev_close(struct inode *inode, struct file *file){
printk("%s:%s:%d\n",__FILE__, __func__, __LINE__);
return 0;
}
//定义操作方法结构体
struct file_operations fops = {
.open = mycdev_open,
.read = mycdev_read,
.write = mycdev_write,
.release = mycdev_close,
};
static int __init mycdev_init(void){
major = register_chrdev(0,"mychrdev",&fops);
if(major < 0){
printk("字符设备驱动注册失败\n");
return major;
}
printk("字符设备驱动注册成功major = %d\n",major);
//进行寄存器的地址映射
vir_moder = ioremap(PHY_LED1_MODER, 4);
if(vir_moder == NULL){
printk("物理内存地址映射失败%d\n", __LINE__);
return -1;
}
vir_odr = ioremap(PHY_LED1_ODR, 4);
if(vir_odr == NULL){
printk("物理内存地址映射失败%d\n", __LINE__);
return -1;
}
vir_rcc = ioremap(PHY_RCC, 4);
if(vir_rcc == NULL){
printk("物理内存地址映射失败%d\n", __LINE__);
return -1;
}
//初始化寄存器
(*vir_rcc) |= (0x1 << 4);
(*vir_moder) &= ~(0x3 << 20);
(*vir_moder) |= (0x1 << 20);
(*vir_odr) &= ~(0x1 << 10); //默认关灯
return 0;
}
static void __exit mycdev_exit(void){
//取消内存映射
iounmap(vir_moder);
iounmap(vir_odr);
iounmap(vir_rcc);
//注销字符设备驱
unregister_chrdev(major, "mychrdev");
}
module_init(mycdev_init);
module_exit(mycdev_exit);
MODULE_LICENSE("GPL");
应用程序
cs
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<string.h>
int main(int argc, void const *argv[]){
char buf[128] = {0};
int fd = open("/dev/mychrdev", O_RDWR);
if(fd < 0){
printf("打开设备文件失败\n");
return -1;
}
printf("打开设备文件成功\n");
while(1){
printf("输入0灭灯,输入1亮灯>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = 0;
write(fd, buf, sizeof(buf));
/*
bzero(buf,sizeof(buf));
read(fd, buf, sizeof(buf));
printf("buf:%s\n", buf);
*/
}
close(fd);
return 0;
}
头文件
cs
#ifndef __HEAD_H__
#define __HEAD_H__
#define PHY_LED1_MODER 0X50006000
#define PHY_LED1_ODR 0X50006014
#define PHY_RCC 0X50000A28
#endif