3

I want to read data from my serial port on Linux with C/C++ code. As I can still read from this serial port with GtkTerm and even with cat /dev/ttyUSB0, this is not a hardware / driver problem.

It seems that the serial port is not initiated correctly as reading do works after the use a program like gtkterm.

Here is the code I use to init the serial port (seconde version) :

UbiDriver::UbiDriver(const std::string &ttyPort)
{
    // Doc : http://www.easysw.com/~mike/serial/serial.html#2_4

    m_serialHandle = open(ttyPort.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); // Open perif
    if(m_serialHandle < 0)
    {
        MY_THROW("Impossible d'ouvrir le port '" << ttyPort << "' !\nerrno = " << errno);
    }

    // Conf
    //if(fcntl(m_serialHandle, F_SETFL, 0) == -1) // lecture en mode bloquant
    if(fcntl(m_serialHandle, F_SETFL, O_NONBLOCK) == -1) // lecture en mode non bloquant
    {
        MY_THROW("fcntl failed !\nerrno = " << errno);
    }

    struct termios options;
    tcgetattr(m_serialHandle, &options); // Init struct avec la conf actuelle

    cfsetispeed(&options, B9600); // In speed
    cfsetospeed(&options, B9600); // Output speed

    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_cflag |= (CLOCAL | CREAD); // Enable the receiver and set local mode...
    options.c_cflag &= ~PARENB; // Desactive bit de parité
    options.c_cflag &= ~CSTOPB; // Désactive 2 stop bits -> Active 1 stop bits
    options.c_cflag &= ~CSIZE; // Désactive le bit "CSIZE"
    options.c_cflag |= CS8; // Communication sur 8 bits

    options.c_oflag &= ~OPOST; // Raw output is selected by resetting the OPOST option in the c_oflag member:

    // Application de la conf
    if(tcsetattr(m_serialHandle, TCSAFLUSH, &options) == -1) // Vidage buffer & application immédiate
    {
        MY_THROW("tcsetattr failed !\nerrno = " << errno);
    }
}

And to read data from the port

std::string UbiDriver::GetAnswer()
{
    const int buffSize = 1024;
    char buffer[buffSize] = {'\0'};
    int count = 0;
    std::string wholeAnswer = "";

    int noDataTime = 0;

    while(noDataTime < 2) // Tant qu'il y a des données à lire
    {
        count = read(m_serialHandle, buffer, buffSize - 1);
        if(count == -1)
        {
            MY_THROW("Impossible de lire sur le port serie. Verifiez la connexion avec l'imprimante !")
        }

        if(count > 0)
        {
            noDataTime = 0;

            buffer[count] = '\0';
            for(int i = 0; i < count; i++)
            {
                buffer[i] &= ~128; // Supression du premier 1 du binaire
            }

            wholeAnswer += std::string(buffer);
            std::cout << count << std::endl;
        }
        else
        {
            noDataTime++;
            usleep(100000);
        }
    }

    cerr << "----------- Answer -----------" << endl;
    cerr << "Size = " << wholeAnswer.size() << endl;
    cerr << wholeAnswer << endl;

    return wholeAnswer;
    return std::string("");
}

Note: this code is a second version completed with your comments.

MPelletier
  • 16,256
  • 15
  • 86
  • 137
Congelli501
  • 2,403
  • 2
  • 27
  • 28
  • 10
    You said it doesn't work. What does not work? What happens? – j4x Mar 27 '12 at 12:51
  • I will not give you an answer to your problem. This might be a specific platform issue. But perhaps you might think about doing this with a higher level library than using termios. Maybe PySerial in Python or using a high level serial port I/O library in C. – Halim Qarroum Apr 02 '12 at 01:33
  • see if this works for you http://stackoverflow.com/questions/9046649/read-and-write-on-serial-port-in-ubuntu-with-c-c-and-libserial – Saurabh Ghorpade May 27 '12 at 05:59
  • 1
    Why was the code to check whether read() returned -1 commented out? It should be in there, and it should log errno, or, preferably, strerror(errno). Also you should check whether tcgetattr, cfsetospeed and cfsetispeed are returning an error. – craig65535 Jul 04 '12 at 15:18
  • man tcsetattr also says this: "Note that tcsetattr() returns success if any of the requested changes could be successfully carried out. Therefore, when making multiple changes it may be necessary to follow this call with a further call to tcgetattr() to check that all changes have been performed successfully." – craig65535 Jul 04 '12 at 15:23

2 Answers2

1

I opened the gtkterm source code and I finally found a solution : in fact, you need to override the terminos structure (and yes, you should not have to do it normally).

If someone finds a better solution, feel free to post it. In the meantime, here is the working code, with english comments :

To open the serial port :

// Doc : http://www.easysw.com/~mike/serial/serial.html#2_4

m_serialHandle = open(ttyPort.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); // Open serial port
if(m_serialHandle < 0)
{
    MY_THROW("Impossible d'ouvrir le port '" << ttyPort << "' !\nerrno = " << errno);
}

// Read mode
//if(fcntl(m_serialHandle, F_SETFL, 0) == -1) // Blocking read
if(fcntl(m_serialHandle, F_SETFL, O_NONBLOCK) == -1) // Non-blocking read
{
    MY_THROW("fcntl failed !\nerrno = " << errno);
}

// Get current terminos configuration
struct termios options;
tcgetattr(m_serialHandle, &options);

// Force termios values (should not be needed, but is)
options.c_cflag = B9600;
options.c_oflag = 0;
options.c_lflag = 0;
options.c_iflag = IGNPAR | IGNBRK;
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 1;

// Set data rate
cfsetispeed(&options, B9600); // In speed
cfsetospeed(&options, B9600); // Output speed

// Set communication flags
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_cflag |= (CLOCAL | CREAD); // Enable the receiver and set local mode...
options.c_cflag &= ~PARENB; // Desactive bit de parité
options.c_cflag &= ~CSTOPB; // Désactive 2 stop bits -> Active 1 stop bits
options.c_cflag &= ~CSIZE; // Désactive le bit "CSIZE"
options.c_cflag |= CS8; // Communication sur 8 bits

options.c_oflag &= ~OPOST; // Raw output is selected by resetting the OPOST option in the c_oflag member:

// Disable flow control
options.c_iflag &= ~(IXON | IXOFF);

// Apply
if(tcsetattr(m_serialHandle, TCSANOW, &options) == -1) // Vidage buffer & application immédiate
{
    MY_THROW("tcsetattr failed !\nerrno = " << errno);
}

// Empty buffers
tcflush(m_serialHandle, TCIOFLUSH);

To read (non-blocking)

const int buffSize = 1024;
char buffer[buffSize] = {'\0'};
int count = 0;
std::string wholeAnswer = "";

int noDataTime = 0;

while(noDataTime < 3) // while there is data to be read
{
    count = read(m_serialHandle, buffer, buffSize - 1);
    // May fail in NON-BLOCKING mode if there is nothing to be read
    /*if(count == -1)
    {
        MY_THROW("Impossible de lire sur le port serie. Verifiez la connexion avec l'imprimante !")
    }*/

    if(count > 0)
    {
        noDataTime = 0;

        buffer[count] = '\0';
        /*for(int i = 0; i < count; i++)
        {
            buffer[i] &= ~128; // Delete first binary bit. Could be useful for 7 bit communication, if the first bit is set to 1
        }*/

        wholeAnswer += std::string(buffer);
    }
    else
    {
        noDataTime++;
        usleep(100000);
    }
}

if(!wholeAnswer.empty())
{
    cerr << "----------- Answer -----------" << endl;
    cerr << "Size = " << wholeAnswer.size() << endl;
    cerr << wholeAnswer << endl;
}

return wholeAnswer;
Congelli501
  • 2,403
  • 2
  • 27
  • 28
0

Checking you code, I did not see where you set raw input mode.

You may need to add:

options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

Maybe what changed on this version of Ubuntu is that default input mode is set to CANONICAL and not raw. You can check this document for full detail:

http://www.easysw.com/~mike/serial/serial.html#2_3_2

Also check the flow control used by your other device. If it expects hardware flow control, you have to set it when opening the port. The code probably worked in a previous version because the values used by default there were compatible with your program. Your program should set all options it needs to work: port speed, parity, flow control, input mode, etc.

nmenezes
  • 910
  • 6
  • 12