一个简单的 LED 控制节点示例代码,使用 sysfs 接口与 Linux 内核交互

一个简单的 LED 控制节点示例代码,使用 sysfs 接口与 Linux 内核交互:

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/gpio.h>

#define LED_PIN 4 // GPIO4

static int led_major;

static ssize_t led_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
{
    return 0; // 不支持读取
}

static ssize_t led_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)
{
    char value;
    if (count > 0 && get_user(value, buf) == 0) {
        gpio_set_value(LED_PIN, (value != '0'));
        return count;
    }
    return -EINVAL;
}

static struct file_operations led_fops = {
    .owner = THIS_MODULE,
    .read = led_read,
    .write = led_write,
};

static int __init led_init(void)
{
    if (gpio_request(LED_PIN, "led") < 0) {
        printk(KERN_ALERT "LED: Failed to request GPIO pin\n");
        return -ENODEV;
    }

    if (gpio_direction_output(LED_PIN, 0) < 0) {
        printk(KERN_ALERT "LED: Failed to set GPIO direction\n");
        gpio_free(LED_PIN);
        return -ENODEV;
    }

    led_major = register_chrdev(0, "led", &led_fops);
    if (led_major < 0) {
        printk(KERN_ALERT "LED: Failed to register character device\n");
        gpio_free(LED_PIN);
        return -ENODEV;
    }

    printk(KERN_INFO "LED: Initialized successfully\n");

    return 0;
}

static void __exit led_exit(void)
{
    unregister_chrdev(led_major, "led");
    gpio_set_value(LED_PIN, 0);
    gpio_free(LED_PIN);
    printk(KERN_INFO "LED: Uninitialized\n");
}

module_init(led_init);
module_exit(_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("LED control node"); 

这个驱动程序用于控制 Linux 系统中连接到 GPIO4 引脚的 LED 灯。它创建一个字符设备节点 /dev/led,通过 sysfs 接口让用户空间程序可以写入 '0' 或 '1' 来控制 LED 灯的开关状态。请注意,需要运行此驱动程序的系统已经支持 GPIO 和 sysfs 接口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全职编程-叶秋然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值