Creating a serial number for sd card files

Hello,

I am pretty sure (since I’m generally a poor programmer) there’s a simple answer out there, but after trying to bang my way through using the typical google>copy>modify approaches, I’m stuck.

I want to create a serial number for image files I’m saving to an SD card. I want them to be in the form “IMAGE000.JPG” and be able to go up to 999. I borrowed a bit of code for 1-99 that worked just fine, but when I adapted it to what I thought would work for 1-999. I got some weird outputs. It works up to 99, but then the middle digit turns into characters. See below

IMAGE097.JPG
IMAGE098.JPG
IMAGE099.JPG
IMAGE1:0.JPG
IMAGE1:1.JPG
IMAGE1:2.JPG
IMAGE1:3.JPG
IMAGE1:4.JPG

I won’t include the whole program, but a simple version of this is below to see how it’s structured.

void setup() {

  Serial.begin(9600);
}

void loop() {
  char filename[13];
    strcpy(filename, "IMAGE000.JPG");
    for (int i = 0; i < 1000; i++) {
      filename[5] = '0' + i / 100;
      filename[6] = '0' + i / 10;
      filename[7] = '0' + i % 10;
    Serial.println(filename);
    delay(100);
  }
}

At a guess (and not knowing why) it seems like the middle digit is not rolling back to 0 after 9, but going on to other characters that represent something to it.

Love to sort this out, and welcome your help

kifling: At a guess (and not knowing why) it seems like the middle digit is not rolling back to 0 after 9

Congrats, you already found your problem. Now take a closer look at your code ;) Do you understand what the line

filename[6] = '0' + i / 10;

does?

Hint: (look what comes after '9' in the "Chr" column) |500x341

lg, couka

The sprintf() function is probably overkill, but WILL solve your problem quite nicely.

   sprintf(filename, "IMAGE%03d.txt", i);

Try:

int num = i;
filename[7] = '0' + ( num % 10 );
num /= 10;
filename[6] = '0' + ( num % 10 );
num /= 10;
filename[5] = '0' + num;

or:

filename[7] = '0' + ( i % 10 );
filename[6] = '0' + ( ( i / 10 ) % 10 );
filename[5] = '0' + ( i / 100 );