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);
  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."); 
void loop() {

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

  // Sets the trigPin on HIGH state for 10 micro seconds 
  digitalWrite(trigPin, HIGH);
  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: ");

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

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:

What does the serial monitor show?

int pinCS = 10;

const int echoPin = 10;

That looks like a problem