/*
 *
 * MH-Z14B CO2 Sensor
 * Based on Raspberry Pi wiringPi library
 * Time: 20240109
 *
 */

#include <stdio.h>
#include <wiringPi.h>
#include <wiringSerial.h>
#include <unistd.h>

// 校准
static void calibration(int fd)
{
    // 校准传感器零点（ZERO）
    char zero[9] = { 0XFF, 0X01, 0X87, 0X00, 0X00, 0X00, 0X00, 0X00, 0X78 };

    write(fd, zero, 9);
    delay(200);

    return;
}

int main()
{
    int fd = 0;
    char checksum = 0;
    int High = 0;
    int Low = 0;
    int ppm = 0;
    char read_command[9] = { 0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79 };
    char data[9] = { 0 };

    if ((fd = serialOpen("/dev/serial0", 9600)) < 0) {
        printf("Unable to open device\n");
        return 1;
    } else {
        printf("ttyAMA0 initialised ok\n");
    }

    while (1) {
        // 写入读取命令
        write(fd, read_command, 9);
        delay(100);

        // 读取
        read(fd, data, 9);

        checksum = (0xFF - (data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7])) + 1;
        High = (int)data[2];
        Low = (int)data[3];
        ppm = (256 * High) + Low;

        if (data[8] == checksum) {
            for (int loop = 0; loop <= 8; loop++) {
                printf("data%d: %X\n", loop, data[loop]);
            }
            printf("checksum: %X = %X\n", data[8], checksum);
            printf("CO2 Concentration: %d ppm\n\r\n", ppm);
        } else {
            calibration(fd);
            continue;
        }

        delay(3000);
    }

    return 0;
}
