led.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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[100] = "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 read_bytes = read(fd, read_buf, sizeof(read_buf));
  20. if (read_bytes < 0) {
  21. perror("read");
  22. close(fd);
  23. return -1;
  24. } else if (read_bytes == 0) {
  25. printf("No data read from the device.\n");
  26. } else {
  27. read_buf[read_bytes] = '\0';
  28. printf("Read from the device: %s\n", read_buf);
  29. }
  30. // 向设备写入数据
  31. ssize_t written = write(fd, write_buf, strlen(write_buf));
  32. if (written < 0) {
  33. perror("write");
  34. close(fd);
  35. return -1;
  36. } else {
  37. printf("Wrote %zd bytes to the device.\n", written);
  38. }
  39. // 从设备读取数据
  40. ssize_t read_bytes = read(fd, read_buf, sizeof(read_buf));
  41. if (read_bytes < 0) {
  42. perror("read");
  43. close(fd);
  44. return -1;
  45. } else if (read_bytes == 0) {
  46. printf("No data read from the device.\n");
  47. } else {
  48. read_buf[read_bytes] = '\0';
  49. printf("Read from the device: %s\n", read_buf);
  50. }
  51. // 关闭设备文件
  52. close(fd);
  53. return 0;
  54. }