/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "fatfs.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "ds1302.h" // 新增RTC头文件
#include "SDdriver.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define MAX_RETRIES 5
#define INITIAL_DELAY 100
#define DELAY_INCREMENT 100
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi1;
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart3;
UART_HandleTypeDef huart4g; // 新增 4G 模块 UART 句柄
/* USER CODE BEGIN PV */
uint8_t page = 0;
uint8_t uart3RecBuff = 0;
uint8_t uart4gRecBuff = 0; // 新增 4G 模块接收缓冲区
uint32_t relay_timer = 0; // 继电器计时变量
uint8_t relay_state = 0; // 继电器状态,0 表示关闭,1 表示打开
int fputc(int ch, FILE *f);
uint16_t uart_value[3];
uint8_t aRxBuffer1; //uart rx buff
BYTE WriteBuffer[] = "01 ;write; buff ;to; sd \r\n";
uint8_t write_cnt = 0; //写SD计数器
char SD_FileName[] = "hello.txt"; // 新增 SD_FileName 定义
/* 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_USART1_UART_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_USART4G_UART_Init(void); // 新增 4G 模块 UART 初始化函数
void WritetoSD(BYTE write_buff[], uint8_t bufSize);
void Get_SDCard_Capacity(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void HAL_DelayUs(uint32_t udelay)
{
uint32_t startval, tickn, delays, wait;
startval = SysTick->VAL;
tickn = HAL_GetTick();
//sysc = 72000; //SystemCoreClock / (1000U / uwTickFreq);
delays = udelay * 72; //sysc / 1000 * udelay;
if (delays > startval)
{
while (HAL_GetTick() == tickn)
{
}
wait = 72000 + startval - delays;
while (wait < SysTick->VAL)
{
}
}
else
{
wait = startval - delays;
while (wait < SysTick->VAL && HAL_GetTick() == tickn)
{
}
}
}
/********************************************************************************
* @brief initialize variables
* @param None
* @retval None
********************************************************************************/
static void InitVar(void)
{
//key value init
// 假设这些变量已经在其他地方定义
// KeyInfo.ConfirmVal = NO_KEY_PRESSED_DEF;
// KeyInfo.HoldCnt = 0;
// KeyInfo.OldVal = NO_KEY_PRESSED_DEF;
// KeyInfo.TempNewVal = NO_KEY_PRESSED_DEF;
// KeyInfo.LongPress = KEY_SHORT_PRESS;
// memset(&timeBase, 0, sizeof(Timer_Struct));
}
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (unsigned char *)&ch, 1, 0xFFFF);
return ch;
}
void WritetoSD(BYTE write_buff[], uint8_t bufSize)
{
FATFS fs;
FIL file;
uint8_t res = 0;
UINT Bw;
int retry_count;
uint32_t delay_time = INITIAL_DELAY;
printf("Starting SD card write operation...\n");
printf("SD_FileName: %s\n", SD_FileName);
printf("WriteBuffer size: %u\n", sizeof(WriteBuffer));
// 检查硬件连接和状态
if (!IsSDCardConnected()) {
printf("SD card is not connected!\n");
return;
}
retry_count = 0;
while (retry_count < MAX_RETRIES) {
res = SD_init(); //SD卡初始化
if (res == 0) {
printf("SD card initialization successful! \n");
break;
} else {
printf("SD card initialization failed! Error code: %d\n", res);
retry_count++;
if (retry_count >= MAX_RETRIES) {
printf("Max retries reached for SD card initialization. Aborting.\n");
return;
}
HAL_Delay(delay_time);
delay_time += DELAY_INCREMENT;
}
}
retry_count = 0;
delay_time = INITIAL_DELAY;
while (retry_count < MAX_RETRIES) {
res = f_mount(&fs, "0:", 1); //挂载
if (res == FR_OK) {
printf("Mounting successful! \n");
break;
} else if (res == FR_NO_FILESYSTEM) {
printf("No file system! \n");
res = f_mkfs("", 0, 0); //格式化sd卡
if (res == FR_OK) {
printf("Formatting successful! \n");
res = f_mount(NULL, "0:", 1); //格式化后取消挂载
res = f_mount(&fs, "0:", 1); //重新挂载
if (res == FR_OK) {
printf("SD card has been successfully mounted and file writing operations can be performed!\n");
break;
} else {
printf("Re-mounting failed after formatting! Error code: %d\n", res);
}
} else {
printf("Formatting failed! Error code: %d\n", res);
}
} else {
printf("Mounting failed! Error code: %d\n", res);
}
retry_count++;
if (retry_count >= MAX_RETRIES) {
printf("Max retries reached for mounting. Unmounting and aborting.\n");
f_mount(NULL, "0:", 1); // 取消挂载
return;
}
HAL_Delay(delay_time);
delay_time += DELAY_INCREMENT;
}
retry_count = 0;
delay_time = INITIAL_DELAY;
while (retry_count < MAX_RETRIES) {
printf("Trying to open file %s...\n", SD_FileName);
res = f_open(&file, SD_FileName, FA_OPEN_ALWAYS | FA_WRITE);
if (res == FR_OK) {
printf("File opened/created successfully! \n");
break;
} else {
printf("File opening failed! Error code: %d\n", res);
retry_count++;
if (retry_count >= MAX_RETRIES) {
printf("Max retries reached for file opening. Unmounting and aborting.\n");
f_mount(NULL, "0:", 1); // 取消挂载
return;
}
HAL_Delay(delay_time);
delay_time += DELAY_INCREMENT;
}
}
retry_count = 0;
delay_time = INITIAL_DELAY;
while (retry_count < MAX_RETRIES) {
printf("Seeking to the end of the file...\n");
res = f_lseek(&file, f_size(&file));//确保写入不覆盖之前的内容
if (res == FR_OK) {
printf("Seek to the end of the file successful!\n");
break;
} else {
printf("Failed to seek to the end of the file! Error code: %d\n", res);
retry_count++;
if (retry_count >= MAX_RETRIES) {
printf("Max retries reached for file seeking. Closing file, unmounting and aborting.\n");
f_close(&file);
f_mount(NULL, "0:", 1); // 取消挂载
return;
}
HAL_Delay(delay_time);
delay_time += DELAY_INCREMENT;
}
}
retry_count = 0;
delay_time = INITIAL_DELAY;
while (retry_count < MAX_RETRIES) {
printf("Writing %u bytes to the file...\n", bufSize);
res = f_write(&file, write_buff, bufSize, &Bw); //写入数据到SD卡
if (res == FR_OK && Bw == bufSize) {
printf("File written successfully! %u bytes written.\n", Bw);
break;
} else if (res != FR_OK) {
printf("File writing failed! Error code: %d\n", res);
} else {
printf("File writing incomplete! Expected %u bytes, but wrote %u bytes.\n", bufSize, Bw);
}
retry_count++;
if (retry_count >= MAX_RETRIES) {
printf("Max retries reached for file writing. Closing file, unmounting and aborting.\n");
f_close(&file);
f_mount(NULL, "0:", 1); // 取消挂载
return;
}
HAL_Delay(delay_time);
delay_time += DELAY_INCREMENT;
}
retry_count = 0;
delay_time = INITIAL_DELAY;
while (retry_count < MAX_RETRIES) {
printf("Closing the file...\n");
res = f_close(&file);
if (res == FR_OK) {
printf("File closed.\n");
break;
} else {
printf("File closing failed! Error code: %d\n", res);
retry_count++;
if (retry_count >= MAX_RETRIES) {
printf("Max retries reached for file closing. Unmounting and aborting.\n");
f_mount(NULL, "0:", 1); // 取消挂载
return;
}
HAL_Delay(delay_time);
delay_time += DELAY_INCREMENT;
}
}
retry_count = 0;
delay_time = INITIAL_DELAY;
while (retry_count < MAX_RETRIES) {
printf("Unmounting the SD card...\n");
res = f_mount(NULL, "0:", 1); //取消挂载
if (res == FR_OK) {
printf("SD card unmounted.\n");
break;
} else {
printf("Unmounting failed! Error code: %d\n", res);
retry_count++;
if (retry_count >= MAX_RETRIES) {
printf("Max retries reached for unmounting. Aborting.\n");
return;
}
HAL_Delay(delay_time);
delay_time += DELAY_INCREMENT;
}
}
printf("SD card write operation finished.\n");
}
void Get_SDCard_Capacity(void)
{
FRESULT result;
FATFS FS;
FATFS *fs;
DWORD fre_clust, AvailableSize, UsedSize;
uint16_t TotalSpace;
uint8_t res;
res = SD_init(); //SD卡初始化
if (res == 1)
{
printf("SD card initialization failed! \n");
return;
}
else
{
printf("SD card initialization successful! \n");
}
/* 挂载 */
res = f_mount(&FS, "0:", 1); //挂载
if (res != FR_OK)
{
printf("FileSystem Mounted Failed (%d)\n", result);
return;
}
res = f_getfree("0:", &fre_clust, &fs); /* 根目录 */
if (res == FR_OK)
{
TotalSpace = (uint16_t)(((fs->n_fatent - 2) * fs->csize) / 2 / 1024);
AvailableSize = (uint16_t)((fre_clust * fs->csize) / 2 / 1024);
UsedSize = TotalSpace - AvailableSize;
/* Print free space in unit of MB (assuming 512 bytes/sector) */
printf("\n%d MB total drive space.\n""%d MB available.\n""%d MB used.\n", TotalSpace, AvailableSize, UsedSize);
}
else
{
printf("Get SDCard Capacity Failed (%d)\n", result);
}
}
// 新增检查SD卡连接的函数,需要根据实际硬件情况实现
int IsSDCardConnected() {
// 这里需要根据实际硬件连接情况实现检查逻辑
// 例如检查SD卡的片选信号或者其他状态引脚
return 1; // 暂时返回1表示连接正常,实际需要修改
}
/* 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 */
InitVar();
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
DS1302_GPIO_Init(); // 新增RTC时钟GPIO初始化
//DS1302_Init(); // 新增RTC时钟初始化
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI1_Init();
MX_USART1_UART_Init();
MX_USART3_UART_Init();
MX_USART4G_UART_Init(); // 新增 4G 模块 UART 初始化
MX_FATFS_Init();
/* USER CODE BEGIN 2 */
// 开启 UART3 接收中断
HAL_UART_Receive_IT(&huart3, (uint8_t*)&uart3RecBuff, 1);
// 开启 4G 模块 UART 接收中断
HAL_UART_Receive_IT(&huart4g, (uint8_t*)&uart4gRecBuff, 1);
HAL_UART_Receive_IT(&huart1, &aRxBuffer1, 1); //enable uart
// InitOled();
// InitOledDisp();
// SystemDisplay(page);
printf(" main \n");
Get_SDCard_Capacity(); //获取使用内存可选格式化
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
uint8_t page = 0; // 新增页面变量
uint32_t page_timer = 0; // 新增页面切换计时器
printf("Entering main loop...\n"); // 添加调试信息
while (1)
{
if (bSysTick1ms)
{
bSysTick1ms = 0;
relay_timer++;
page_timer++;
if (relay_state == 0)
{
if (relay_timer >= 111000) // 111000ms = 10分钟 不工作
{
RELAY_ON();
relay_state = 1;
relay_timer = 0;
}
}
else
{
if (relay_timer >= 2000) // 2000ms = 10秒 工作
{
RELAY_OFF();
relay_state = 0;
relay_timer = 0;
}
}
if (page_timer >= 5000) // 5000ms = 5秒 切换页面
{
page = (page + 1) % 3; // 循环切换页面 0, 1, 2
page_timer = 0;
}
}
if (bSysTick10ms)
{
bSysTick10ms = 0;
ScanKeyBoard();
ProcessKeyInfo();
}
if (bSysTick100ms)
{
bSysTick100ms = 0;
}
if (bSysTick1000ms)
{
bSysTick1000ms = 0;
SystemDisplay(page); // 新增页面参数
SystemControl();
LED_TOG();
// UploadDataToOneNet(); // 新增上传数据到 OneNet 平台函数调用
}
// 调用 WritetoSD 函数
printf("Calling WritetoSD function...\n");
WritetoSD(WriteBuffer, sizeof(WriteBuffer));
HAL_Delay(500);
WriteBuffer[0] = WriteBuffer[0] + 0;
WriteBuffer[1] = WriteBuffer[1] + 1;
write_cnt++;
while (write_cnt > 10)
{
printf(" while \n");
HAL_Delay(500);
}
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* 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 CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses 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_DIV2;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != 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_2;
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 USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief USART3 Initialization Function
* @param None
* @retval None
*/
static void MX_USART3_UART_Init(void)
{
/* USER CODE BEGIN USART3_Init 0 */
/* USER CODE END USART3_Init 0 */
/* USER CODE BEGIN USART3_Init 1 */
/* USER CODE END USART3_Init 1 */
huart3.Instance = USART3;
huart3.Init.BaudRate = 9600;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART3_Init 2 */
/* USER CODE END USART3_Init 2 */
}
/**
* @brief 4G Module USART Initialization Function
* @param None
* @retval None
*/
static void MX_USART4G_UART_Init(void)
{
huart4g.Instance = USART1; // 根据实际连接修改为对应的 USART 实例
huart4g.Init.BaudRate = 115200; // 根据 4G 模块的波特率修改
huart4g.Init.WordLength = UART_WORDLENGTH_8B;
huart4g.Init.StopBits = UART_STOPBITS_1;
huart4g.Init.Parity = UART_PARITY_NONE;
huart4g.Init.Mode = UART_MODE_TX_RX;
huart4g.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart4g.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart4g) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(SD_CS_GPIO_Port, SD_CS_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : SD_CS_Pin */
GPIO_InitStruct.Pin = SD_CS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(SD_CS_GPIO_Port, &GPIO_InitStruct);
/* Configure relay control pins */
GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
RELAY_OFF();
}
/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
// 接收 UART3 数据
if (USART3 == huart->Instance)
{
// 调用土壤温湿度数据接收处理函数
// SoilReceivePacket(uart3RecBuff);
// 继续等待接收下一个字节数据
while (HAL_UART_Receive_IT(&huart3, (uint8_t*)&uart3RecBuff, 1) != HAL_OK);
}
// 接收 4G 模块数据
else if (huart4g.Instance == huart->Instance)
{
// 可添加 4G 模块数据处理代码
while (HAL_UART_Receive_IT(&huart4g, (uint8_t*)&uart4gRecBuff, 1) != HAL_OK);
}
}
/* 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\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
上面是主代码,下面是串口信息
main
CMD0 response: 0x01
CMD8 response: 0x01
CMD55+CMD41 response: 0x01
CMD55+CMD41 response: 0x00
SD card initialization successful!
SD card initialization successful!
CMD0 response: 0x01
CMD8 response: 0x01
CMD55+CMD41 response: 0x01
CMD55+CMD41 response: 0x00
SD card initialization successful!
116 MB total drive space.
116 MB available.
0 MB used.
Entering main loop
Calling WritetoSD function
代码运行之后SD卡中没有内容