/**
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2025-05-08
 *
 * @attention
 *
 *  Copyright (C) 2025 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

/* Includes ***************************************************************/
#include "main.h"

/* Private includes *******************************************************/
#include "apm32f4xx_device_cfg.h"
#include "log.h"

/* Private macro **********************************************************/
#define FLASH_USER_ADDR         ((uint32_t)0x08040000U)

/* Private typedef ********************************************************/

/* Private variables ******************************************************/
static const char* tag = "main";

/* Private function prototypes ********************************************/

/* External variables *****************************************************/

/* External functions *****************************************************/

/**
 * @brief   Main program
 *
 * @param   None
 *
 * @retval  None
 */
int main(void)
{
    uint32_t sectorError = 0U;
    
    FLASH_EraseInitTypeDef Erase_InitStruct = {0};

    /* Device configuration */
    DAL_DeviceConfig();

    /* Unlock the Flash */
    DAL_FLASH_Unlock();

    /* Read address data */
    LOGI(tag, "Before erase sector, data of 0x08040000 address = 0x%08X\r\n", *(volatile uint32_t*)FLASH_USER_ADDR);

    /* Erase sector */
    Erase_InitStruct.Sector         = FLASH_SECTOR_6;
    Erase_InitStruct.NbSectors      = 1U;
    Erase_InitStruct.TypeErase      = FLASH_TYPEERASE_SECTORS;
    Erase_InitStruct.VoltageRange   = FLASH_VOLTAGE_RANGE_3;
    if(DAL_FLASHEx_Erase(&Erase_InitStruct, &sectorError) != DAL_OK)
    {
        Error_Handler();
    }

    /* Read address data */
    LOGI(tag, "After erase sector, data of 0x08040000 address = 0x%08X\r\n", *(volatile uint32_t*)FLASH_USER_ADDR);
    
    if (DAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, FLASH_USER_ADDR, 0x12345678U) != DAL_OK)
    {
        Error_Handler();
    }
    
    /* Read data again */
    LOGI(tag, "After program word, data of 0x08040000 address = 0x%08X\r\n", *(volatile uint32_t*)FLASH_USER_ADDR);

    /* Lock the Flash to */
    DAL_FLASH_Lock();

    /* Infinite loop */
    while (1)
    {
    }
}
