led.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #define DEVICE_FILE "/dev/gpio_led"
  7. int main()
  8. {
  9. int fd;
  10. char write_buf[2];
  11. ssize_t written;
  12. // 打开设备文件
  13. fd = open(DEVICE_FILE, O_RDWR);
  14. if (fd < 0) {
  15. perror("open");
  16. return -1;
  17. }
  18. // 在死循环中交替写入 0 和 1,控制 LED
  19. int i = 0;
  20. while (1) {
  21. // 每次循环写入 1(开启 LED)或 0(关闭 LED)
  22. if (i % 2 == 0) {
  23. write_buf[0] = '1'; // LED 开
  24. } else {
  25. write_buf[0] = '0'; // LED 关
  26. }
  27. // 向设备写入数据
  28. written = write(fd, write_buf, 1);
  29. if (written < 0) {
  30. perror("write");
  31. close(fd);
  32. return -1;
  33. } else {
  34. printf("Wrote %c to the device\n", write_buf[0]);
  35. }
  36. // 延迟 1 秒钟
  37. sleep(1);
  38. i++;
  39. }
  40. // 关闭设备文件
  41. close(fd);
  42. return 0;
  43. }