我正在使用嵌入式Linux中的串口,因为你知道我可以在互联网上找到很多来源。但是我对函数tcsetattr有一点问题,我试图设置ubit端口使用stopbit disable和enable(如果CSTOPB位置1,则使用两个停止位。否则,只使用一个停止位),但是我无法在tcsetattr中保存选项结构。
以下代码是示例:
#include <stdio.h>
#include <glib.h>
#include <termios.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/timeb.h>
static int uart_fd = 0;
void set_uart_fd(int fd) {
uart_fd = fd;
}
int get_uart_fd() {
return uart_fd;
}
void close_uart() {
printf("Uart was closed \n");
close(get_uart_fd());
}
void open_uart(){
int flags = O_RDONLY;
int fd;
flags = O_RDWR | O_NOCTTY | O_NDELAY;
fd = open("/dev/ttyUSB2", flags);
if (fd < 0) {
printf("Unable to open device \n");
}
set_uart_fd(fd);
}
void configuration_uart(speed_t baudrate,int data_bit, int stop_bit, int parity, int hardware_flow) {
int status = 0,rc = 0;
struct termios options;
int uart = get_uart_fd();
fcntl(uart, F_SETFL, 0);
if ((rc = tcgetattr(uart,&options)) < 0){
printf("failed to get attr\n");
}
printf("Bits get: %d \n",options.c_cflag);
sleep(1);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 0;
options.c_cflag |= CLOCAL | CREAD;
if (data_bit == 7) {
options.c_cflag &= ~CS8;
options.c_cflag |= CS7;
}
if (stop_bit == 1) {
printf("Stop Bit enable to two stop bits\n");
options.c_cflag |= CSTOPB;
}
if (parity == 1) {
options.c_cflag |= PARODD;
} else if (parity == 2){
options.c_cflag |= PARENB;
}
if (hardware_flow == 1) {
options.c_cflag |= CRTSCTS;
}
cfsetispeed(&options, baudrate);
cfsetospeed(&options, baudrate);
printf("Bits set: %d \n",options.c_cflag);
if ((rc = tcsetattr(uart, TCSANOW, &options)) < 0) {
printf("UART error in tcsetattr \n");
}
if ((rc = tcgetattr(uart,&options)) < 0){
printf("failed to get attr\n");
}
printf("Bits end: %d \n",options.c_cflag);
}
int main(int argc,char** argv)
{
speed_t baudrate =B115200;
int data_bit=8;
int parity=0;
int stop_bit=0;
int hardware_flow=0;
open_uart();
printf("Start Serial Port Configuration \n");
configuration_uart(baudrate,data_bit,stop_bit,parity,hardware_flow);
printf("New Configuration \n");
stop_bit=1;
configuration_uart(baudrate,data_bit,stop_bit,parity,hardware_flow);
close_uart();
}
我可以在停止位设置为0的情况下运行代码,代码运行没有问题。但是当我将停止位更改为1时,tcsetattr不会设置options.c_cflag变量中的值。此变量显示相同的值。
以下输出来自代码:
Start Serial Port Configuration
Bits get: 3261
Bits set: 7346
Bits end: 7346
New Configuration
Bits get: 7346
Stop Bit enable to two stop bits
Bits set: 7410
Bits end: 7346
Uart was closed
感谢您的帮助