跳转至

rocketpi_sd_pic_to_lcd

驱动以及测试代码

Core/Src/main.c
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "fatfs.h"
#include "sdio.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <ctype.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "st7789.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#ifndef LCD_FRAME_NAME_MAX
#define LCD_FRAME_NAME_MAX 13U
#endif

typedef struct
{
  char name[LCD_FRAME_NAME_MAX];
} LCD_FrameEntry;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#ifndef _USE_MKFS
#define _USE_MKFS 1
#endif

#if (_USE_MKFS == 1)
#define FATFS_MKFS_BUFFER_SIZE 4096U
#endif
#define FATFS_SPEED_TEST_BUFFER_SIZE 4096U

#define LCD_FRAME_DIRECTORY        "PIC_BIN"
#define LCD_FRAME_EXTENSION        ".bin"
#define LCD_FRAME_DELAY_MS         25U
#define LCD_FRAME_PATH_MAX         64U
#define LCD_FRAME_LINE_BYTES       (ST7789_WIDTH * 2U)
#define LCD_FRAME_ROWS             ST7789_HIGHT
#define LCD_FRAME_MAX_COUNT        600U
#define LCD_FRAME_BATCH_ROWS       120U
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
static void FATFS_Test(void);
static void FATFS_SpeedTest(uint32_t kilobytes);
static void FATFS_PlaybackFrames(void);
static void FATFS_PlaybackFramesOptimized(void);
static void LCD_LogError(const char *fmt, ...);
static FRESULT LCD_BuildFramePath(char *frame_path, size_t frame_path_size, const char *directory, const char *file_name);
static FRESULT LCD_DrawFrameBatched(const char *directory,
                                    const char *file_name,
                                    uint8_t *batch_buffer,
                                    UINT batch_rows);
static FRESULT LCD_PopulateFrameList(const char *directory,
                                     LCD_FrameEntry *entries,
                                     UINT max_entries,
                                     UINT *out_count);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART2_UART_Init();
  MX_SPI1_Init();
  MX_ADC1_Init();
  MX_SDIO_SD_Init();
  MX_FATFS_Init();
  /* USER CODE BEGIN 2 */
  HAL_Delay(200);
  FATFS_Test();
  const uint32_t speed_test_kbytes = 512U; /* Adjust size to profile different transfers */
  FATFS_SpeedTest(speed_test_kbytes);

  ST7789_Init();
  ST7789_TestFrameRate();
  ST7789_Clear(BLACK);
  /* USER CODE END 2 */

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

    /* USER CODE BEGIN 3 */
    FATFS_PlaybackFramesOptimized();
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 84;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 7;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
static bool LCD_IsBinFrame(const char *name)
{
  if ((name == NULL) || (name[0] == '\0') || (name[0] == '.'))
  {
    return false;
  }

  const size_t ext_len = strlen(LCD_FRAME_EXTENSION);
  const size_t name_len = strlen(name);
  if (name_len < ext_len)
  {
    return false;
  }

  const char *ext = name + name_len - ext_len;
  for (size_t i = 0U; i < ext_len; ++i)
  {
    const char lhs = (char)tolower((unsigned char)ext[i]);
    const char rhs = (char)tolower((unsigned char)LCD_FRAME_EXTENSION[i]);
    if (lhs != rhs)
    {
      return false;
    }
  }

  return true;
}

static void LCD_LogError(const char *fmt, ...)
{
  va_list args;
  va_start(args, fmt);
  vprintf(fmt, args);
  va_end(args);
  HAL_Delay(500U);
}

static FRESULT LCD_BuildFramePath(char *frame_path, size_t frame_path_size, const char *directory, const char *file_name)
{
  int written = 0;
  if ((directory != NULL) && (directory[0] != '\0'))
  {
    written = snprintf(frame_path, frame_path_size, "%s/%s", directory, file_name);
  }
  else
  {
    written = snprintf(frame_path, frame_path_size, "%s", file_name);
  }

  if ((written <= 0) || ((size_t)written >= frame_path_size))
  {
    return FR_INVALID_NAME;
  }

  return FR_OK;
}

