Question

Hello I need advice of how correctly to change the baud rate of the UART port in the middle of the program.

To establish communication with my desired slave I need to send the so called "break field" which consists of 13-26 (MIN 11) LOW BITS, on UART as I think it's not achievable as before and after every 8 bits UART adds start & stop bit. I had an idea of achieving it by manipulating the baud-rates send break field at 9600Bauds followed by the 19200Baud speed. But I'm unable to see difference between baudrates on the oscilloscope. So I suppose I do it in the wrong way.

#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);
} 

I have tried it also by setting baudrates in different way as well:

cfsetispeed(&midtio, B9600)
cfset0speed(&midtio, B9600)

cfsetispeed(&newtio, B19200)
cfset0speed(&newtio, B19200)
Était-ce utile?

La solution

I need to send the so called "break field"

If the goal is to send a "break", then you've asked an XY question with "How to change the baudrate in c/c++". You cannot generate a break condition by manipulating the baud rate. You would need a baud rate of less than 32 baud to achieve a quarter-second break.

A break condition can be sent on the serial link by using the TCSBRK command in an ioctl().

BTW your serial port initialization code does not conform to best programming practices. You should always be testing the return codes from system calls. The elements of the termios structure should not be directly assigned, but rather just the individual bits should be modified. Refer to a guide such as this.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top