1.编写Linux设备驱动驱动程序,将该文件复制到(linux 源码目录)/drivers/(目标文件夹)/中
LED驱动(nios2-linux/linux-2.6/drivers/myleds/myleds.c)
//myleds.c
#include "linux/init.h"
#include "linux/module.h"
#include
#include
#include
#include
#include
#include
#define DEV_NAME "myleds"
#define DEV_MAJOR 242
#define na_pio_LED 0x00400000
static int leds_ioctl(struct inode *indode,struct file *file,unsigned int cmd,unsigned long arg)
{
switch(cmd){
case 0:
case 1:
if(arg>3)printk("parameter is wrong!");
writeb(cmd, (na_pio_LED));
return(na_pio_LED);
default:
return(na_pio_LED);
}
}
static struct file_operations leds_fops=
{
.owner=THIS_MODULE,
.ioctl=leds_ioctl,
};
static int leds_init(void)
{
int ret;
printk(KERN_ALERT "call leds_init/n");
ret=register_chrdev(DEV_MAJOR,DEV_NAME,&leds_fops);
if(ret<0){
printk(KERN_ALERT "cannot register leds device!/n");
return ret;}
return 0;
}
static void leds_exit(void)
{
printk(KERN_ALERT "call leds_exit/n");
unregister_chrdev(DEV_MAJOR,DEV_NAME);
}
module_init(leds_init);
module_exit(leds_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("jhj");
2.在目标文件夹(myleds文件夹)中创建Makefile和Kconfig(菜单配置文件),内容分别如下:
#Makefile
obj-$(CONFIG_MYLEDS) += myleds.o
#Kconfig
menu USER_DEVICE_DRIVERS
config MYLEDS
tristate "myleds"
---help---
This is a sample driver programme.
endmenu
注意,如果Kconfig文件中的"tristate"写成"bool",则该模块只能选为Y(编译进内核)或N(不选择),不能选为M(编译为模块,可动态加载)
3.修改上层目录( linux内核源码目录/drivers/)中的Makefile和Kconfig文件,Makefile中加入如下语句
#makefile
obj-y += myleds
Kconfig中加入如下语句:
#Kconfig
source "drivers/myleds/Kconfig"
4.编译内核
make menuconfig
找到我们自己的菜单名,然后按回车或空格进入,用M键使选项前的尖括号里显示M表示该模块要动态加载,也可以按y键选择直接编辑进内核,选择完后exit退出,选择yes或no的对话框通一选yes。
5.加载测试:将生成的zImage文件下载到开发板,开发板上的嵌入式Linux启动后可以用insmod或modprobe加载驱动模块
6.LED测试程序
测试程序(test_led.c)
#include
#include
#include
#include
int main(int argc,int **argv)
{
int on;
int led_no;
int fd;
if(argc!=3 || sscanf(argv[1],"%d",&led_no)!=1 || sscanf(argv[2],"%d",&on)!=1 || on<0 || on>1 || led_no<0 ||led_no>3)
{
printf("input is wrong!");
exit(1);
}
fd=open("/dev/myleds",0);
if(fd<0)
{
perror("open leds device");
exit(1);
}
ioctl(fd,on,led_no);
return 0;
编译
nios2-linux-uclibc-gcc test_led.c -o test_led -elf2flt
cp test_led ~/nios2-linux/uClinux-dist/romfs/bin