SD log help!!!

I have a program where I am measuring the time in between when a sensor is switched on/off. I have gotten the data to log to the sd card and store it in a csv file. The problem is when I open it in excel it shows thousands of lines when it has only ran for 30 seconds because it is logging everytime there is a change in the millis(). Is there a way that I can get it to log to the sd card only when the sensor changes? Instead of the time? I am new to programming and trying to teach myself, so any help is appreciated!

#include <SD.h>

int inputPin = 2; //Infrared Sensor
int counter = 0;
int state;
int laststate = HIGH;
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int refreshrate = 10;
const int CS_PIN = 10;
const int POW_PIN = 8;

void setup() {
  Serial.begin(9600);
  Serial.println("Initializing Card");
  pinMode(CS_PIN, OUTPUT);
  pinMode(POW_PIN, OUTPUT);
  digitalWrite(POW_PIN, HIGH);
  if (!SD.begin(CS_PIN)) {
    Serial.println("Card Failure");
    return;
  }
  Serial.println("Card Ready");
  
  File commandFile = SD.open("speed.txt");
  if (commandFile) {
    Serial.println("Reading Command File");
    while(commandFile.available()) {
      refreshrate = commandFile.parseInt();
    }
    Serial.print("Refresh Rate = ");
    Serial.print(refreshrate);
    Serial.println("ms");
    commandFile.close();
  }
  else {
    Serial.println("Could not read command file.");
    return;
  }
}


void loop()
{
  int state = digitalRead(inputPin);
  File dataFile =SD.open("log.csv",FILE_WRITE);
    if ( state != laststate) 
  {
     lastDebounceTime = millis();
     laststate = state;
     counter=counter+1;
  }
  if (dataFile) {
    dataFile.print(counter);
    dataFile.print(",");
    dataFile.print(millis()/10);
    dataFile.println("CentiSeconds");
    dataFile.close();
    
    Serial.print(counter);
    Serial.print(",");
    Serial.println(millis()/10);
 
  }
}

Hello,

I think you just need to move your logging code inside the

if ( state != laststate)

block

Wow. Thanks!