#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

int main() {
    // 1. Open the serial port
    int fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        perror("Error opening serial port");
        return 1;
    }

    struct termios tty;

    // 2. Get current terminal attributes
    if (tcgetattr(fd, &tty) != 0) {
        perror("Error from tcgetattr");
        close(fd);
        return 1;
    }

    // 3. Apply raw mode configuration
    cfmakeraw(&tty);

    // 4. Set additional custom settings (Example: 115200 Baud rate)
    cfsetispeed(&tty, B115200);
    cfsetospeed(&tty, B115200);

    // VMIN and VTIME define reading behavior
    tty.c_cc[VMIN]  = 1;  // Block until at least 1 byte is read
    tty.c_cc[VTIME] = 0;  // No inter-character timer

    // 5. Apply the modified attributes immediately
    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        perror("Error from tcsetattr");
        close(fd);
        return 1;
    }

    printf("Serial port configured in raw mode.\n");
    
    // ... perform your read/write operations here ...

    close(fd);
    return 0;
}