5 years, 6 months ago.

About the time to read the sensor

Hi,thx for watching my question!!! if i have three sensor(A、B、C) and i need these sensor to get data in different time. Just like i want every 1s to ask A sensor to work. and 2s to ask B and then 4s to ask C. How could i arrange the timer and set the timer? Maybe can give me an example. Thx~~~very much!!!!

1 Answer

5 years, 6 months ago.

What you need to do is start 3 Tickers, one for each sensor. They will then read the sensors at the requested rate. In the main function you loop around waiting for new sensor readings and do whatever you want with them as they become available.

This will be reliable as long as the loop in main never takes longer to run than your fastest sensors sample period, if that happens you'll start to miss samples unless you add buffering. If your fastest rate is 1 second then this isn't going to be an issue.

Ticker sensorATimer;
Ticker sensorBTimer;
Ticker sensorCTimer;

volatile bool newSensorA = false;
volatile bool newSensorB = false;
volatile bool newSensorC = false;

float sensorAValue;
float sensorBValue;
float sensorCValue;

void readSensorA() {
  sensorAValue = ... // read the sensor
  newSensorA  = true;

void readSensorB() {
  sensorBValue = ... // read the sensor
  newSensorB  = true;

void readSensorC() {
  sensorCValue = ... // read the sensor
  newSensorC  = true;

main() {
  sensorBTimer.attach(&readSensorB, 2);
  sensorCTimer.attach(&readSensorC, 4);
  while(true) {
    if (newSensorA) {
      printf("Sensor A = %.3f\r\n",sensorAValue);
      newSensorA = false;
    if (newSensorB) {
      printf("Sensor B = %.3f\r\n",sensorBValue);
      newSensorB = false;
    if (newSensorC) {
      printf("Sensor C = %.3f\r\n",sensorCValue);
      newSensorC = false;



Accepted Answer

Thanks very much!!!

posted by jajn HA 15 Nov 2016