static FRESULT LCD_DrawFrameFromFile(const char *directory,
                                     const char *file_name,
                                     uint8_t *line_buffer,
                                     UINT line_bytes)
{
  char frame_path[LCD_FRAME_PATH_MAX];
  FRESULT res = LCD_BuildFramePath(frame_path, sizeof(frame_path), directory, file_name);
  if (res != FR_OK)
  {
    return res;
  }

  FIL frame_file;
  res = f_open(&frame_file, frame_path, FA_READ);
  if (res != FR_OK)
  {
    return res;
  }

  for (uint32_t row = 0U; row < LCD_FRAME_ROWS; ++row)
  {
    UINT bytes_read = 0U;
    res = f_read(&frame_file, line_buffer, line_bytes, &bytes_read);
    if ((res != FR_OK) || (bytes_read != line_bytes))
    {
      if (res == FR_OK)
      {
        res = FR_INT_ERR;
      }
      break;
    }
    ST7789_DrawBitmap(0U, (uint16_t)row, ST7789_WIDTH, 1U, line_buffer);
  }

  f_close(&frame_file);
  return res;
}

static FRESULT LCD_DrawFrameBatched(const char *directory,
                                    const char *file_name,
                                    uint8_t *batch_buffer,
                                    UINT batch_rows)
{
  if ((batch_rows == 0U) || (batch_buffer == NULL))
  {
    return FR_INVALID_PARAMETER;
  }

  char frame_path[LCD_FRAME_PATH_MAX];
  FRESULT res = LCD_BuildFramePath(frame_path, sizeof(frame_path), directory, file_name);
  if (res != FR_OK)
  {
    return res;
  }

  FIL frame_file;
  res = f_open(&frame_file, frame_path, FA_READ);
  if (res != FR_OK)
  {
    return res;
  }

  uint32_t row = 0U;
  while (row < LCD_FRAME_ROWS)
  {
    UINT rows_this = batch_rows;
    if (rows_this > (LCD_FRAME_ROWS - row))
    {
      rows_this = (UINT)(LCD_FRAME_ROWS - row);
    }

    UINT bytes_request = rows_this * LCD_FRAME_LINE_BYTES;
    UINT bytes_read = 0U;
    res = f_read(&frame_file, batch_buffer, bytes_request, &bytes_read);
    if ((res != FR_OK) || (bytes_read != bytes_request))
    {
      if (res == FR_OK)
      {
        res = FR_INT_ERR;
      }
      break;
    }

    ST7789_DrawBitmap(0U, (uint16_t)row, ST7789_WIDTH, rows_this, batch_buffer);
    row += rows_this;
  }

  f_close(&frame_file);
  return res;
}

static FRESULT LCD_PopulateFrameList(const char *directory,
                                     LCD_FrameEntry *entries,
                                     UINT max_entries,
                                     UINT *out_count)
{
  if ((entries == NULL) || (out_count == NULL))
  {
    return FR_INVALID_PARAMETER;
  }

  DIR dir;
  FILINFO fno;
  FRESULT res = f_opendir(&dir, directory);
  if (res != FR_OK)
  {
    return res;
  }

  UINT count = 0U;
  while (1)
  {
    res = f_readdir(&dir, &fno);
    if (res != FR_OK)
    {
      break;
    }

    if (fno.fname[0] == '\0')
    {
      break;
    }

    if ((fno.fattrib & AM_DIR) != 0U)
    {
      continue;
    }

    if (!LCD_IsBinFrame(fno.fname))
    {
      continue;
    }

    if (count < max_entries)
    {
      strncpy(entries[count].name, fno.fname, LCD_FRAME_NAME_MAX - 1U);
      entries[count].name[LCD_FRAME_NAME_MAX - 1U] = '\0';
      count++;
    }
  }

  f_closedir(&dir);
  *out_count = count;
  return res;
}

