Advertisement
Guest User

Untitled

a guest
Apr 5th, 2014
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <sys/mman.h>
  4. #include <unistd.h>
  5.  
  6. #define BCM2708_PERI_BASE 0x20000000
  7. #define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */
  8. #define LED_ACT 16
  9.  
  10. #define BLOCK_SIZE (4*1024)
  11.  
  12. int mem_fd;
  13. void *gpio_map;
  14. volatile unsigned *gpio;
  15.  
  16. // GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y)
  17. #define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
  18. #define OUT_GPIO(g) *(gpio+((g)/10)) |= (1<<(((g)%10)*3))
  19. #define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))
  20.  
  21. #define GPIO_SET *(gpio+7) // sets bits which are 1 ignores bits which are 0
  22. #define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
  23.  
  24. int init_io()
  25. {
  26. /* open /dev/mem */
  27. if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
  28. printf("can't open /dev/mem \n");
  29. return(-1);
  30. }else{
  31. printf("/dev/mem opened\n");
  32.  
  33. /* mmap GPIO */
  34. gpio_map = mmap(
  35. NULL, //Any adddress in our space will do
  36. BLOCK_SIZE, //Map length
  37. PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory
  38. MAP_SHARED, //Shared with other processes
  39. mem_fd, //File to map
  40. GPIO_BASE //Offset to GPIO peripheral
  41. );
  42.  
  43. close(mem_fd);
  44. printf("/dev/mem closed\n");
  45.  
  46. if (gpio_map == MAP_FAILED) {
  47. printf("mmap error %d\n", (int)gpio_map);//errno also set!
  48. return(-1);
  49. }else{
  50. printf("mmap Success.\n");
  51. }
  52.  
  53. }
  54.  
  55. // Always use volatile pointer!
  56. gpio = (volatile unsigned *)gpio_map;
  57.  
  58. return 0;
  59. }
  60.  
  61.  
  62. int main(){
  63.  
  64. if(init_io() == -1)
  65. {
  66. printf("Failed to map the physical GPIO registers into the virtual memory space.\n");
  67. return -1;
  68. }
  69.  
  70. // must use INP_GPIO before we can use OUT_GPIO
  71. INP_GPIO(LED_ACT);
  72. OUT_GPIO(LED_ACT);
  73.  
  74. int repeat;
  75. for (repeat=1; repeat<5; repeat++)
  76. {
  77. GPIO_SET = 1 << LED_ACT;
  78. printf("LED OFF\n");
  79. sleep(2);
  80.  
  81. GPIO_CLR = 1 << LED_ACT;
  82. printf("LED ON\n");
  83. sleep(1);
  84. }
  85.  
  86. printf("- finished -\n");
  87. return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement