Serial communication between linux and windows - c++

I am sending data bytes from linux to windows in serial RS232 then everything is ok, only i have to handle 0xa send from linux, because windows read it as 0xd + 0xa.
but when i am sending data bytes from windows to linux some bytes are replaced as -
windows send - 0xd linux receive 0xa
windows send - 0x11 linux receive garbage tyte value in integer something 8200
plese explain what goes wrong when I send data from windows to Linux.
thanks in advance
Windows serial port initialize
char *pcCommPort = "COM1";
hCom = CreateFile( TEXT("COM1"),
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
fSuccess = GetCommState(hCom, &dcb);
FillMemory(&dcb, sizeof(dcb),0);
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = CBR_115200; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
dcb.fOutxCtsFlow = false;
fSuccess = SetCommState(hCom, &dcb);
buff_success = SetupComm(hCom, 1024, 1024);
COMMTIMEOUTS cmt;
// ReadIntervalTimeout in ms
cmt.ReadIntervalTimeout = 1000;
cmt.ReadTotalTimeoutMultiplier = 1000;
cmt.ReadTotalTimeoutConstant=1000;
timeout_flag = SetCommTimeouts(hCom, &cmt);
windows write serial-
WriteFile(hCom, buffer, len, &write, NULL);
Linux serial initialize-
_fd_port_no = open("//dev//ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
tcgetattr(_fd_port_no, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CS8);
options.c_cflag|=(CLOCAL|CREAD);
options.c_cflag &=~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag |= (IXON | IXOFF | IXANY);
options.c_cflag &= ~ CRTSCTS;
tcsetattr(_fd_port_no, TCSANOW, &options);
read serial linux-
while(read(_fd_port_no,buffer+_buffer_len,sizeof(buffer))>0)
{
_buffer_len = _buffer_len+sizeof(buffer);
}
Yes, as i told from Linux to windows only NL/CR problem detected but i solved it by byte replacing,
but do you have any idea about serila data send from windows to Linux (byte replacement policy).
Actually I have to send 200 KB file in 200 bytes blocks over serial so which byte could be replaced if send from Windows to Linux

If you are using the ReadFile and WrietFile on Windows and read and write in Linux, it shouldn't really matter what the line-endings are, other than "you have to translate it at some point after receiving it.
This doesn't look right:
while(read(_fd_port_no,buffer+_buffer_len,sizeof(buffer))>0)
{
_buffer_len = _buffer_len+sizeof(buffer);
}
You should take into account the size of the read returned by read.
And if sizeof(buffer) is the actual buffer you are reading into, adding +_buffer_len, when _buffer_len >= sizeof(buffer) will write outside the buffer.
Also slightly worried about this:
options.c_iflag |= (IXON | IXOFF | IXANY);
options.c_cflag &= ~ CRTSCTS;
Are you SURE you want a XOFF/CTRL-S (0x13) to stop flow? Usually that means that data with CTRL-S in it won't be allowed - which may not be an issue when sending text data, but if you ever need to send binary data it certainly will be. IXOFF also means that the other end will have to respond to XOFF and XON (CTRL-Q, 0x11) to stop/start the flow of data. Typically, we don't want this in modern systems....
Using RTS/CTS should be safe if you have the wiring correct between the two ends.

I think you have to flush before reading the flux from a serial port
tcflush(_fd_port_no TCIFLUSH);
furthemore Have you tried to see the flux with a console using the commande
cat < dev/ttyS0 ?

To avoid line ending conversions you might need to add:
options.c_iflag &= ~IGNCR; // turn off ignore \r
options.c_iflag &= ~INLCR; // turn off translate \n to \r
options.c_iflag &= ~ICRNL; // turn off translate \r to \n
options.c_oflag &= ~ONLCR; // turn off map \n to \r\n
options.c_oflag &= ~OCRNL; // turn off map \r to \n
options.c_oflag &= ~OPOST; // turn off implementation defined output processing
Also, the following line:
options.c_iflag |= (IXON | IXOFF | IXANY);
Will enable XON/XOFF processing, so the tty driver will process Ctrl-S (XOFF) and Ctrl-Q (XON) characters as flow control (which is probably why you see somethign unexpected when sending 0x11, which is Ctrl-Q). I'd expect that you'd want to turn those bits off:
options.c_iflag &= ~(IXON | IXOFF | IXANY);
In fact, I think you might want to call cfmakeraw() after calling tcgetattr() which should disable all special handling of input and output characters.

Thanks all
This Change Solved my problem
fd_port_no = open("//dev//ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
tcgetattr(_fd_port_no, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CS8);
options.c_cflag|=(CLOCAL|CREAD);
options.c_cflag &=~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~ CRTSCTS;
options.c_iflag |= (IXON | IXOFF | IXANY);
options.c_lflag &= ~(ICANON | ISIG | ECHO | ECHONL | ECHOE | ECHOK);
options.c_cflag &= ~ OPOST;
tcsetattr(_fd_port_no, TCSANOW, &options);

Related

c++ application quits without error on serial data receive

I am trying to set up serial port communication in a c++ application on Ubuntu 20. I am opening the serial port like this:
serialPort = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (serialPort == -1)
{
perror("FAILED ");
exit(1);
}
fcntl(serialPort, F_SETOWN, getpid());
fcntl(serialPort, F_SETFL, (FNDELAY | FASYNC));
struct termios options;
tcgetattr(serialPort, &options);
cfsetispeed(&options, (speed_t) B115200);
cfsetospeed(&options, (speed_t) B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~(IXON | IXOFF | IXANY | INPCK | ISTRIP | IGNBRK | BRKINT | PARMRK | IGNCR | ICRNL);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 0;
tcsetattr(serialPort, TCSANOW, &options);
I know the port is open and functional, because when I try to write to it, my other device does receive the data. But every time the other device writes data back, the application quits without an error message. Even when I am in debug mode, the debugger just drops and the application quits. This happens regardless of who sends data first, but it does happen consistently every time data is received. Because of this I can also not check the data using the application, since it exits before I would get the chance. Does anybody know what is going on?
For those interested, here is the code I use to write to the serial port:
void MotorBenchmarker::sendMessage(char* message, int size)
{
write(serialPort, message, size);
}
Edit 1:
I am using GDB debugger and I now see that the application is terminated with the following message:
Program terminated with signal SIGIO, I/O possible.
below which it says:
The program no longer exists.
SIGIO - I did not notice earlier, you did specify FASYNC flag, this means that any incoming data is reported through this signal. Since you are not handling it, the program crashes.
Either remove the flag and use read - blocking or non-blocking, or install the handler.

Why cannot I read data from a serial port?

I have faced the following problem: I wish to read data comming to my serial port on linux. Data are send from an external device with standard serial settings. I'm sure that the external device sends them, that has been already checked.
However, on linux all i can read is an empty byte. What am I setting wrong?
My settings looks like that:
serial = open(_name, O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(serial, F_SETFL,0);
tcgetattr(_serial, &_options);
options.c_ispeed = _baudRate;
options.c_ospeed = _baudRate;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_iflag &= ~(INPCK|PARMRK|ISTRIP);
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CREAD |CLOCAL ;
tcflush(serial, TCIFLUSH);
tcsetattr(serial, TCSANOW, &options);
my read function looks like that:
char byte = 'a';
int datasize = 0;
while (byte != '\n') {
datasize = read(serial, &byte, sizeof(byte));
std::cout<< "Read:"<< byte <<".\t"; // this line always prints: "Read: ."
}
I'm not sure what has happened but the following settings finally worked. I will share it with you as I got a lot of help here on Stackoverflow:
serial = open(name.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(serial, F_SETFL,0);
tcgetattr(serial, &options);
options.c_ispeed = _baudRate;
options.c_ospeed = _baudRate;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_iflag &= ~(INPCK|PARMRK|ISTRIP);
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CREAD |CLOCAL ;
options.c_cc[VMIN]=0;
options.c_cc[VTIME]=10;
options.c_cflag &= ~CRTSCTS; // turn off hardware flow control
options.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off sowftware flow control
options.c_lflag &= ~ICANON;
options.c_lflag &= ~ISIG;
options.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes
options.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
options.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
tcflush(serial, TCIFLUSH);
tcsetattr(serial, TCSANOW, &options);

Not stable serial port reading from raspberry pi

I am trying to read serial data from an arduino serial port with my raspberry pi with a 33 bytes package in 800 Hz. I tried to time the duration, it turned to be very unstable.
The code I use to receive data is as follow, basically it just calculate how low does the "read" take. It will be called in 800 Hz.
std::chrono::system_clock::time_point startGet= std::chrono::system_clock::now();
int readBytes = read(serialPort, this->serialBuf+alreadyRead, this->dataNeedRead);
std::chrono::system_clock::time_point endGet= std::chrono::system_clock::now();
microsecs_t get_time(std::chrono::duration_cast<microsecs_t>(endGet-startGet));
cout<<"spend "<<get_time.count()<<endl;
Since the above script will be called in 800 Hz, ideally, I should see the port received 33 bytes in a short period of time.Yet it turned out the output is:
read: 33
spend 3817
read: 33
spend 5
read: 33
spend 1301
read: 33
spend 40
read: 33
spend 1333
read: 33
spend 31
I can see the port does read 33 bytes, but the processing time is too long( 800Hz need to be ran within 1250 us, but some of them is more than 3000 us.
And the way I setup the serialport is as follow
int Sensor::serialPortConnect(char *portName)
{
// Open the serial port. Change device path as needed (currently set to an standard FTDI USB-UART cable type device)
int serial_port = open(portName, O_RDWR);
// Create new termios struc, we call it 'tty' for convention
struct termios tty;
memset(&tty, 0, sizeof tty);
// Read in existing settings, and handle any error
if (tcgetattr(serial_port, &tty) != 0)
{
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
}
tty.c_cflag &= ~PARENB; // set parity bit, disabling parity (most common)
tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common)
tty.c_cflag |= CS8; // 8 bits per byte (most common)
tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common)
tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1)
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO; // Disable echo
tty.c_lflag &= ~ECHOE; // Disable erasure
tty.c_lflag &= ~ECHONL; // Disable new-line echo
tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); // Disable any special handling of received bytes
tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
// tty.c_oflag &= ~OXTABS; // Prevent conversion of tabs to spaces (NOT PRESENT ON LINUX)
// tty.c_oflag &= ~ONOEOT; // Prevent removal of C-d chars (0x004) in output (NOT PRESENT ON LINUX)
tty.c_cc[VTIME] = 0;
tty.c_cc[VMIN] =33;
// Set in/out baud rate to be 1000000
cfsetispeed(&tty, B1000000);
cfsetospeed(&tty, B1000000);
// Save tty settings, also checking for error
if (tcsetattr(serial_port, TCSANOW, &tty) != 0)
{
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
}
//Allocate buffer for read buffer
//tcflush(serial_port, TCIFLUSH);
return serial_port;
}
I am not sure why this happen. The RPi is installed with RT-PREEMPT kernel and the application I am running has the highest priority (RT). I thought it shouldn't be this unstable.

How to check serial port in linux work properly

I am going to use serial port in my C++ program linux ubuntu 10.4 ,this is my open port function :
int Recorder::OpenPort()
{
int intFd ;
struct termios options;
intFd=open("/dev/ttyS0", O_RDWR | O_NOCTTY| O_NDELAY);
if (intFd==-1){
perror("open_port: Unable to open /dev/ttyS0 - ");
}
fcntl(intFd, F_SETFL, FNDELAY); /*configuration the port*/
tcgetattr(intFd, &options);
//set baud rates at 115200
cfsetispeed(&options, B115200 );
cfsetospeed(&options, B115200);
//mask the character size to 8 bit data & no parity.CHARACTER SIZE SETTING
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
//setting hardware flow control
options.c_cflag |= CRTSCTS;
//Enable the receiver and set local mode .should always be enabled (enable receiver and dont change owner of port)
options.c_cflag |= (CLOCAL | CREAD);
//flush output buffer
options.c_lflag |= FLUSHO;
//choosing raw data disable echoing
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
//not setting software flow control
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_oflag &= ~OPOST;
// //output changes :for mapping NL to CR-NL.
// options.c_oflag |= (OPOST | ONLCR );
//
// options.c_oflag |= (NL1 | CR1 | FFDLY);
tcsetattr(intFd, TCSANOW, &options);
return intFd;
}
and this is the sample where I check my serial number:
int serial=0;
ioctl(intFd, TIOCMGET, &serial);
//for ubuntu 7.04 and 10.04
if(serial==16390 || serial==16422 || serial==16454 || serial==16486){//no connection with serial port
i checked my program many times and serial is 16486 every times and it means I have no connection with serial port , I checked my serial cable and it was ok? so how can I Solve my problem?

Serial communication: 0x0D is replaced by 0x0A during transmission

I'm reading some data from serial interface using Linux. From time to time there is a 0x0D within the data stream. On receiver side this value is replaced by 0x0A. This looks like a desired behaviour - unfortunately it is not desired in my case and I think it has to do with one of the options set during opening the port:
struct termios options;
struct serial_struct sStruct;
*fd= open(serialParams->port, O_RDWR|O_NOCTTY);// | O_NDELAY);
if (*fd == -1) return OAPC_ERROR_DEVICE;
fcntl(*fd, F_SETFL,FNDELAY);
tcgetattr(*fd, &options);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~CSIZE; // Mask the character size bits
options.c_cflag |= CS8;
options.c_cflag &= ~(PARENB|PARODD);
options.c_iflag &= ~(INPCK | ISTRIP);
options.c_iflag |=IGNPAR;
options.c_cflag&=~CSTOPB;
options.c_iflag |= (IXON | IXOFF | IXANY);
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE |ECHOK|ISIG|IEXTEN|ECHONL);
options.c_iflag&=~(IGNCR|IUTF8);
options.c_oflag&=~(ONLCR|OCRNL);
ioctl(*fd, TIOCGSERIAL, &sStruct);
sStruct.flags &= ~ASYNC_SPD_MASK;
ioctl(*fd, TIOCSSERIAL, &sStruct);
int speed;
speed=1000000;
ioctl(*fd, TIOCGSERIAL, &sStruct);
sStruct.flags = (sStruct.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
sStruct.custom_divisor = (sStruct.baud_base + (speed / 2)) / speed;
ioctl(*fd, TIOCSSERIAL, &sStruct);
cfsetispeed(&options, B38400);
cfsetospeed(&options, B38400);
if (tcsetattr(*fd, TCSANOW, &options)!=0) return OAPC_ERROR_DEVICE;
Any idea which of these options causes this data conversion during reception?
You reset the ONLCR/OCRNL flags to disable output processing, but you seem to miss resetting the reverse flags for input (INLCR/ICRNL).