static void FATFS_PlaybackFrames(void)
{
  DIR dir;
  FILINFO fno;
  FRESULT res;
  uint8_t is_mounted = 0U;
  uint8_t dir_opened = 0U;
  bool reached_end = false;
  uint32_t frames_shown = 0U;
  static uint8_t line_buffer[LCD_FRAME_LINE_BYTES];

  res = f_mount(&SDFatFS, (TCHAR const*)SDPath, 1);
  if (res != FR_OK)
  {
    LCD_LogError("video: mount failed (%d)\r\n", (int)res);
    return;
  }
  is_mounted = 1U;

  const char *dir_path = (LCD_FRAME_DIRECTORY[0] == '\0') ? "" : LCD_FRAME_DIRECTORY;
  res = f_opendir(&dir, dir_path);
  if (res != FR_OK)
  {
    if (LCD_FRAME_DIRECTORY[0] == '\0')
    {
      LCD_LogError("video: failed to open root directory (%d)\r\n", (int)res);
    }
    else
    {
      LCD_LogError("video: failed to open %s (%d)\r\n", LCD_FRAME_DIRECTORY, (int)res);
    }
    goto cleanup;
  }
  dir_opened = 1U;
  if (LCD_FRAME_DIRECTORY[0] == '\0')
  {
    printf("video: streaming frames from SD root\r\n");
  }
  else
  {
    printf("video: streaming frames from /%s\r\n", LCD_FRAME_DIRECTORY);
  }

  while (1)
  {
    res = f_readdir(&dir, &fno);
    if (res != FR_OK)
    {
      LCD_LogError("video: readdir failed (%d)\r\n", (int)res);
      goto cleanup;
    }

    if (fno.fname[0] == '\0')
    {
      reached_end = true;
      break;
    }

    if ((fno.fattrib & AM_DIR) != 0U)
    {
      continue;
    }

    if (!LCD_IsBinFrame(fno.fname))
    {
      continue;
    }

    res = LCD_DrawFrameFromFile(LCD_FRAME_DIRECTORY, fno.fname, line_buffer, LCD_FRAME_LINE_BYTES);
    if (res != FR_OK)
    {
      if (LCD_FRAME_DIRECTORY[0] == '\0')
      {
        LCD_LogError("video: draw %s failed (%d)\r\n", fno.fname, (int)res);
      }
      else
      {
        LCD_LogError("video: draw %s/%s failed (%d)\r\n", LCD_FRAME_DIRECTORY, fno.fname, (int)res);
      }
      continue;
    }

    frames_shown++;
    HAL_Delay(LCD_FRAME_DELAY_MS);
  }

  if (reached_end)
  {
    if (frames_shown == 0U)
    {
      if (LCD_FRAME_DIRECTORY[0] == '\0')
      {
        LCD_LogError("video: no %s frames found in root\r\n", LCD_FRAME_EXTENSION);
      }
      else
      {
        LCD_LogError("video: no %s frames found inside %s\r\n", LCD_FRAME_EXTENSION, LCD_FRAME_DIRECTORY);
      }
    }
    else
    {
      printf("video: finished %lu frames from %s\r\n", (unsigned long)frames_shown, LCD_FRAME_DIRECTORY);
    }
  }

cleanup:
  if (dir_opened)
  {
    f_closedir(&dir);
  }

  if (is_mounted)
  {
    f_mount(NULL, (TCHAR const*)SDPath, 0);
  }
}

