라즈베리파이에서 GPIO를 사용할 때 라이브러리를 사용하지 않고 직접제어하는 방법은 다음과 같다.
//#define BCM2708_PERI_BASE 0x20000000 // Pi3 이전 모델
#define BCM2708_PERI_BASE 0x3F000000 // Pi3
#define GPIO_BASE (BCM2708_PERI_BASE + 0x200000)
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#define PAGE_SIZE (4*1024)
#define BLOCK_SIZE (4*1024)
int mem_fd;
void *gpio_map;
volatile unsigned *gpio;
#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
#define OUT_GPIO(g) *(gpio+((g)/10)) |= (1<<(((g)%10)*3))
#define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))
#define GPIO_SET *(gpio+7)
#define GPIO_CLR *(gpio+10)
#define GET_GPIO(g) (*(gpio+13)&(1<<g)) // 0 if LOW, (1<<g) if HIGH
#define GPIO_PULL *(gpio+37)
#define GPIO_PULLCLK0 *(gpio+38)
void setup_io();
int main(int argc, char **argv)
{
int i,g;
setup_io();
g = 14; // GPIO14
INP_GPIO(g);
OUT_GPIO(g);
for(i=0; i<10; i++) {
GPIO_CLR = 1<<g;
sleep(1);
GPIO_SET = 1<<g;
sleep(1);
if (GET_GPIO(g))
printf("Button pressed!\n");
else
printf("Button released!\n");
}
return 0;
}
void setup_io()
{
if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
printf("can't open /dev/mem \n");
exit(-1);
}
gpio_map = mmap(
NULL, //Any adddress in our space will do
BLOCK_SIZE, //Map length
PROT_READ|PROT_WRITE, //Enable reading & writting to mapped memory
MAP_SHARED, //Shared with other processes
mem_fd, //File to map
GPIO_BASE //Offset to GPIO peripheral
);
close(mem_fd); //No need to keep mem_fd open after mmap
if (gpio_map == MAP_FAILED) {
printf("mmap error %d\n", (int)gpio_map);//errno also set!
exit(-1);
}
gpio = (volatile unsigned *)gpio_map;
}
'컴퓨터 > Linux' 카테고리의 다른 글
Raspberry Pi UART 사용 (C 프로그램) (0) | 2022.09.22 |
---|---|
Raspberry Pi UART 설정 (0) | 2022.09.21 |
Raspberry Pi 설치 방법 (0) | 2022.09.20 |
Raspberry Pi 윈도우 원격 데스크탑 제어 (0) | 2022.09.20 |
Raspberry Pi의 GPIO 사용 (wiringPi 라이브러리) (0) | 2022.09.20 |
댓글