Okay, Maybe you can try the below code
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/serial.h>
#include <string.h>
int main(int argc, char *argv[]) {
// Open serial port ttyS1
const char *device = "/dev/ttyS1";
int fd = open(device, O_RDWR | O_NOCTTY);
if (fd < 0) {
perror("Error opening serial port");
return -1;
}
// Get the current serial port settings
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
perror("Error getting port attributes");
close(fd);
return -1;
}
// Configure the serial port settings
// Clear all settings first
tty.c_cflag = 0;
tty.c_iflag = 0;
// Enable receiver, ignore modem control lines
tty.c_cflag |= CREAD | CLOCAL;
// Enable hardware flow control (RTS/CTS)
tty.c_cflag |= CRTSCTS;
// Set baud rate to 19200
cfsetispeed(&tty, B19200);
cfsetospeed(&tty, B19200);
// Set 7 bits per byte
tty.c_cflag |= CS7;
// Enable even parity bit, without PARODD
tty.c_cflag |= PARENB;
// Set 2 stop bits
tty.c_cflag |= CSTOPB;
// Apply the new settings
if (tcsetattr(fd, TCSANOW, &tty) < 0) {
perror("Error setting port attributes");
close(fd);
return -1;
}
printf("Serial port configured successfully\n");
printf("Port configuration:\n");
printf("- Device: %s\n", device);
printf("- Baud rate: 19200\n");
printf("- Data bits: 7\n");
printf("- Parity: Even\n");
printf("- Stop bits: 2\n");
printf("- Flow control: RTS/CTS\n");
// Test string to send
const char *test_string = "Hello! This is UART1\n";
ssize_t bytes_written = write(fd, test_string, strlen(test_string));
if (bytes_written < 0) {
perror("Error writing to serial port");
} else {
printf("\nSent %zd bytes: %s", bytes_written, test_string);
}
// Keep the port open briefly to ensure transmission
sleep(1);
// Close the serial port
close(fd);
return 0;
}