static void FATFS_PlaybackFramesOptimized(void)
{
  static LCD_FrameEntry s_frame_cache[LCD_FRAME_MAX_COUNT];
  static UINT s_frame_count = 0U;
  static uint8_t s_cache_valid = 0U;
  static uint8_t batch_buffer[LCD_FRAME_LINE_BYTES * LCD_FRAME_BATCH_ROWS];
  uint8_t is_mounted = 0U;
  FRESULT res;
  const char *dir_path = (LCD_FRAME_DIRECTORY[0] == '\0') ? "" : LCD_FRAME_DIRECTORY;

  res = f_mount(&SDFatFS, (TCHAR const*)SDPath, 1);
  if (res != FR_OK)
  {
    LCD_LogError("video(opt): mount failed (%d)\r\n", (int)res);
    return;
  }
  is_mounted = 1U;

  if (!s_cache_valid)
  {
    res = LCD_PopulateFrameList(dir_path, s_frame_cache, LCD_FRAME_MAX_COUNT, &s_frame_count);
    if (res != FR_OK)
    {
      if (LCD_FRAME_DIRECTORY[0] == '\0')
      {
        LCD_LogError("video(opt): scan root failed (%d)\r\n", (int)res);
      }
      else
      {
        LCD_LogError("video(opt): scan %s failed (%d)\r\n", LCD_FRAME_DIRECTORY, (int)res);
      }
      goto cleanup;
    }

    if (s_frame_count == 0U)
    {
      if (LCD_FRAME_DIRECTORY[0] == '\0')
      {
        LCD_LogError("video(opt): no %s frames in root\r\n", LCD_FRAME_EXTENSION);
      }
      else
      {
        LCD_LogError("video(opt): no %s frames inside %s\r\n", LCD_FRAME_EXTENSION, LCD_FRAME_DIRECTORY);
      }
      goto cleanup;
    }

    if (LCD_FRAME_DIRECTORY[0] == '\0')
    {
      printf("video(opt): cached %lu frames from SD root\r\n", (unsigned long)s_frame_count);
    }
    else
    {
      printf("video(opt): cached %lu frames from /%s\r\n",
             (unsigned long)s_frame_count, LCD_FRAME_DIRECTORY);
    }
    s_cache_valid = 1U;
  }

  if (LCD_FRAME_DIRECTORY[0] == '\0')
  {
    printf("video(opt): streaming cached frames from SD root\r\n");
  }
  else
  {
    printf("video(opt): streaming cached frames from /%s\r\n", LCD_FRAME_DIRECTORY);
  }

  uint32_t cycle_start = HAL_GetTick();
  uint32_t frames_drawn = 0U;
  for (UINT idx = 0U; idx < s_frame_count; ++idx)
  {
    res = LCD_DrawFrameBatched(dir_path, s_frame_cache[idx].name, batch_buffer, LCD_FRAME_BATCH_ROWS);
    if (res != FR_OK)
    {
      if (LCD_FRAME_DIRECTORY[0] == '\0')
      {
        LCD_LogError("video(opt): draw %s failed (%d)\r\n", s_frame_cache[idx].name, (int)res);
      }
      else
      {
        LCD_LogError("video(opt): draw %s/%s failed (%d)\r\n",
                     LCD_FRAME_DIRECTORY, s_frame_cache[idx].name, (int)res);
      }
      continue;
    }
    frames_drawn++;
    HAL_Delay(LCD_FRAME_DELAY_MS);
  }

  uint32_t elapsed_ms = HAL_GetTick() - cycle_start;
  if ((frames_drawn > 0U) && (elapsed_ms > 0U))
  {
    float fps = ((float)frames_drawn * 1000.0f) / (float)elapsed_ms;
    printf("video(opt): cycle %lu frames in %lums (%.2f FPS)\r\n",
           (unsigned long)frames_drawn,
           (unsigned long)elapsed_ms,
           fps);
  }

cleanup:
  if (is_mounted)
  {
    f_mount(NULL, (TCHAR const*)SDPath, 0);
  }
}

