您好我需要建议如何正确地改变程序中间UART端口的波特率。
为了与我想要的从机建立通信,我需要在UART上发送所谓的“中断字段”,它由13-26(MIN 11)个低位组成,因为我认为它不可能像之前和之后每8位UART一样实现添加开始&停止位。我想通过操纵9600Bauds的波特率发送中断字段然后是19200Baud速度来实现它。 但我无法在示波器上看到波特率之间的差异。所以我想我是以错误的方式做到的。
#include <iostream>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <time.h>
#include <stdlib.h>
#define BAUDRATE9600 B9600
#define BAUDRATE19200 B19200
#define PORT "/dev/ttyO4"
#define _POSIX_SOURCE 1
main()
{
int fd, c;
struct termios oldtio, newtio, midtio;
fd = open(PORT, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd <0) { perror(PORT); exit(-1); }
tcgetattr(fd, &oldtio); /* save current port settings */
/* set new port settings for canonical input processing */
midtio.c_cflag = BAUDRATE9600 | CS8 | CLOCAL | CSTOPB ;
midtio.c_iflag = IGNPAR | ICRNL;
midtio.c_oflag = 0;
midtio.c_lflag = ICANON;
newtio.c_cflag = BAUDRATE19200 | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR | ICRNL;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;
tcsetattr(fd, TCSANOW, &midtio);
char break[] = {0x00}; // break field (0000 0000)
c = write (fd, break, sizeof(break));
tcsetattr(fd, TCSANOW, &newtio);
char sync [] = {0x55};
char PID [] = {0xE2};
char data [] = {0xAA};
char data1 [] = {0xA5};
char check [] = {0xAF};
c = write (fd, sync, sizeof(sync));
c = write (fd, PID, sizeof(PID));
c = write (fd, data, sizeof(data));
c = write (fd, data1, sizeof(data1));
c = write (fd, check, sizeof(check));
/* restore old port settings */
tcsetattr(fd,TCSANOW,&oldtio);
}
我也尝试过以不同的方式设置波特率:
cfsetispeed(&midtio, B9600)
cfset0speed(&midtio, B9600)
cfsetispeed(&newtio, B19200)
cfset0speed(&newtio, B19200)