accurate sampling in c++

前端 未结 2 1417
耶瑟儿~
耶瑟儿~ 2021-01-06 21:55

I want to sample values I get from a gpio 4000 times per second, currently I do something like that:

std::vector sample_a_chunk(unsigned int rate         


        
2条回答
  •  长情又很酷
    2021-01-06 22:24

    I think the best you can probably achieve is to use absolute timing so as to avoid drift.

    Something like this:

    std::vector sample_a_chunk(unsigned int rate,
        unsigned int block_size_in_seconds)
    {
        using clock = std::chrono::steady_clock;
    
        std::vector data;
    
        const auto times = rate * block_size_in_seconds;
        const auto delay = std::chrono::microseconds{1000000 / rate};
    
        auto next_sample = clock::now() + delay;
    
        for(int j = 0; j < times; j++)
        {
            data.emplace_back(/* read the value from the gpio */);
    
            std::this_thread::sleep_until(next_sample);
    
            next_sample += delay; // don't refer back to clock, stay absolute
        }
        return data;
    }
    

提交回复
热议问题