Coding Help (How to make an action happen when states change only)

Here's my code so far:

#include <Chrono.h>
#include <SD.h>
#include <SPI.h>

File myFile;

int pinCS = 10;
int LDR = 0;

Chrono millisChrono;

void setup() {
  pinMode(pinCS, OUTPUT);
  pinMode(LDR, INPUT);

  //SD Booting
  if (SD.begin())
    Serial.println("SD Card is ready to use.");
  } else
    Serial.print("SD card initialization failed");

  //Create or open file
  myFile ="Data.txt", FILE_WRITE);

  //opened succesfully
  if(myFile) {
    Serial.println("Ready to Log :)");
  else {
    Serial.print("error opening Data.txt");

void loop() {

  if (analogRead(LDR) < 100) {


Hello, I'm new to coding. I'm using Chronos to keep track of the elapsed time since the program started or since the timer was reset.
I want to measure the period at different times of a rotating object. To do this I'm using an LDR sensor to detect when a light beam is blocked. Once the LDR reads below a threshold level I want the program to write the elapsed time onto the SD and then reset the clock. Is there a way to make it so that I only measure the time when it goes dark once and resets after it's bright again?

The Arduino State Change Detection example was written to illustrate the technique.


1 Like

Can you explain a bit more? Why are you using chronos - are the changes going to be very slow (weeks, months?)
You can easily use millis() to do this sort of timing.

If the object is rotating rapidly an LDR wont be fast enough, you should use a photodiode.

1 Like

I'm using Chronos to measure the elapsed time of each rotation. The change is going to be quite fast maybe a couple of times per second. I see now I'll check these files out. I think it might be too fast so I'll switch over to a photodiode. Thank you so much for all your help!

Thanks :smiley:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.