Combining SD Card + ultrasonic sensor to count cars

Hi Guys,

Actually I´ve got the problem, that my code doesn´t work correctly…

The aim is to count the cars which are driving next to our house 24/7.

Problem description:
SD card inizialises correctly. After that the sensor should count the cars and write the result as a txt-file on the SD card. But the counting doesn´t work.

#include <SD.h>
#include <SPI.h>
File myFile;
int pinCS = 10; 

// defines pins numbers for the sensor (Ultraschall)
const int trigPin = 9; 
const int echoPin = 10;

// defines variables long duration;
long duration;
int distance;
float counter = 0;

void setup() {
    
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  Serial.begin(9600);
  pinMode(pinCS, OUTPUT);
  
  // SD Karte initialisieren...
  if (SD.begin())
  {
    Serial.println("SD Karte ist bereit.");
  } else
  {
    //Testen indem ich Karte entferne
    Serial.println("SD Karte kann nicht initialisiert werden."); 
    return;
  }
}
void loop() {
  

// Clears the trigPin 
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds 
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance 
  distance= duration*0.034/2;
  
  Serial.print("Distanz: ");
  Serial.println(distance);
  delay(900);

if (distance < 50 && distance > 10){ 
  counter = counter + 1; 
  Serial.print("Autos: ");
  Serial.println(counter);
  delay(900);
 
  myFile = SD.open("AnzahlAutos.txt", FILE_WRITE); //Starte mit dem Schreiben
  if (myFile) {    
    myFile.print("Autos: ");  
    myFile.println(counter);
    myFile.close(); // File schließen.
  }
  // Wenn das File nicht aufgeht, muss ein Fehler kommen:
  else {
    Serial.println("FehlerbeimÖffnen.txt");
  }
  delay(3000);
}
}

Would be great if you have some ideas/solutions for me. To be honest I´m really new into Arduino and I worked for this sketch a few days and read a lot…but I can´t find the solution (maybe I´m searching for the wrong things).
Thanks a lot for your assistance (every assistance ideas, articles, etc.) :slight_smile:
Cheers
Tobias

What does the serial monitor show?

int pinCS = 10;

const int echoPin = 10;

That looks like a problem