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,033
  • 8
  • 20
  • 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
  • 319
  • 2
  • 6
  • Hi, thank you for making things clearer- so I was wrong. What does the 3000ul mean please? – Tom Dec 23 '22 at 17:43
  • @Tom 3000ul is a literal constant and they have variable types just like other variables. In this case, the constant 3000 is designated as an unsigned long [ul] type, as is appropriate, see https://cplusplus.com/doc/tutorial/constants/ To put it simply, millis() measures in millisecond and when the difference between the last timestamp and the current millis() count is > 3000 milliseconds (3 seconds) go do your thing :) – DrG Dec 23 '22 at 17:49