ARM-linux驱动学习:led驱动程序编写练习(2014-8-22)

来源:互联网 发布:苹果电脑mac玩英雄联盟 编辑:程序博客网 时间:2024/06/06 07:44

LED驱动程序:led_dev.c


#include <linux/init.h>#include <linux/module.h>#include <linux/fs.h>#include <asm/uaccess.h>#include <asm/io.h>static volatile unsigned int *GPJ2CON,*GPJ2DAT;static int major = 0;static int led_open(struct inode *pi, struct file *pf)//主要用于初始化{        printk("<open> led driver file open.\n");        *GPJ2CON &= 0xffff0000;        *GPJ2CON |= 0x00001111;        *GPJ2DAT |= 0x0f;            return 0;}static int led_release(struct inode *pi, struct file *pf){        printk("<release> test release.\n");        return 0;}static ssize_t led_write(struct file *pf, const char __user *pbuf, size_t len, loff_t *ppos){        char *after;        int a = simple_strtol(pbuf,&after,16);        *GPJ2DAT = ~a;        return 4;}static ssize_t led_read(struct file *pf, char __user *pbuf, size_t len, loff_t *ppos){        printk("<read> GPJ2DAT = %x\n",*GPJ2DAT);        printk("<read> buf: %s",pbuf);        return 0;}static struct file_operations led_fops ={        .owner     = THIS_MODULE,        .open      = led_open,        .release   = led_release,        .write     = led_write,        .read      = led_read,};static __init int test_init(void){        major = register_chrdev(0, "LED", &led_fops);        printk("major = %d\n",major);        GPJ2CON = ioremap(0xe0200280, 8);        GPJ2DAT = GPJ2CON + 1;        printk("GPJ2CON:0x%p,GPJ2DAT:0x%p\n", GPJ2CON, GPJ2DAT);        return 0;}static __exit void test_exit(void){        iounmap(GPJ2CON);        unregister_chrdev(major, "LED");        *GPJ2DAT |= 0x0f;        printk("\n      Goodbye!\n\n");}module_init(test_init);module_exit(test_exit);MODULE_LICENSE("GPL");MODULE_AUTHOR("henry");MODULE_DESCRIPTION("This is test demo");


在kernel/drivers/char下的Kconfig里面添加:

config LED
        tristate "LED DEV"
        default y

Makefile里面添加:obj-m  += led_dev.o


在kernel下编译:make menuconfig

                            make modules

kernel/drivers/char下的led_dev.ko文件下载到开发板上:

tftp  -g  -r  led_dev.ko 192.168.x.x


在开发板上挂载该LED驱动模块:insmod  led_dev.ko

查看挂载的模块:          lsmod

查看设备:                    cat /proc/devices

创建字符设备:             mknod led c 251 1    (命令 设备名 类型 主设备号 次设备号)

通过echo写入内容:     echo  1  >  led

卸载模块:                    rmmod led_dev


应用程序:ledapp.c

#include <stdio.h>#include <sys/types.h>    #include <sys/stat.h>    #include <fcntl.h>#include <string.h>#include <unistd.h>#include <stdlib.h>int main(void){        char buf[20];        int fd;         fd = open("led",O_RDWR);        while(1)        {                   fgets(buf,sizeof(buf),stdin);                write(fd,buf,sizeof(buf));                read(fd,buf,sizeof(buf));        }           return 0;}



编译应用程序:arm-none-linux-gnueabi-gcc -static ledapp.c -o ledapp            (-static添加静态库)

下载到开发板上并运行:./ledapp

0 0