static void FATFS_SpeedTest(uint32_t kilobytes)
{
  const char speed_file[] = "sd_speed.bin";
  FRESULT res;
  UINT bytes_io = 0U;
  uint32_t total_bytes = 0U;
  uint32_t remaining = 0U;
  uint32_t start_tick = 0U;
  uint32_t elapsed_ms = 0U;
  uint32_t speed_kbs = 0U;
  uint8_t is_mounted = 0U;
  uint8_t file_opened = 0U;
  uint8_t file_created = 0U;
  static uint8_t transfer_buffer[FATFS_SPEED_TEST_BUFFER_SIZE];

  if (kilobytes == 0U)
  {
    printf("fatfs speed test: size parameter must be > 0\r\n");
    return;
  }

  if (kilobytes > (UINT32_MAX / 1024U))
  {
    printf("fatfs speed test: size too large\r\n");
    return;
  }

  total_bytes = kilobytes * 1024U;

  for (uint32_t i = 0U; i < sizeof(transfer_buffer); ++i)
  {
    transfer_buffer[i] = (uint8_t)(i & 0xFFU);
  }

  printf("fatfs speed test: mounting %s\r\n", SDPath);
  res = f_mount(&SDFatFS, (TCHAR const*)SDPath, 1);
  if (res != FR_OK)
  {
    printf("fatfs speed test: mount failed (%d)\r\n", (int)res);
    return;
  }
  is_mounted = 1U;

  res = f_open(&SDFile, speed_file, FA_CREATE_ALWAYS | FA_WRITE);
  if (res != FR_OK)
  {
    printf("fatfs speed test: open for write failed (%d)\r\n", (int)res);
    goto cleanup;
  }
  file_opened = 1U;
  file_created = 1U;

  printf("fatfs speed test: writing %lu KB\r\n", (unsigned long)kilobytes);
  remaining = total_bytes;
  start_tick = HAL_GetTick();
  while (remaining > 0U)
  {
    uint32_t chunk = (remaining > sizeof(transfer_buffer)) ? (uint32_t)sizeof(transfer_buffer) : remaining;
    res = f_write(&SDFile, transfer_buffer, chunk, &bytes_io);
    if ((res != FR_OK) || (bytes_io != chunk))
    {
      printf("fatfs speed test: write error (%d)\r\n", (int)res);
      goto cleanup;
    }
    remaining -= chunk;
  }

  res = f_sync(&SDFile);
  if (res != FR_OK)
  {
    printf("fatfs speed test: sync failed (%d)\r\n", (int)res);
    goto cleanup;
  }
  elapsed_ms = HAL_GetTick() - start_tick;
  speed_kbs = (elapsed_ms > 0U) ? (uint32_t)(((uint64_t)total_bytes * 1000ULL) / ((uint64_t)elapsed_ms * 1024ULL)) : 0U;
  printf("fatfs speed test: write done in %lu ms (%lu KB/s)\r\n",
         (unsigned long)elapsed_ms, (unsigned long)speed_kbs);

  f_close(&SDFile);
  file_opened = 0U;

  res = f_open(&SDFile, speed_file, FA_READ);
  if (res != FR_OK)
  {
    printf("fatfs speed test: open for read failed (%d)\r\n", (int)res);
    goto cleanup;
  }
  file_opened = 1U;

  printf("fatfs speed test: reading %lu KB\r\n", (unsigned long)kilobytes);
  remaining = total_bytes;
  start_tick = HAL_GetTick();
  while (remaining > 0U)
  {
    uint32_t chunk = (remaining > sizeof(transfer_buffer)) ? (uint32_t)sizeof(transfer_buffer) : remaining;
    res = f_read(&SDFile, transfer_buffer, chunk, &bytes_io);
    if (res != FR_OK)
    {
      printf("fatfs speed test: read error (%d)\r\n", (int)res);
      goto cleanup;
    }
    if (bytes_io == 0U)
    {
      printf("fatfs speed test: unexpected end of file\r\n");
      goto cleanup;
    }
    remaining -= bytes_io;
  }
  elapsed_ms = HAL_GetTick() - start_tick;
  speed_kbs = (elapsed_ms > 0U) ? (uint32_t)(((uint64_t)total_bytes * 1000ULL) / ((uint64_t)elapsed_ms * 1024ULL)) : 0U;
  printf("fatfs speed test: read done in %lu ms (%lu KB/s)\r\n",
         (unsigned long)elapsed_ms, (unsigned long)speed_kbs);

  f_close(&SDFile);
  file_opened = 0U;

  printf("fatfs speed test: removing %s\r\n", speed_file);
  res = f_unlink(speed_file);
  if (res == FR_OK)
  {
    file_created = 0U;
  }
  else
  {
    printf("fatfs speed test: remove failed (%d)\r\n", (int)res);
  }

cleanup:
  if (file_opened)
  {
    f_close(&SDFile);
  }

  if (is_mounted && file_created)
  {
    FRESULT unlink_res = f_unlink(speed_file);
    if (unlink_res != FR_OK)
    {
      printf("fatfs speed test: cleanup remove %s failed (%d)\r\n", speed_file, (int)unlink_res);
    }
  }

  if (is_mounted)
  {
    f_mount(NULL, (TCHAR const*)SDPath, 0);
    printf("fatfs speed test: unmounted\r\n");
  }
}

