cstm32sd-card

stm32 save hex number on sd card


I use this code to save data on sd card. it works good for character but when I want to save hex numbers it's output is not desirable.

FATFS myfatfs;
FIL myfile;
UINT my_biytes;
char my_data[1];
// or uint_8
char myfilename;

/* USER CODE BEGIN 2 */

f_mount(&myfatfs, SDPath ,1)     
     
/* USER CODE END 2 */

  while (1)
  {
    /* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */

          f_open (&myfile , "test2.txt" , FA_WRITE| FA_OPEN_ALWAYS  );
          data= 0x03;

          sprintf(my_data, "%x",data);
          // or  sprintf(my_data, "%c",data);

          f_lseek(&myfile, f_size(&myfile));
          f_write(&myfile, my_data, sizeof(my_data), &my_biytes);
          f_close(&myfile);

      }

when I use %x it saves "3" but i need "03".

when I use %c it saves "ETX" that is ascii form of "03"

how can I save hex numbers correctly in a txt file on sd card!!


Solution

  • when data is 0x03 I want to have 03 in my_data; so I should write %02x then two numbers (03) will come in my_data variable. and I should define my_data and sprintf like this:

    uint8_t my_data[2]
    
    sprintf(my_data, "%02x",data);