fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4.  
  5. #include <unistd.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <sys/mman.h>
  9.  
  10. #include "platform.h"
  11.  
  12. volatile uint8_t *gpio_base = NULL;
  13.  
  14. #define REG_DEREF(x) (*((volatile uint32_t *)x))
  15. #define GPFSEL0 (REG_DEREF(gpio_base + 0x00))
  16. #define GPFSEL1 (REG_DEREF(gpio_base + 0x04))
  17. #define GPFSEL2 (REG_DEREF(gpio_base + 0x08))
  18. #define GPFSEL3 (REG_DEREF(gpio_base + 0x0C))
  19. #define GPFSEL4 (REG_DEREF(gpio_base + 0x10))
  20. #define GPFSEL5 (REG_DEREF(gpio_base + 0x14))
  21.  
  22. #define GPSET0 (REG_DEREF(gpio_base + 0x1C))
  23. #define GPSET1 (REG_DEREF(gpio_base + 0x20))
  24. #define GPCLR0 (REG_DEREF(gpio_base + 0x28))
  25. #define GPCLR1 (REG_DEREF(gpio_base + 0x2C))
  26.  
  27. #define GPLEV0 (REG_DEREF(gpio_base + 0x34))
  28. #define GPVEL1 (REG_DEREF(gpio_base + 0x38))
  29.  
  30. //TODO: add the rest of the gpio regs and move to header
  31.  
  32. int main()
  33. {
  34. printf("GPIO physical base: %p\n", (void *)GPIO_BASE);
  35.  
  36. int mem_fd = open("/dev/mem", O_RDWR | O_SYNC);
  37. if(mem_fd == -1)
  38. {
  39. printf("Failed to open /dev/mem\n");
  40. }
  41.  
  42. // get a page aligned pointer to memory
  43. uint8_t *buf = malloc(8192);
  44. uint8_t *aligned_buf;
  45. if((uint32_t)buf % 4096 != 0)
  46. {
  47. aligned_buf = buf + (4096 - ((uint32_t)buf % 4096));
  48. }
  49.  
  50. // map it
  51. gpio_base = mmap(aligned_buf, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, mem_fd, GPIO_BASE);
  52. if(gpio_base == NULL)
  53. {
  54. printf("Failed to map GPIO memory\n");
  55. }
  56.  
  57. printf("gpio_base: %p\n", gpio_base);
  58. printf("buf: %p\n", buf);
  59. printf("aligned_buf: %p\n", aligned_buf);
  60.  
  61. // GPIO1 set to output
  62. GPFSEL0 = 0x0;
  63.  
  64. // didn't fix it
  65. usleep(10000);
  66.  
  67. // GPIO1 set to low
  68. GPSET0 = 0x0;
  69.  
  70. // didn't fix it
  71. usleep(10000);
  72.  
  73. // get GPIO1's state
  74. uint32_t state = GPLEV0 & 0x1;
  75. printf("GPIO1: %u\n", state);
  76.  
  77. munmap(gpio_base, 4096);
  78. free(buf);
  79. close(mem_fd);
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty