How to check serial port in linux work properly - c++

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?

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

Why when I try set serial port, function return "Input/output error"?

I try set in c++ some serial port, but when I try function tcsetatrr, its return error -1. Port opens without problems.
char port_name[] = "/dev/ttyS1";
int port = open(port_name, O_RDWR | O_NOCTTY | O_NDELAY);
if(port < 0){
std::cout << "Cant open port" << std::endl;
return;
}
struct termios settings;
tcgetattr(port, &settings);
cfgetispeed(&settings);
//std::cout << settings.c_cflag;
//Baudrate
cfsetispeed(&settings, B115200);
cfsetospeed(&settings, B115200);
//Data bits
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8;
//Parity
settings.c_cflag |= ~PARENB;
//Stop bit
settings.c_cflag &= ~CSTOPB;
//Flow control
settings.c_cflag |= ~CRTSCTS;
settings.c_iflag &= ~(IXON | IXOFF | IXANY);
int er = tcsetattr(port, TCSANOW, &settings);
if (er<0) {
fprintf(stderr, "Error openinig: %s\n", strerror(errno));
}
close(port);
output:
Input/output error
How can I fix that? I was running code as root. The problem is not in the configuration of the settings structure because after commenting it out, I get the same error
The most likely answer is that you don't really have a serial device /dev/ttyS1. Try /dev/ttyS0 instead. I have the same deal on my PC.
I see a few additional problems here.
You don't check if tcgetattr() succeeds, so don't be so sure you even get to tcsetattr().
Calling settings.c_cflag |= ~PARENB; or settings.c_cflag |= ~CRTSCTS; is most likely not what you want to do (will raise all flags except the selected one).

struct termios setting for serial communication with arduino

on a unix based software, which must send a number between 0 and 179 to arduino and arduino will apply that number as an angle to a servo motor, but i do not know what parameters i have to change in the terminos struct to permit the serial communication.
this is the c++ code:
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <termios.h>
using namespace std;
int main()
{
unsigned int angle;
ofstream arduino;
struct termios ttable;
//cout<<"test-1";
arduino.open("/dev/tty.usbmodem3a21");
//cout<<"test-2";
if(!arduino)
{
cout<<"\n\nERR: could not open port\n\n";
}
else
{
if(tcgetattr(arduino,&ttable)<0)
{
cout<<"\n\nERR: could not get terminal options\n\n";
}
else
{
//there goes the terminal options setting for the output;
ttable.c_cflag = -hupcl //to prevent the reset of arduino
cfsetospeed(&ttable,9600);
if(tcsetattr(arduino,TCSANOW,&ttable)<0)
{
cout<<"\n\nERR: could not set new terminal options\n\n";
}
else
{
do
{
cout<<"\n\ninsert a number between 0 and 179";
cin>>angle;
arduino<<angle;
}while(angle<=179);
arduino.close();
}
}
}
}
and this is arduino’s :
#include <Servo.h>
Servo servo;
const int pinServo = 2;
unsigned int angle;
void setup()
{
Serial.begin(9600);
servo.attach(pinServo);
servo.write(0);
}
void loop()
{
if(Serial.available()>0)
{
angle = Serial.read();
if(angle <= 179)
{
servo.write(angle);
}
}
}
So would you kindly tell me what do i have to change of "ttable" ?
In general, talking to an Arduino from C/C++ is easiest with the serial port in 'raw' mode. This is basically 8N1, byte-at-a-time, with the TTY doing the minimal amount of futzing about with the data. An easy way to set the various flags in a termios struct for this mode is to use cfmakeraw(3). Per the man pages this does the following:
struct termios config;
config.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP |
INLCR | IGNCR | ICRNL | IXON);
config.c_oflag &= ~OPOST;
config.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
config.c_cflag &= ~(CSIZE | PARENB);
config.c_cflag |= CS8;
For good measure, explicitly set receive enable and ignore modem control with config.c_cflag |= (CLOCAL | CREAD);. If the termios structure you are using is a copy of the existing one (obtained with tcgetattr(), for example), then also disable flow control altogether with config.c_iflag &= ~(IXOFF | IXANY);. So all-in-all, it will look like:
struct termios config;
cfmakeraw(&config);
config.c_cflag |= (CLOCAL | CREAD);
config.c_iflag &= ~(IXOFF | IXANY);
// set vtime, vmin, baud rate...
config.c_cc[VMIN] = 0; // you likely don't want to change this
config.c_cc[VTIME] = 0; // or this
cfsetispeed(&config, B9600);
cfsetospeed(&config, B9600);
// write port configuration to driver
tcsetattr(fd, TCSANOW, &config;
Using C++ file streams is a bit tricky as well. You very likely want non-blocking read/write and no controlling TTY, so it is usually easier to use open(2) with the O_NOCTTY and O_NDELAY flags set.
some thing like that for termios is best option
options.c_cflag &= ~CRTSCTS;
options.c_cflag |= (CLOCAL | CREAD);
options.c_iflag |= (IGNPAR | IGNCR);
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_oflag &= ~OPOST;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_iflag &= ~INPCK;
options.c_iflag &= ~(ICRNL|IGNCR);
options.c_cflag &= ~CSTOPB;
options.c_iflag |= INPCK;
options.c_cc[VTIME] = 0.001; // 1s=10 0.1s=1 *
options.c_cc[VMIN] = 0;

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).