1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <termios.h>
#define SERIAL_PORT "/dev/serial0"
void setup_serial(int fd) { struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; tcsetattr(fd, TCSANOW, &options); }
int main() { int fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY); if (fd == -1) { perror("Unable to open serial port"); return -1; } setup_serial(fd); const char *msg = "Hello UART!"; write(fd, msg, strlen(msg)); char buffer[256]; int n = read(fd, buffer, sizeof(buffer)); buffer[n] = '\0'; printf("Received: %s\n", buffer); close(fd); return 0; }
|