From 7b1e6c7d849aec2e1b45c3a6c851d6a0d68360ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ferit=20Yi=C4=9Fit=20BALABAN?= Date: Mon, 7 Aug 2023 17:11:01 +0300 Subject: [PATCH] Initial version --- main.c | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 main.c diff --git a/main.c b/main.c new file mode 100644 index 0000000..cffbb42 --- /dev/null +++ b/main.c @@ -0,0 +1,79 @@ +/* + * Ferit Yiğit BALABAN, fybalaban@fybx.dev + * rpi-fan-control 2023 + */ + +#include +#include +#include +#include +#include + +#define TEMP_PATH "/sys/class/thermal/thermal_zone0/temp" +#define FAN_PIN 17 + +#define HIGH 1 +#define LOW 0 + +int main(int argc, char** argv) { + int fd; + char buffer[6]; + int fanRunning; + double temperature; + int threshold; + int variance; + + if (argc != 3) { + printf("Expected threshold temperature and variance\n"); + return -1; + } + + threshold = atoi(*(argv + 1)); + variance = atoi(*(argv + 2)); + + if (!threshold) { + printf("Expected integer for threshold temperature: %s\n", *(argv + 1)); + return -2; + } else if (!variance) { + printf("Expected integer for variance: %s\n", *(argv + 2)); + return -3; + } + + if (gpioInitialise() < 0) { + printf("Failed to initialize GPIO.\n"); + return 1; + } + + gpioSetMode(FAN_PIN, PI_INPUT); + fanRunning = gpioRead(FAN_PIN); + gpioSetMode(FAN_PIN, PI_OUTPUT); + + fd = open(TEMP_PATH, O_RDONLY); + if (fd < 0) { + printf("Error opening temperature file\n"); + return 2; + } + + if (read(fd, buffer, sizeof(buffer)) < 0) { + printf("Error reading temperature\n"); + close(fd); + return 3; + } + + close(fd); + temperature = atof(buffer) / 1000.0; + printf("CPU Temperature: %.2f°C\n", temperature); + + if (!fanRunning && temperature >= threshold + variance) { + gpioWrite(FAN_PIN, HIGH); + printf("Setting pin GPIO17 to HIGH\n"); + } else if (temperature <= threshold - variance) { + gpioWrite(FAN_PIN, LOW); + printf("Setting pin GPIO17 to LOW\n"); + } else { + printf("Pin GPIO17 is already HIGH\n"); + } + + gpioTerminate(); + return 0; +}