accurate sampling in c++

前端 未结 2 1391
耶瑟儿~
耶瑟儿~ 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:38

    I would use boost::asio::deadline_timer.

    #include 
    
    #define BOOST_ERROR_CODE_HEADER_ONLY 1
    #include 
    #include 
    
    std::vector sample_a_chunk(unsigned int rate, unsigned int block_size_in_seconds) {
      std::vector data;
      const unsigned int times = rate * block_size_in_seconds;
      auto expiration_time = boost::posix_time::microsec_clock::local_time();
      const auto delay = boost::posix_time::microseconds(1000000/rate);
      boost::asio::io_service io;
      boost::asio::deadline_timer t(io);
    
      for (unsigned int j=0; j < times; j++) {
        expiration_time += delay;
        data.emplace_back(/* read the value from the gpio */);
        t.expires_at(expiration_time);
        t.wait();
      }
      return data;
    }
    

提交回复
热议问题