1、led驱动代码。led.c
-
#include <linux/module.h>
-
#include <linux/init.h>
-
#include <linux/cdev.h>
-
#include <linux/fs.h>
-
#include <linux/io.h>
-
#include "led.h"
-
-
MODULE_LICENSE("GPL");
-
-
#define GPBCON 0x56000010
-
#define GPBDAT 0x56000014
-
-
unsigned int *led_config;
-
unsigned int *led_data;
-
-
struct cdev cdev;
-
dev_t devno;
-
-
int led_open(struct inode *node, struct file *filp)
-
{
-
led_config = ioremap(GPBCON,4);//将物理地址转化为虚拟地址
-
writel(0x00015400,led_config);// 15400 设置配置寄存器
-
led_data = ioremap(GPBDAT,4);
-
-
return 0;
-
}
-
-
long led_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
-
{
-
switch(cmd)
-
{
-
case LED_ON:
-
writel(0x00,led_data);
-
return 0;
-
-
case LED_OFF:
-
writel(0xff,led_data);
-
return 0;
-
-
default :
-
return -EINVAL;
-
}
-
}
-
-
static struct file_operations led_fops=
-
{
-
.open = led_open,
-
.unlocked_ioctl = led_ioctl,
-
};
-
-
static int led_init()
-
{
-
//设备初始化
-
cdev_init(&cdev, &led_fops);
-
-
//获得设备号
-
alloc_chrdev_region(&devno, 0, 1, "myled");
-
//注册设备
-
cdev_add(&cdev,devno,1);
-
-
return 0;
-
}
-
-
static void led_exit()
-
{
-
//注销设备
-
cdev_del(&cdev);
-
//注销设备号
-
unregister_chrdev_region(devno,1);
-
}
-
-
module_init(led_init);
-
module_exit(led_exit);
2、led.h
点击(此处)折叠或打开
-
#define LED_MAGIC 'L'
-
#define LED_ON _IO(LED_MAGIC,0)
-
#define LED_OFF _IO(LED_MAGIC,1)
3、Makefile
点击(此处)折叠或打开
-
obj-m := led.o
-
KDIR := /home/win/code3/my2440/linux-2.6.39
-
all:
-
make -C $(KDIR) M=$(PWD) modules CROSS_COMPILE=arm-linux- ARCH=arm
-
clean:
-
rm -f *.ko *.o *.mod.o *.mod.c *.symvers *.bak *.order
make生成内核模块,led.ko文件
#make
4、led测试代码。led_app.c
点击(此处)折叠或打开
-
#include <sys/types.h>
-
#include <sys/stat.h>
-
#include <fcntl.h>
-
#include <sys/ioctl.h>
-
#include "led.h"
-
-
int main(int argc, char *argv[])
-
{
-
int fd;
-
int cmd;
-
-
if(argc <2)
-
{
-
printf("Please enter the sencond para!\n");
-
return 0;
-
}
-
-
cmd = atoi(argv[1]);
-
-
fd = open("/dev/myled",O_RDWR);
-
-
if(cmd == 1)
-
ioctl(fd,LED_ON);
-
else if(cmd == 0)
-
ioctl(fd,LED_OFF);
-
-
return 0;
-
}
因为根文件系统没有一些库文件,所以需要采用静态编译的方式编译led_app.c文件
arm-linux-gcc -static led_app.c -o led_app
5、测试代码。
5.1启动开发板,将led.ko 和 led_app放到rootfs文件夹下,用nfs挂接linux服务器下的文件夹
#mount -t nfs -o nolock 192.168.1.101:/home/win/code3/my2440/myroot/rootfs /mnt
#cd /mnt
5.2 加载内核模块led.ko
#insmod led.ko
5.3 查看myled主设备号
#cat /proc/devices
#252 myled
5.4 创建设备文件
#mknod /dev/myled c 252 0
5.5 运行 led_app
#./led_app 1 (点亮所有led)
#./led_app 0 (熄灭所有led)
阅读(1464) | 评论(0) | 转发(0) |