/*
本例程实现了烟雾传感器的使用，VCC接3.3V，GND接地，DO接GPIO3_1（编号449）输出模式，有源蜂鸣器正极接3.3V，DO脚接GPIO1_12（编号492），负极接地。
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include<sys/time.h>

#define GPIO_EXPORT "/sys/class/gpio/export"
#define GPIO_UNEXPORT "/sys/class/gpio/unexport"
#define smoke 449
#define buzzer 492
//导出GPIO函数
void exportPin(int pin) {
    char pinStr[4];
    sprintf(pinStr, "%d", pin);

    int fd = open(GPIO_EXPORT, O_WRONLY);
    if (fd == -1) {
        printf("Failed to open GPIO export file.\n");
        exit(1);
    }

    write(fd, pinStr, strlen(pinStr));
    close(fd);
}
//释放GPIO函数
void unexportPin(int pin) {
    char pinStr[4];
    sprintf(pinStr, "%d", pin);

    int fd = open(GPIO_UNEXPORT, O_WRONLY);
    if (fd == -1) {
        printf("Failed to open GPIO unexport file.\n");
        exit(1);
    }

    write(fd, pinStr, strlen(pinStr));
    close(fd);
}
//设置GPIO方向函数
void setPinDirection(int pin, const char *direction) {
    char pinDir[100];
    sprintf(pinDir, "/sys/class/gpio/gpio%d/direction", pin);

    int fd = open(pinDir, O_WRONLY);
    if (fd == -1) {
        printf("Failed to open pin %d\n", pin);
        exit(1);
    }

    write(fd, direction, strlen(direction));
    close(fd);
}
//设置GPIO输出值函数
void setPinValue(int pin, int value) {
    char pinValue[100];
    sprintf(pinValue, "/sys/class/gpio/gpio%d/value", pin);

    int fd = open(pinValue, O_WRONLY);
    if (fd == -1) {
        printf("Failed to open pin %d\n", pin);
        exit(1);
    }

    char strValue[2];
    sprintf(strValue, "%d", value);
    write(fd, strValue, strlen(strValue));
    close(fd);
}
//读取GPIO输入值函数
int readPinValue(int pin) {
    char pinValue[100];
    sprintf(pinValue, "/sys/class/gpio/gpio%d/value", pin);

    int fd = open(pinValue, O_RDONLY);
    if (fd == -1) {
        printf("Failed to open pin %d\n", pin);
        exit(1);
    }

    char value;
    read(fd, &value, sizeof(value));
    close(fd);

    return (value == '1') ? 1 : 0;
}
int main() {
    int pinValue;
 
    exportPin(smoke);   // 导出GPIO引脚        
    setPinDirection(smoke, "in");// 设置GPIO引脚方向为输出 
    exportPin(buzzer);   // 导出GPIO引脚        
    setPinDirection(buzzer, "out");// 设置GPIO引脚方向为输出 
    setPinValue(buzzer,1);//初始化引脚
    setPinValue(smoke,1);
    printf("初始化成功\n");

    while (1) {
        pinValue = readPinValue(smoke);
        if (pinValue != 1)
        {
        usleep(500000);//延时防止误触发
        pinValue = readPinValue(smoke);
        if (pinValue != 1)
        {
        setPinValue(buzzer,0);
        sleep(1);
        setPinValue(buzzer,1);
        sleep(1);
        }
        }
       }


    unexportPin(smoke);
    unexportPin(buzzer);

    return 0;
}


