Linux驱动程序实例:
假设我们要编写一个简单的LED闪烁驱动程序,以下是一个基本的实例:
1. 驱动程序代码(led_driver.c)
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/gpio.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "led_driver"
#define GPIO_PIN 18 // 假设使用GPIO18
static int major_number;
static struct class *led_class;
static struct device *led_device;
static int led_open(struct inode *inode, struct file *file)
{
printk(KERN_INFO "LED driver opened
");
return 0;
}
static long led_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case 0: // 关闭LED
gpio_set_value(GPIO_PIN, 0);
printk(KERN_INFO "LED turned off
");
break;
case 1: // 打开LED
gpio_set_value(GPIO_PIN, 1);
printk(KERN_INFO "LED turned on
");
break;
default:
printk(KERN_INFO "Invalid command
");
return -EINVAL;
}
return 0;
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = led_open,
.unlocked_ioctl = led_ioctl,
};
static int __init led_init(void)
{
int ret;
ret = gpio_request(GPIO_PIN, "led_gpio");
if (ret < 0) {
printk(KERN_INFO "Failed to request GPIO
");
return ret;
}
gpio_direction_output(GPIO_PIN, 0);
major_number = register_chrdev(0, DEVICE_NAME, &fops);
if (major_number < 0) {
printk(KERN_INFO "Failed to register device
");
gpio_free(GPIO_PIN);
return major_number;
}
led_class = class_create(THIS_MODULE, DEVICE_NAME);
if (IS_ERR(led_class)) {
unregister_chrdev(major_number, DEVICE_NAME);
gpio_free(GPIO_PIN);
printk(KERN_INFO "Failed to create class
");
return PTR_ERR(led_class);
}
led_device = device_create(led_class, NULL, MKDEV(major_number, 0), NULL, DEVICE_NAME);
if (IS_ERR(led_device)) {
class_destroy(led_class);
unregister_chrdev(major_number, DEVICE_NAME);
gpio_free(GPIO_PIN);
printk(KERN_INFO "Failed to create device
");
return PTR_ERR(led_device);
}
printk(KERN_INFO "LED driver loaded
");
return 0;
}
static void __exit led_exit(void)
{
device_destroy(led_class, MKDEV(major_number, 0));
class_destroy(led_class);
unregister_chrdev(major_number, DEVICE_NAME);
gpio_free(GPIO_PIN);
printk(KERN_INFO "LED driver unloaded
");
}
module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple LED driver");
2. 编译驱动程序
创建一个Makefile文件:
obj-m += led_driver.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
运行make
命令来编译驱动程序。
3. 加载和卸载驱动程序
使用insmod
命令加载驱动程序:
sudo insmod led_driver.ko
使用rmmod
命令卸载驱动程序:
sudo rmmod led_driver
4. 测试驱动程序
使用ioctl
命令来控制LED的开关:
sudo chmod 666 /dev/led_driver
echo 1 > /dev/led_driver # 打开LED
echo 0 > /dev/led_driver # 关闭LED
优势:
应用场景:
常见问题及解决方法:
class_create
和device_create
函数的返回值,确保没有错误。sudo
命令来加载驱动程序和访问设备节点。这个实例展示了如何编写一个简单的LED闪烁驱动程序,并说明了其编译、加载、测试的过程。
领取专属 10元无门槛券
手把手带您无忧上云