static void FATFS_Test(void)
{
  const char test_file[] = "rocketpi.txt";
  const char test_payload[] = "RocketPi FATFS SDIO write/read demo.\r\n";
  char read_buffer[sizeof(test_payload)] = {0};
  const UINT payload_len = (UINT)strlen(test_payload);
  UINT bytes_written = 0;
  UINT bytes_read = 0;
  FRESULT res;
  uint8_t is_mounted = 0;
  uint8_t file_opened = 0;

  printf("fatfs: mounting %s\r\n", SDPath);
  res = f_mount(&SDFatFS, (TCHAR const*)SDPath, 1);
  if (res == FR_OK)
  {
    is_mounted = 1;
  }
  else if (res == FR_NO_FILESYSTEM)
  {
#if (_USE_MKFS == 1)
#if (FATFS_MKFS_BUFFER_SIZE < 1024U)
#error "FATFS_MKFS_BUFFER_SIZE must be >= 1024 bytes"
#endif
    static uint8_t mkfs_work[FATFS_MKFS_BUFFER_SIZE];

    printf("fatfs: no filesystem, formatting...\r\n");
    res = f_mkfs((TCHAR const*)SDPath, FM_ANY, 0, mkfs_work, sizeof(mkfs_work));
    if (res != FR_OK)
    {
      printf("fatfs: format failed (%d)\r\n", (int)res);
      return;
    }

    printf("fatfs: format complete, remounting\r\n");
    res = f_mount(&SDFatFS, (TCHAR const*)SDPath, 1);
    if (res != FR_OK)
    {
      printf("fatfs: mount after format failed (%d)\r\n", (int)res);
      return;
    }
    is_mounted = 1;
#else
    printf("fatfs: no filesystem and mkfs disabled\r\n");
    return;
#endif
  }
  else
  {
    printf("fatfs: mount failed (%d)\r\n", (int)res);
    return;
  }

  printf("fatfs: creating %s\r\n", test_file);
  res = f_open(&SDFile, test_file, FA_CREATE_ALWAYS | FA_WRITE);
  if (res != FR_OK)
  {
    printf("fatfs: open for write failed (%d)\r\n", (int)res);
    goto cleanup;
  }
  file_opened = 1;

  res = f_write(&SDFile, test_payload, payload_len, &bytes_written);
  if ((res != FR_OK) || (bytes_written != payload_len))
  {
    printf("fatfs: write failed (%d)\r\n", (int)res);
    goto cleanup;
  }
  printf("fatfs: wrote %lu bytes\r\n", (unsigned long)bytes_written);

  f_close(&SDFile);
  file_opened = 0;

  res = f_open(&SDFile, test_file, FA_READ);
  if (res != FR_OK)
  {
    printf("fatfs: open for read failed (%d)\r\n", (int)res);
    goto cleanup;
  }
  file_opened = 1;

  memset(read_buffer, 0, sizeof(read_buffer));
  res = f_read(&SDFile, read_buffer, sizeof(read_buffer) - 1, &bytes_read);
  if (res != FR_OK)
  {
    printf("fatfs: read failed (%d)\r\n", (int)res);
    goto cleanup;
  }
  printf("fatfs: read %lu bytes\r\n", (unsigned long)bytes_read);

  f_close(&SDFile);
  file_opened = 0;

  if ((bytes_read == bytes_written) && (strncmp(read_buffer, test_payload, payload_len) == 0))
  {
    printf("fatfs: verification OK\r\n");
    printf("fatfs: content: %s", read_buffer);
  }
  else
  {
    printf("fatfs: verification failed\r\n");
  }

cleanup:
  if (file_opened)
  {
    f_close(&SDFile);
  }

  if (is_mounted)
  {
    f_mount(NULL, (TCHAR const*)SDPath, 0);
    printf("fatfs: unmounted\r\n");
  }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
Core/Src/stm32f4xx_it.c
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    stm32f4xx_it.c
  * @brief   Interrupt Service Routines.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */

/* USER CODE END TD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_sdio_rx;
extern DMA_HandleTypeDef hdma_sdio_tx;
extern SD_HandleTypeDef hsd;
extern DMA_HandleTypeDef hdma_spi1_tx;
extern SPI_HandleTypeDef hspi1;
/* USER CODE BEGIN EV */

/* USER CODE END EV */

/******************************************************************************/
/*           Cortex-M4 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/**
  * @brief This function handles Non maskable interrupt.
  */
void NMI_Handler(void)
{
  /* USER CODE BEGIN NonMaskableInt_IRQn 0 */

  /* USER CODE END NonMaskableInt_IRQn 0 */
  /* USER CODE BEGIN NonMaskableInt_IRQn 1 */
   while (1)
  {
  }
  /* USER CODE END NonMaskableInt_IRQn 1 */
}

/**
  * @brief This function handles Hard fault interrupt.
  */
void HardFault_Handler(void)
{
  /* USER CODE BEGIN HardFault_IRQn 0 */

  /* USER CODE END HardFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_HardFault_IRQn 0 */
    /* USER CODE END W1_HardFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Memory management fault.
  */
void MemManage_Handler(void)
{
  /* USER CODE BEGIN MemoryManagement_IRQn 0 */

  /* USER CODE END MemoryManagement_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
    /* USER CODE END W1_MemoryManagement_IRQn 0 */
  }
}

/**
  * @brief This function handles Pre-fetch fault, memory access fault.
  */
void BusFault_Handler(void)
{
  /* USER CODE BEGIN BusFault_IRQn 0 */

  /* USER CODE END BusFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_BusFault_IRQn 0 */
    /* USER CODE END W1_BusFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Undefined instruction or illegal state.
  */
void UsageFault_Handler(void)
{
  /* USER CODE BEGIN UsageFault_IRQn 0 */

  /* USER CODE END UsageFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_UsageFault_IRQn 0 */
    /* USER CODE END W1_UsageFault_IRQn 0 */
  }
}

/**
  * @brief This function handles System service call via SWI instruction.
  */
void SVC_Handler(void)
{
  /* USER CODE BEGIN SVCall_IRQn 0 */

  /* USER CODE END SVCall_IRQn 0 */
  /* USER CODE BEGIN SVCall_IRQn 1 */

  /* USER CODE END SVCall_IRQn 1 */
}

/**
  * @brief This function handles Debug monitor.
  */
void DebugMon_Handler(void)
{
  /* USER CODE BEGIN DebugMonitor_IRQn 0 */

  /* USER CODE END DebugMonitor_IRQn 0 */
  /* USER CODE BEGIN DebugMonitor_IRQn 1 */

  /* USER CODE END DebugMonitor_IRQn 1 */
}

/**
  * @brief This function handles Pendable request for system service.
  */
void PendSV_Handler(void)
{
  /* USER CODE BEGIN PendSV_IRQn 0 */

  /* USER CODE END PendSV_IRQn 0 */
  /* USER CODE BEGIN PendSV_IRQn 1 */

  /* USER CODE END PendSV_IRQn 1 */
}

/**
  * @brief This function handles System tick timer.
  */
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F4xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f4xx.s).                    */
/******************************************************************************/

