树莓派linux驱动学习之hello world

时间:2023-03-08 20:48:59
树莓派linux驱动学习之hello world

最近想学习一下linux驱动,看了一些书和教学视频,大概了解了一下,不过要想深入,肯定需要实践。手上有几块linux的板子,最终选择了树莓派作为我的实验平台,资料比较丰富,接口也比较简单。

程序员的入门经典当然就是hello world程序了,我的第一个实验就是要搭建实验环境和工具链,通过交叉编译的方式,在上位机完成hello world驱动程序的编写,最终在板子上运行。

一、安装树莓派系统

        首先要在树莓派上安装系统,这个网上的资料比较多,就不细说了,我使用的是2013-09-25-wheezy-raspbian,下载地址可见:http://www.raspberrypi.org/downloads
          最终搭建的平台如下,后期的通讯可以直接使用串口,就不需要HDMI输出了: 
树莓派linux驱动学习之hello world

二、下载交叉编译工具链

        交叉编译工具链可以帮助我们在PC机上完成驱动程序的开发,此外还需要和下位机配套的Linux内核代码,树莓派官方已经为我们提供了相应的内核代码和工具链,直接使用git下载:
    $ git clone git://github.com/raspberrypi/linux.git RpiLinux
    $ git clone git://github.com/raspberrypi/tools.git RpiTools

需要注意的是下载的时候要注意内核代码是否和我们板子中的内核版本相同,我使用的是3.6.11+,所以下载代码的时候也要选择3.6.y这个版本。

三、编写驱动代码

我们在上位机编写hello world的代码:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h> MODULE_LICENSE("Dual BSD/GPL"); static int hello_init(void)
{
printk(KERN_ALERT"Hello, world\n");
return 0;
} static void hello_exit(void)
{
printk(KERN_ALERT"Goodbye, cruel world\n");
} module_init(hello_init);
module_exit(hello_exit);

相应的makefile代码:

ifneq ($(KERNELRELEASE),)

obj-m := hello.o

else

KDIR := /home/hcx/work/boards/RPi/kernel/linux-rpi-3.6.y
all:
make -C $(KDIR) M=$(PWD) modules ARCH=arm CROSS_COMPILE=/home/hcx/work/boards/RPi/kernel/RpiTools/arm-bcm2708/arm-bcm2708hardfp-linux-gnueabi/bin/arm-bcm2708hardfp-linux-gnueabi- clean:
rm -f *.ko *.o *.mod.o *.mod.c *.symvers modul* endif

编译完成后,我们通过U盘将hello.ko文件拷贝到树莓派中,然后通过insmod插入模块,结果如下:

树莓派linux驱动学习之hello world

----------------------------------------------------------------

欢迎大家转载我的文章。

转载请注明:转自古-月

http://blog.csdn.net/hcx25909

欢迎继续关注我的博客