Skip to content
Snippets Groups Projects
Select Git revision
  • f42b4f3430997fd4f34fedea40e1265d8fcd55a9
  • main default protected
2 results

pir_sensor.c

Blame
  • pir_sensor.c 4.62 KiB
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <sys/socket.h>
    #include <arpa/inet.h>
    #include <string.h>
    
    int sock;
    
    #define PIR_PIN 17 // PIR 센서가 연결된 GPIO 핀 번호
    
    // GPIO 핀 초기화 함수
    void init_gpio() {
        int fd;
    
        // GPIO 핀을 export
        fd = open("/sys/class/gpio/export", O_WRONLY); // /sys/class/gpio/export 파일을 쓰기 전용으로 연다.
        if (fd == -1) { 
            perror("Error exporting GPIO");
            exit(1);
        }
        //파일 디스크립터(fd)가 정상적으로 열렸다면,
        write(fd, "17", 2);  //write(fd, "17", 2);는 17 문자열을 파일에 쓰되, 문자열의 길이가 2이므로 2바이트만큼 쓰라는 의미
        close(fd);
    
        // 방향 설정 (in으로 설정)
        fd = open("/sys/class/gpio/gpio17/direction", O_WRONLY); ///sys/class/gpio/gpio17/direction 파일을 쓰기 전용으로 연다. 이 파일 GPIO핀의 방향을 설정하는 사용된다.
        if (fd == -1) {
            perror("Error setting direction GPIO");
            exit(1);
        }
        write(fd, "in", 2);
        //in"으로 설정하기 위해 "in" 문자열을 파일에 쓰기 위해 write 함수를 사용
        // write(fd, "in", 2);는 "in" 문자열을 파일에 쓰되, 문자열의 길이가 2이므로 2바이트만큼 쓰라는 의미
        close(fd);
    }
    
    // GPIO 핀 읽기 함수
    int read_gpio() {
        int fd;
        char buffer[2];
    
        // 값 읽기
        fd = open("/sys/class/gpio/gpio17/value", O_RDONLY); ///sys/class/gpio/gpio17/value 경로에 위치한 파일을 읽기 전용(O_RDONLY)으로 연다.
        //GPIO핀 현재상태를 나타내며 값이 1또는0이다.
        if (fd == -1) {
            perror("Error reading GPIO value"); 
            exit(1);
        }
        read(fd, buffer, sizeof(buffer)); //read(fd, buffer, sizeof(buffer));를 사용하여 파일에서 데이터를 읽어와서 buffer에 저장
        close(fd);
    
        return atoi(buffer);//atoi(buffer)를 통해 GPIO 현재값(1또는0)을 저장
    }
    
    int main(int argc, char *argv[]) {
        printf("PIR Sensor Test\n");
        
    
        // GPIO 핀 초기화
        init_gpio();
        struct sockaddr_in server_addr;
    
        if (argc != 3)
        {
            printf("Please deliver IP & Port num as arguments correctly!\n");
            exit(1);
        }