1. 程式人生 > 其它 >字元裝置驅動:LED核心實現方式

字元裝置驅動:LED核心實現方式

1. 環境:

1.1 開發板:正點原子 I.MX6U ALPHA V2.2

1.2 開發PC:Ubuntu20.04

1.3 U-boot:uboot-imx-rel_imx_4.1.15_2.1.0_ga.tar.bz2

1.4 LInux核心:linux-imx-rel_imx_4.1.15_2.1.0_ga.tar.bz2

1.5 rootfs:busybox-1.29.0.tar.bz2製作

1.6 交叉編譯工具鏈:gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabihf.tar.xz

2. 硬體控制說明

2.1 由GPIO1 PIN3控制,高---熄滅, 低---點亮

3. 將LED驅動編譯進核心,路徑:Device Drivers--->LED Support--->LED Support for GPIO connected LEDs

4. 修改裝置樹,在根節點"/{}"中增加gpioled子節點,此實驗效果為,系統啟動完畢,LED就會自動心跳閃爍

 1     gpioled {
 2         compatible = "gpio-leds";    //此屬性一定要是gpio-leds,否則驅動無法匹配,即與drivers\leds\leds-gpio.c的of_match_table一致
 3 
 4         //增加LED節點,根據需要增加,這裡增加一個
5 led0 { 6 label = "red"; //可選項,起一個別名,可用於測試程式碼或者其他程式開啟 7 gpios = <&gpio1 3 GPIO_ACTIVE_HIGH>; //給節點賦初值 8 linux,default-trigger = "heartbeat"; //設定心跳 9 default-state = "on"; //設定預設狀態為開啟 10 }; 11 };

5. 測試程式碼

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <sys/types.h>
 4 #include <sys/stat.h>
 5 #include <fcntl.h>
 6 
 7 #define LED_ON                  1
 8 #define LED_OFF                 0
 9 
10 
11 int main(int argc, char **argv)
12 {
13     int fd;
14 
15     fd = open("/sys/class/leds/red/brightness", O_RDWR);
16 
17     printf("fd = %d\n", fd);
18     if(fd < 0)
19     {
20         perror("open fail!\n");
21 
22         exit(1);
23     }
24 
25 #if 0
26 
27     if(strcmp(argv[1], "on") == 0)
28     {
29         if(ioctl(fd, LED_ON) < 0)
30             perror("ioctrl fail:led on\n");
31         else
32             printf("ioctl ok:led on\n");
33     }
34     else if(strcmp(argv[1], "off") == 0)
35     {
36         if(ioctl(fd, LED_OFF) < 0)
37              perror("ioctrl fail:led off\n");
38         else
39             printf("ioctl ok:led off\n");
40     }
41     else
42     {
43         perror("command is invalid!\n");
44     }
45 
46 
47 #else
48      if(strcmp(argv[1], "on") == 0)
49      {
50     
51         if(write(fd, "1", sizeof("1")) < 0)
52         {
53             perror("write fail:led on!\n");
54             exit(1);
55         }
56         else
57         {
58             printf("write ok:led on!\n");
59         }
60      }
61      else if(strcmp(argv[1], "off") == 0)
62      {
63   
64         if(write(fd, "0", sizeof("0")) < 0)
65         {
66             perror("write fail:led off!\n");
67             exit(1);
68         }
69         else
70         {
71             printf("write ok:led off!\n");
72         }
73      }
74      else
75     {
76         perror("command is invalid!\n");
77     }
78 
79 
80 #endif
81 
82     close(fd);
83     return 0;
84 }
View Code

總結:

1. 核心需要增加LED驅動的支援

2. 裝置樹中,在根目錄下增加對LED節點,且對其屬性進行設定

3. 測試程式碼,寫入的是"1"或“0”字串,進行控制