// This document implements some function to interact with an // Raspberry Pi 4 and some external components. // Used components: DS18B20, and LED and a push button. // libgpiod is used for the communication with the GPIOs #include #include #include // For sleep() #include #define GPIO_CHIP "gpiochip0" #define LED_GPIO_PIN 18 #define BUTTON_GPIO_PIN 22 #define LED_BLINK_TIME 1 // Blink delay in seconds #define SENSOR_PATH "/sys/bus/w1/devices/28-000000306565/temperature" // DS18B20 sensor address // function to set the LED state by passing the pin and state void set_led(int pin, int state) { struct gpiod_chip *chip; struct gpiod_line *line; chip = gpiod_chip_open_by_name(GPIO_CHIP); if (!chip) { perror("Failed to open GPIO chip"); return; } line = gpiod_chip_get_line(chip, pin); if (!line) { perror("Failed to get GPIO line"); gpiod_chip_close(chip); return; } if (gpiod_line_request_output(line, "gpio-led", 0) < 0) { perror("Failed to request line as output"); gpiod_chip_close(chip); return; } // Set the LED state gpiod_line_set_value(line, state); // Release the GPIO line and chip gpiod_line_release(line); gpiod_chip_close(chip); } // function to blink the LED by passing the pin, number of blinks and the delay void blink_led(int pin, int time, int delay) { for (int i = 0; i < time; i++) { set_led(pin, 1); sleep(delay); set_led(pin, 0); sleep(delay); } } float read_temperature() { int fd; float temperature; char buf[16]; // Large enough to hold the temperature string fd = open(SENSOR_PATH, O_RDONLY); if (fd == -1) { perror("Failed to open temperature file"); return -1; // Return an error indicator } ssize_t numRead = read(fd, buf, sizeof(buf) - 1); if (numRead == -1) { perror("Failed to read temperature file"); close(fd); return -1; // Return an error indicator } buf[numRead] = '\0'; // Null-terminate the string temperature = atof(buf) / 1000; // Convert the string to an integer close(fd); return temperature; } // funciton to read button status int read_button(int pin) { struct gpiod_chip *chip; struct gpiod_line *line; int value; chip = gpiod_chip_open_by_name(GPIO_CHIP); if (!chip) { perror("Failed to open GPIO chip"); return -1; } line = gpiod_chip_get_line(chip, pin); if (!line) { perror("Failed to get GPIO line"); gpiod_chip_close(chip); return -1; } if (gpiod_line_request_input(line, "gpio-button") < 0) { perror("Failed to request line as input"); gpiod_chip_close(chip); return -1; } value = gpiod_line_get_value(line); // Release the GPIO line and chip gpiod_line_release(line); gpiod_chip_close(chip); return value; } int main(void) { // printf("Temperature: %.2f\n", read_temperature(SENSOR_ADDRESS)); // blink_led(LED_GPIO_PIN, 5, LED_BLINK_TIME); // printf("Temperature: %.2f\n", read_temperature()); // check button status and sleep for a second while(1){ printf("Button status: %d\n", read_button(BUTTON_GPIO_PIN)); sleep(1); } return 0; }