/**
  * @brief This function handles SPI1 global interrupt.
  */
void SPI1_IRQHandler(void)
{
  /* USER CODE BEGIN SPI1_IRQn 0 */

  /* USER CODE END SPI1_IRQn 0 */
  HAL_SPI_IRQHandler(&hspi1);
  /* USER CODE BEGIN SPI1_IRQn 1 */

  /* USER CODE END SPI1_IRQn 1 */
}

/**
  * @brief This function handles SDIO global interrupt.
  */
void SDIO_IRQHandler(void)
{
  /* USER CODE BEGIN SDIO_IRQn 0 */

  /* USER CODE END SDIO_IRQn 0 */
  HAL_SD_IRQHandler(&hsd);
  /* USER CODE BEGIN SDIO_IRQn 1 */

  /* USER CODE END SDIO_IRQn 1 */
}

/**
  * @brief This function handles DMA2 stream3 global interrupt.
  */
void DMA2_Stream3_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream3_IRQn 0 */

  /* USER CODE END DMA2_Stream3_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_sdio_tx);
  /* USER CODE BEGIN DMA2_Stream3_IRQn 1 */

  /* USER CODE END DMA2_Stream3_IRQn 1 */
}

/**
  * @brief This function handles DMA2 stream5 global interrupt.
  */
void DMA2_Stream5_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream5_IRQn 0 */

  /* USER CODE END DMA2_Stream5_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_spi1_tx);
  /* USER CODE BEGIN DMA2_Stream5_IRQn 1 */

  /* USER CODE END DMA2_Stream5_IRQn 1 */
}

/**
  * @brief This function handles DMA2 stream6 global interrupt.
  */
void DMA2_Stream6_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Stream6_IRQn 0 */

  /* USER CODE END DMA2_Stream6_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_sdio_rx);
  /* USER CODE BEGIN DMA2_Stream6_IRQn 1 */

  /* USER CODE END DMA2_Stream6_IRQn 1 */
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */