UART (Universal Asynchronous Receiver/Transmitter) represents one implementation approach for serial communication, making it a form of serial data transmission. This intreface enables two devices to exchange information via a serial connection using an asynchronous communication protocol.
Programming with UART typically involves opening the serial device, configuring communication parameters like baud rate, data bits, stop bits, and parity settings, followed by transmitting and receiving data. Below is a basic example demonstrating how to perform serial communication using UART in a Linux environment.
- Opening the Serial Device
First, you need to use the open function to access the serial device file. On Linux systems, these files are usually located under the /dev directory, such as /dev/ttyS0 or /dev/ttyUSB0.
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
int main() {
int device_fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (device_fd < 0) {
perror("open_port: Unable to open /dev/ttyS0\n");
return 1;
}
// ... additional configuration and communication code ...
close(device_fd);
return 0;
}
- Setting Serial Parameters
Subsequently, you should utilize tcgetattr and tcsetattr functions to retrieve and modify the serial port settings. These settings encompass baud rate, data bits, stop bits, and parity configuration.
struct termios config;
tcgetattr(device_fd, &config);
cfsetispeed(&config, B9600); // Input speed
cfsetospeed(&config, B9600); // Output speed
config.c_cflag |= (CLOCAL | CREAD);
config.c_cflag &= ~PARENB; // No parity
config.c_cflag &= ~CSTOPB; // One stop bit
config.c_cflag &= ~CSIZE; // Clear data size mask
config.c_cflag |= CS8; // Eight data bits
tcsetattr(device_fd, TCSANOW, &config);
- Transmitting and Receiving Data
Data transmission generally employs the write function, whereas data rceeption uses the read function.
char *message = "Hello, UART!";
int count = write(device_fd, message, strlen(message));
if (count < 0) {
perror("write() of 12 bytes failed!\n");
return 1;
}
char buffer[256];
count = read(device_fd, buffer, sizeof(buffer));
if (count < 0) {
perror("read failed!\n");
return 1;
}
printf("Read %d bytes: %s\n", count, buffer);
By combining all the above steps, you can create a complete UART serial communication program. However, this serves merely as a fundamental example; real-world applications often require more sophisticated handling such as error management, timeout controls, and non-blocking I/O operations.
When working with UART communication, ensure that your hardware connections are properly established and that the selected serial device matches your physical setup. Additionally, adjust the serial parameters according to your specific application requirements.