led.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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[] = "Hello from user space!";
  11. char read_buf[100];
  12. // 打开设备文件
  13. fd = open(DEVICE_FILE, O_RDWR);
  14. if (fd < 0) {
  15. perror("open");
  16. return -1;
  17. }
  18. // 向设备写入数据
  19. ssize_t written = write(fd, write_buf, strlen(write_buf));
  20. if (written < 0) {
  21. perror("write");
  22. close(fd);
  23. return -1;
  24. } else {
  25. printf("Wrote %zd bytes to the device.\n", written);
  26. }
  27. // 从设备读取数据
  28. ssize_t read_bytes = read(fd, read_buf, sizeof(read_buf));
  29. if (read_bytes < 0) {
  30. perror("read");
  31. close(fd);
  32. return -1;
  33. } else if (read_bytes == 0) {
  34. printf("No data read from the device.\n");
  35. } else {
  36. read_buf[read_bytes] = '\0';
  37. printf("Read from the device: %s\n", read_buf);
  38. }
  39. // 关闭设备文件
  40. close(fd);
  41. return 0;
  42. }