wjwwood / serial

Cross-platform, Serial Port library written in C++
http://wjwwood.github.com/serial/
MIT License
2.13k stars 1.04k forks source link

Unexpected serial reading rates #208

Closed aaamorgan closed 3 years ago

aaamorgan commented 5 years ago

When using this library, the read interval is inconsistent. The data comes in at 10Hz, but the serial reads are not happening at 10Hz. Instead, there is a long wait and then several data packets are pushed through. This is seen when the following code is run:

int main()
{
    auto serialPort = serial::Serial("/dev/ttyACM0");
    auto timeout = serial::Timeout::simpleTimeout(50);
    serialPort.setTimeout(timeout);

    for (int i = 0; i < 100; i++) {
        std::vector<uint8_t> dataBuffer;
        serialPort.read(dataBuffer, 1000);
        std::cout << std::endl << "Got some data!";

        auto now = std::chrono::high_resolution_clock::now();
        auto duration = now.time_since_epoch();
        auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
        duration -= seconds;
        auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
        duration -= milliseconds;
        auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration);
        duration -= microseconds;

        double fullTime = (double)seconds.count() + ((double)milliseconds.count()/1000.0) + ((double)microseconds.count()/1000000.0);
        static auto fullTimePrev = fullTime;
        auto fullTimeDelta = fullTime-fullTimePrev;

        std::cout <<  std::endl << "Time since last seen: " << fullTimeDelta*1000 << " ms" << std::endl;

        fullTimePrev = fullTime;
    }
}

The timing output shows data of the form: Got some data! Time since last seen: 790.978193 ms

Got some data! Time since last seen: 0.092030 ms

Got some data! Time since last seen: 0.041008 ms

Got some data! Time since last seen: 0.046015 ms

Got some data! Time since last seen: 0.046015 ms

Got some data! Time since last seen: 0.044823 ms

Got some data! Time since last seen: 655.537128 ms

Got some data! Time since last seen: 0.087738 ms

Is this expected behavior or is there something missing from how the library is used? This is running on linux. Thanks!

ComeBackTo2016 commented 4 years ago

Maybe you can set some parameter called timeout!

wjwwood commented 3 years ago

I'm going to close this because it is old, but please comment and I can reopen if needed.