Advertisement
Guest User

Untitled

a guest
Aug 6th, 2022
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <inttypes.h>
  9. #include <sys/mman.h>
  10. #include <time.h>
  11.  
  12. #ifndef PAGE_SIZE
  13. #define PAGE_SIZE (4*1024)
  14. #endif
  15. #ifndef BLOCK_SIZE
  16. #define BLOCK_SIZE (4*1024)
  17. #endif
  18.  
  19. #define BCM2708_PERI_BASE 0xFE000000
  20. #define SYST_BASE (BCM2708_PERI_BASE + 0x3000)
  21. #define SYST_CS 0
  22. #define SYST_CLO 1
  23. #define SYST_CHI 2
  24.  
  25. struct bcm2835_peripheral {
  26. unsigned long addr_p;
  27. int mem_fd;
  28. void *map;
  29. volatile unsigned int *addr;
  30. };
  31.  
  32. struct bcm2835_peripheral syst = {SYST_BASE};
  33.  
  34. unsigned short map_peripheral(struct bcm2835_peripheral *p)
  35. {
  36. if (geteuid() != 0)
  37. {
  38. printf("Error, you must be root!\n");
  39.  
  40. return 0;
  41. }
  42.  
  43. // Open /dev/mem
  44. if ((p->mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0)
  45. {
  46. printf("Failed to open /dev/mem, try checking permissions.\n");
  47. return 0;
  48. }
  49.  
  50. p->map = mmap(
  51. NULL,
  52. BLOCK_SIZE,
  53. PROT_READ|PROT_WRITE,
  54. MAP_SHARED,
  55. p->mem_fd, // File descriptor to physical memory virtual file '/dev/mem'
  56. p->addr_p // Address in physical map that we want this memory block to expose
  57. );
  58.  
  59. if (p->map == MAP_FAILED) {
  60. perror("mmap");
  61. return 0;
  62. }
  63.  
  64. p->addr = (volatile unsigned int *)p->map;
  65.  
  66. return 1;
  67. }
  68.  
  69. void unmap_peripheral(struct bcm2835_peripheral *p)
  70. {
  71. munmap(p->map, BLOCK_SIZE);
  72. p->map = MAP_FAILED;
  73. close(p->mem_fd);
  74. }
  75.  
  76. uint64_t nanos(void)
  77. {
  78. struct timespec ts;
  79. timespec_get(&ts, TIME_UTC);
  80. return (uint64_t)ts.tv_nsec;
  81. }
  82.  
  83. uint32_t gpioTick(void)
  84. {
  85. return syst.addr[SYST_CLO];
  86. }
  87.  
  88. int main(void)
  89. {
  90. uint8_t i = 0;
  91. uint32_t ticks = 0;
  92. uint32_t rr = 0;
  93.  
  94. if(!map_peripheral(&syst))
  95. {
  96. printf("Failed to map the physical SYST registers into the virtual memory space.\n");
  97. return -1;
  98. }
  99.  
  100. ticks = gpioTick();
  101.  
  102. for (i=0; i<100; ++i)
  103. {
  104. rr = gpioTick() - ticks;
  105. }
  106.  
  107. printf("%d\n", rr);
  108.  
  109. unmap_peripheral(&syst);
  110.  
  111. return 0;
  112. }
  113.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement