Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9172453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T16:20:58+00:00 2026-06-17T16:20:58+00:00

I want to read data from my serial port on Linux with C/C++ code.

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T16:20:59+00:00Added an answer on June 17, 2026 at 4:20 pm

    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;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Okay, so I want to have a generic method that can read data from
I have the following code which needs the data to be read from port
I can capture data from serial device via pyserial, at this time I can
I want to read web service data from a website and display it into
I want to read data about MMORPG characters from a .txt file and then
I want to read both formatted text and binary data from the same iostream.
I want to simply read some JSON data from a URL, then turn that
I'm making chat application and read messages data from SQLite database. I want to
I have Uitable with data read from a AScii file. I want to select
Read about Server push here . I want to push data to client from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.