1

I’ve got a question about this code I’ve attached please- would it be correct to read it like this:

After defining the variable temperature and humidity and assigning measurement_timestamp to millis(), an if loop first checks if millis - measurement_timestamp < 3000 unsigned long (which doesn’t make sense to me) and then if a reading is read, it = true?

Is this correct please?

Code:

static bool measure_environment( float *temperature, float *humidity )
{
  static unsigned long measurement_timestamp = millis( );

/* Measure once every four seconds. */ if( millis( ) - measurement_timestamp > 3000ul ) { if( dht_sensor.measure( temperature, humidity ) == true ) { measurement_timestamp = millis( ); return( true ); } }

return( false ); }

sempaiscuba
  • 1,042
  • 9
  • 21
  • 32
Tom
  • 13
  • 3

1 Answers1

0

The code makes sense to me.

The comment, "/* Measure once every four seconds. */" is inaccurate. It will measure when the time since last measurement is greater than 3 seconds.

Because of "static unsigned long measurement_timestamp = millis( );", measurement_timestamp will NOT be initialized to millis() every time the function is called - it will only be initialized once for lifetime of the run. Otherwise, it would never cause a measurement since "if( millis( ) - measurement_timestamp > 3000ul )" would never be true.

The first call sets measurement_timestamp= to millis() [the current timer value] and the function returns "false"

When called 3.001 sec later, "if( millis( ) - measurement_timestamp > 3000ul )" is true - a measurement is taken, "measurement_timestamp" is updated to the current millis() and the function returns "true".

It returns "false" for the next 3 seconds and then "true" and so on.

see https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c

and How can I handle the millis() rollover?

Hope it helps.

DrG
  • 409
  • 3
  • 7