void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if (htim->Instance == TIM6) { data =1; } }
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_FATFS_Init();
MX_TIM6_Init();
MX_SPI1_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_Base_Start_IT(&htim6);
// Flash changes to the file
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
if (data == 1) {
f_mount(&fs, “0:/”, 1);
f_open(&file, “log105.csv”, FA_OPEN_APPEND| FA_WRITE) ;
// Writing text
strcpy(buffer, “Log the data in SD card\\n”);
f_write(&file, buffer, bufsize(buffer), &bw);
f_close(&file);
f_mount(NULL, “0:/”, 1);
// Clear the buffer and reset data
HAL_Delay(100);
}
} I am using an STM32F207ZG microcontroller to log data on an SD card. I’m utilizing the SD card library available at the following link: GitHub – STM32_SPI_SDCARD. Currently, my data logging occurs only once, after which the file is closed. However, I am seeking a solution to enable continuous data logging.
You can use a state machine, eliminating the need to mount and unmount the SD card every time. Ensure you implement proper error handling. This code is quite basic. If you encounter any issues after optimizing the code, we’re here to help you address them.
Hello Alokm,
After removing the need to repeatedly mount and unmount the SD card every time, the data is not continuously logged. Despite the modifications, data is only logged once in the file.
state = STATE_IDLE; // Initialize state to IDLE
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();
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_FATFS_Init();
MX_TIM6_Init();
MX_SPI1_Init();
HAL_TIM_Base_Start_IT(&htim6);
state = STATE_IDLE; // Initialize state to IDLE
if (f_mount(&fs, “0:/”, 1) != FR_OK) {
state = STATE_ERROR;
}
while (1) {
switch (state) {
case STATE_IDLE:
// Do nothing, waiting for timer callback to transition to logging state
break;
case STATE_LOGGING:
// Logging state
if (data == 1) {
fres = f_open(&file, “log.csv”, FA_OPEN_APPEND | FA_WRITE);
if (fres == FR_OK) {
// Write data to the file
strcpy(buffer, “Log the data in SD card\n”);
f_write(&file, buffer, bufsize(buffer), &bw);
f_close(&file); // Close the file
}
HAL_Delay(1000); // Delay to control the data logging rate
}
state = STATE_IDLE; // Transition back to the IDLE state
break;
case STATE_ERROR:
Error_Handler();
break;
}
}
}
share me the link of your code
https://drive.google.com/file/d/1BIi7qU9J3_G44Iyi9L7znqrH1DdREfsz/view?usp=drive_link
Could someone please assist me with the issue mentioned above?
#include
#include “fatfs.h”
#include
FATFS gSDFatFs; /// File system object for SD card logical drive
FIL gMyFile; /// File object
char aSDPath[4] = { 0 }; /// SD card logical drive path
static uint8_t aExcelHeader[] = “Time, vCell1, vCell2, vCell3, vCell4, vCell5, vCell6, vCell7, vCell8, vCell9, vCell10, vCell11, vCell12, vCell13, vCell14, vCell15, vCell16, Stack Voltage, PACK Pin Voltage, LD Pin Voltage, CC2 Current, TS1, TS2, TS3, TS4”;
/**
* @brief Create Default Directories.
* @param none
* @retval FRESULT status
* @warning This function takes 2 seconds to create directory
*/
uint8_t SD_Init(void)
{
FRESULT ret; /* FatFs function common result code */
ret = f_mount(&gSDFatFs, (TCHAR const*)aSDPath, 1);
if(ret != FR_OK)
{
/* f_mount failed */
return ret;
}
// Create New Folder
ret = f_mkdir(“Logs”);
if((ret != FR_EXIST) && (ret != FR_OK))
{
/* f_mount failed */
return ret;
}
/* ToDo
* create a file to log desynchronized data
*/
ret = f_mount(NULL, (TCHAR const*)aSDPath, 1);
return ret;
}
/**
* @brief Append data into sd card and create file if not exist.
* @param pDir file name
* @param pData The buffer to write
* @retval FRESULT status
*/
uint8_t SD_File_Operations( uint8_t *pDir, uint8_t *pData)
{
FRESULT ret; /* FatFs function common result code */
uint32_t byteswritten; /* File write/read counts */
uint8_t aDirPath[20];
sprintf((char*)aDirPath,”Logs/%s.csv\n”,pDir); /* File read buffer */
ret = f_mount(&gSDFatFs, (TCHAR const*)aSDPath, 1);
if(ret != FR_OK)
{
/* f_mount failed */
return ret;
}
// Create New file
switch (f_open(&gMyFile, (char*)aDirPath, FA_CREATE_NEW | FA_WRITE))
{
case FR_EXIST:
f_open(&gMyFile, (char*)aDirPath, FA_OPEN_APPEND | FA_WRITE);
ret = f_write(&gMyFile, pData, strlen((char *)pData), (void *)&byteswritten);
if((byteswritten == 0) || (ret != FR_OK))
{
return ret;
}
f_close(&gMyFile);
break;
case FR_OK:
ret = f_write(&gMyFile, aExcelHeader, strlen((char *)aExcelHeader), (void *)&byteswritten);
if((byteswritten == 0) || (ret != FR_OK))
{
return ret;
}
f_close(&gMyFile);
break;
default:
return ret;
}
ret = f_mount(NULL, (TCHAR const*)aSDPath, 1);
return ret;
}
/* USER CODE BEGIN Header */
/**
******************************************************************************
* FILEUSE@BELLSOUTH.NET : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2023 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 “fatfs.h”
/* Private includes ———————————————————-*/
/* USER CODE BEGIN Includes */
#include “string.h”
#include “diskio.h”
#include “ff.h”
FATFS fs;
FIL file;
uint8_t ndata;
uint8_t buffer[256];
static uint8_t header[] = “Time, volt, current”;
char sdpath[4]={0};
/* USER CODE END Includes */
/* Private typedef ———————————————————–*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ————————————————————*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro ————————————————————-*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ———————————————————*/
SPI_HandleTypeDef hspi1;
TIM_HandleTypeDef htim2;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes ———————————————–*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM2_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ———————————————————*/
/* USER CODE BEGIN 0 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
UNUSED(htim);
if (htim->Instance == TIM2) {
HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_0);
ndata =1;
}
}
uint8_t sdinit(void){
FRESULT ret;
ret = f_mount(&fs, (TCHAR const*)sdpath, 1);
if(ret != FR_OK)
{
return ret;
}
ret=f_mkdir(“logs”);
if((ret!=FR_EXIST)&&(ret!=FR_OK)){
return ret;
}
ret = f_mount(NULL,(TCHAR const*)sdpath, 1);
return ret;
}
uint8_t sdfileoperation(char *pDir, uint8_t *pData)
{
FRESULT ret;
uint32_t byteswritten;
uint8_t aDirpath[20];
sprintf((char*)aDirpath, “logs/%s.csv\n”, pDir);
ret = f_mount(&fs, (TCHAR const*)sdpath, 1);
if(ret != FR_OK)
{
return ret;
}
switch(f_open(&file,(char*)aDirpath , FA_CREATE_NEW|FA_WRITE))
{
case FR_EXIST:
f_open(&file,(char*)aDirpath , FA_OPEN_APPEND|FA_WRITE);
ret= f_write(&file, pData, strlen((char*)pData), (void*)&byteswritten);
if((byteswritten == 0)|| (ret!=FR_OK))
{
return ret;
}
f_close(&file);
break;
case FR_OK:
ret = f_write(&file, header, strlen((char*)header), (void*)&byteswritten);
if((byteswritten == 0)|| (ret!=FR_OK))
{
return ret;
}
f_close(&file);
break;
default:
return ret;
}
ret=f_mount(NULL, (TCHAR const*)sdpath, 1);
return ret;
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
//FRESULT ret;
/* 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_FATFS_Init();
MX_SPI1_Init();
MX_TIM2_Init();
/* USER CODE BEGIN 2 */
if (sdinit() != FR_OK) {
Error_Handler();
}
HAL_TIM_Base_Start_IT(&htim2);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
if (ndata == 1) {
sdfileoperation(“test”, buffer);
ndata = 0;
}
}
// fclose(&file);
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** 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 = 5;
RCC_OscInitStruct.PLL.PLLN = 225;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV6;
RCC_OscInitStruct.PLL.PLLQ = 4;
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_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 3000;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 1000;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_0, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);
/*Configure GPIO pin : PC0 */
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pin : PB6 */
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
/* 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 */
I am currently utilizing the state machine program you recommended. However, I’ve observed that the data is written to the file only once before closing it. My aim is to enhance the program to enable continuous data logging. where the file remains open for ongoing data writes.