//4led.c
#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/miscdevice.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/spinlock.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <asm/hardware.h>
#define DEVICE_NAME "ledwen"
#define LED_MAJOR 240
MODULE_LICENSE("GPL"); //用于消除版权警告诉
static unsigned long led_table [] = {
GPIO_B7,
GPIO_B8,
GPIO_B9,
GPIO_B10,
};
/*************************************************************************/
static int matrix4_leds_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
switch(cmd)
{
case 0:
case 1:
if (arg > 4)
return -EINVAL;
write_gpio_bit(led_table[arg], !cmd);
printk("led : %d %d",arg , cmd \n);
default:
return -EINVAL;
}
}
/*************************************************************************/
static struct file_operations matrix4_leds_fops = {
owner: THIS_MODULE,
ioctl: matrix4_leds_ioctl,
};
static devfs_handle_t devfs_handle;
static int __init matrix4_leds_init(void)
{
int ret;
int i;
ret = register_chrdev(LED_MAJOR, DEVICE_NAME, &matrix4_leds_fops);
if (ret < 0) {
printk(DEVICE_NAME " can't register major number\n");
return ret;
}
devfs_handle = devfs_register(NULL, DEVICE_NAME, DEVFS_FL_DEFAULT,
LED_MAJOR, 0, S_IFCHR | S_IRUSR | S_IWUSR, &matrix4_leds_fops, NULL);
for (i = 0; i < 8; i++) {
set_gpio_ctrl (led_table[i] | GPIO_PULLUP_EN | GPIO_MODE_OUT);
write_gpio_bit(led_table[i], 1);
}
printk(DEVICE_NAME " initialized\n");
return 0;
}
static void __exit matrix4_leds_exit(void)
{
devfs_unregister(devfs_handle);
unregister_chrdev(LED_MAJOR, DEVICE_NAME);
}
module_init(matrix4_leds_init);
module_exit(matrix4_leds_exit);
上面代码在虚拟机中用命令:
#arm-linux-gcc -D__KERNEL__ -I/friendly-arm/kernel/include -DKBUILD_BASENAME=matrix4-leds -DMODULE -c -o 4led.o 4led.c
将其进行编译。
上面的编译命令中 -DKBUILD_BASENAME=matrix4-leds 段不知道为何意思,实践操作发现这段去掉也可以编译通过,并能运行。
编译通过后,下传到目标板,用命令:insmod 4led.o 将其加载。(注意文件名不是led了,而是;ledwen)