For a hobby project to play audio files, I was planning Counting Files on SD card. A bit of browsing internet and we were not able to find something desirable in top searches. To overcome the situation, it was decided to add a bit of additional variable “int fileCountOnSD = 0; in Arduino’s SD card library example “List files” to count files are it print files. You can remove the serial print commands, if only wish to count files.

This post assumes, that you have already setup sdcard module with arduino, to recap

  • STEP 1: Attach SD card module with arduino and connect pins to the pins mentioned in start of code under heading “The circuit:”
  • STEP 2: copy the code below in new file OR download and open code.ino in arduino ide
  • STEP 3: Upload the code to your arduino and open serial monitor by clicking this icon

you will see FileCountonSD before “Done’ message

Serial monitor in Arduino IDE showing files list as per example, with files count as per modification

All this update does is add +1 when it serial prints files name fileCountOnSD++;
where ++ is just a fancy /short way of writing
fileCountOnSD = fileCountOnSD + 1;

Here is the updated code. or download Arduino file


  This example shows how print out the files in a
  directory on a SD card

  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe
  modified 2 Feb 2014
  by Scott Fitzgerald

  This example code is in the public domain.

  File count part added by : Arif Saeed


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

File root;

int fileCountOnSD = 0; // for counting files

void setup() {
  // Open serial communications and wait for port to open:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  Serial.println("initialization done.");

  root ="/");

  printDirectory(root, 0);

  // Now print the total files count
  Serial.println(F("fileCountOnSD: "));

} // end setup

void loop() {
  // nothing happens after setup finishes.

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
    for (uint8_t i = 0; i < numTabs; i++) {

    // for each file count it

    if (entry.isDirectory()) {
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.println(entry.size(), DEC);

Hire |

Follow |