OSPI code Writing failed

I am trying to store the log in the OSPI but some times it shows the error 
OSPI Write failed! Error code: 40002
I have a array of log if the ram i need to store the elements of the log in my OSPI but some times i am facing the above issue.I am not facing the issue in the begging of the thread i am able to store six data continuously while writing the 7 th data i am getting this error


The OSPI code is 

#include "access_log.h"

#include "ospi.h"

#include "SEGGER_RTT/SEGGER_RTT.h"

#include "ospi_b_ep.h"

#include "common_utils.h"

#include "ospi_b_commands.h"

// Define OSPI sectors

#define OSPI_B_SECTOR_SIZE (*** * 1024) // 64KB sectors

#define OSPI_B_TOTAL_SECTORS *** // Adjust based on your OSPI chip

#define OSPI_B_SECTOR_LAST (OSPI_B_TOTAL_SECTORS - 2) // Reserve last sector for state

#define OSPI_B_STATE_SECTOR (OSPI_B_TOTAL_SECTORS - 1) // Last sector for storing state

// Structure to track OSPI storage state

typedef struct {

uint32_t next_write_address; // Next available address for writing

uint32_t total_entries; // Total number of entries stored

uint32_t current_sector; // Current sector being written to

} OspiStorageState;

// Global storage state

static OspiStorageState g_storage_state = {

.next_write_address = OSPI_B_APP_ADDRESS(OSPI_B_SECTOR_FIRST),

.total_entries = 0,

.current_sector = OSPI_B_SECTOR_FIRST

};

// Function to load storage state from a reserved area in OSPI

static fsp_err_t load_storage_state(void)

{

fsp_err_t err = FSP_SUCCESS;

// Use direct memory access to read state

uint8_t *state_address = (uint8_t *)OSPI_B_APP_ADDRESS(OSPI_B_STATE_SECTOR);

memcpy(&g_storage_state, state_address, sizeof(OspiStorageState));

// Validate loaded state

if (g_storage_state.current_sector >= OSPI_B_SECTOR_LAST ||

g_storage_state.current_sector < OSPI_B_SECTOR_FIRST)

{

// Reset to default if invalid

g_storage_state.next_write_address = OSPI_B_APP_ADDRESS(OSPI_B_SECTOR_FIRST);

g_storage_state.total_entries = 0;

g_storage_state.current_sector = OSPI_B_SECTOR_FIRST;

}

return err;

}

void handle_error(fsp_err_t err, const char *err_str)

{

if(FSP_SUCCESS != err)

{

/* Print the error */

APP_PRINT(err_str);

/* Close opened OSPI module*/

if(0U != g_ospi_b_ctrl.open)

{

if(FSP_SUCCESS != R_OSPI_B_Close(&g_ospi_b_ctrl))

{

APP_ERR_PRINT("R_OSPI_B_Close FAILED\r\n");

}

}

/* Close opened GPT module*/

if(0U != g_timer_ctrl.open)

{

if(FSP_SUCCESS != R_GPT_Close(&g_timer_ctrl))

{

APP_ERR_PRINT("R_GPT_Close FAILED\r\n");

}

}

APP_ERR_TRAP(err);

}

}

fsp_err_t ospi_read_stored_log(void)

{

fsp_err_t err = FSP_SUCCESS;

uint8_t *p_ospi_address = OSPI_B_APP_ADDRESS(OSPI_B_SECTOR_FIRST);

uint32_t execute_time = RESET_VALUE;

AccessLogEntry read_entry;

uint32_t valid_entries = 0;

/* Start timer for read operation */

err = timer_start_measure();

handle_error(err, "timer_start_measure FAILED\r\n");

/* Read until we find an empty entry or reach sector size */

for (uint32_t i = 0; i < OSPI_B_SECTOR_SIZE_256K / sizeof(AccessLogEntry); i++)

{

uint8_t *current_address = p_ospi_address + (i * sizeof(AccessLogEntry));

/* Read entry from OSPI */

memcpy(&read_entry, current_address, sizeof(AccessLogEntry));

/* Check if entry is empty or invalid */

if (read_entry.timestamp == 0xFFFFFFFF || read_entry.timestamp == 0)

{

continue;

}

/* Convert timestamp to time format */

uint8_t hours = read_entry.timestamp / 3600;

uint8_t minutes = (read_entry.timestamp % 3600) / 60;

uint8_t seconds = read_entry.timestamp % 60;

/* Print entry details with address at the end */

APP_PRINT("[%02u:%02u:%02u] | %d | %u | %d | %s | %s | 0x%08x\r\n",

hours, minutes, seconds,

read_entry.timestamp,

read_entry.rfid,

read_entry.door_no,

read_entry.action ? read_entry.action : "RFID Not Found",

read_entry.processed ? "Yes" : "No",

(uint32_t)current_address);

valid_entries++;

}

/* Get and print read time */

err = timer_get_measure(&execute_time);

handle_error(err, "timer_get_measure FAILED\r\n");

return err;

}

static void print_last_entries(uint8_t *p_ospi_address, uint32_t total_entries)

{

AccessLogEntry read_entry;

uint32_t start_index;

/* Calculate starting point for last 20 entries */

if (total_entries <= 20) {

start_index = 0;

} else {

start_index = total_entries - 20;

}

APP_PRINT("\r\n=== LAST 20 OSPI ACCESS LOG ENTRIES ===\r\n");

APP_PRINT("Showing entries %lu to %lu of %lu total entries\r\n",

start_index + 1, total_entries, total_entries);

APP_PRINT("Timestamp | RFID | Door | Action | Processed\r\n");

APP_PRINT("---------------------------------------------\r\n");

/* Read and print last 20 valid entries */

for (uint32_t i = start_index; i < total_entries; i++)

{

/* Read entry from OSPI */

memcpy(&read_entry,

p_ospi_address + (i * sizeof(AccessLogEntry)),

sizeof(AccessLogEntry));

/* Convert timestamp to time format */

uint8_t hours = read_entry.timestamp / 3600;

uint8_t minutes = (read_entry.timestamp % 3600) / 60;

uint8_t seconds = read_entry.timestamp % 60;

/* Print entry details */

APP_PRINT("[%02u:%02u:%02u] %u | %d | %s | %s\r\n",

hours, minutes, seconds,

read_entry.rfid,

read_entry.door_no,

read_entry.action,

read_entry.processed ? "Yes" : "No");

}

APP_PRINT("=======================================\r\n");

}

fsp_err_t ospi_erase_all_data(void)

{

fsp_err_t err = FSP_SUCCESS;

uint32_t execute_time = RESET_VALUE;

uint8_t *p_ospi_address = OSPI_B_APP_ADDRESS(OSPI_B_SECTOR_FIRST);

APP_PRINT("\r\n=== ERASING ALL OSPI DATA ===\r\n");

/* Start timer */

err = timer_start_measure();

handle_error(err, "timer_start_measure FAILED\r\n");

/* Erase sector */

err = ospi_b_erase_operation(p_ospi_address, &execute_time);

handle_error(err, "ospi_b_erase_operation FAILED\r\n");

/* Wait for erase operation to complete */

err = ospi_b_wait_operation(OSPI_B_TIME_ERASE_256K);

handle_error(err, "ospi_b_wait_operation FAILED\r\n");

APP_PRINT("OSPI erase completed in %d nanoseconds\r\n", execute_time);

APP_PRINT("============================\r\n");

return err;

}

void ospi_entry(void *pvParameters)

{

fsp_err_t err = FSP_SUCCESS;

uint8_t *p_ospi_address = NULL;

uint32_t execute_time = RESET_VALUE;

static uint16_t last_stored_index = 0;

static uint32_t ospi_write_position = 0;

AccessLogEntry temp_entry;

/* Initialize OSPI */

err = timer_init();

handle_error(err, "timer_init FAILED\r\n");

err = ospi_b_init();

handle_error(err, "ospi_b_init FAILED\r\n");

/* Set OSPI to SPI mode for reliable operation */

err = ospi_b_set_protocol_to_spi();

handle_error(err, "ospi_b_set_protocol_to_spi FAILED\r\n");

/* Set base address for storing logs */

p_ospi_address = OSPI_B_APP_ADDRESS(OSPI_B_SECTOR_FIRST);

/* Find the last written position in OSPI */

bool found_end = false;

uint32_t max_search = OSPI_B_SECTOR_SIZE_256K / sizeof(AccessLogEntry);

APP_PRINT("\r\nInitializing OSPI Storage Thread...\r\n");

APP_PRINT("Searching for last written position in OSPI...\r\n");

/* Search for last written position by looking for first empty entry */

for (uint32_t i = 0; i < max_search; i++)

{

/* Read entry from current position */

memcpy(&temp_entry,

p_ospi_address + (i * sizeof(AccessLogEntry)),

sizeof(AccessLogEntry));

/* Check if entry is empty (unwritten OSPI will have 0xFF) */

if (temp_entry.timestamp == 0xFFFFFFFF)

{

ospi_write_position = i;

found_end = true;

break;

}

}

if (!found_end) {

ospi_write_position = 0; // Start from beginning if OSPI is full

APP_PRINT("OSPI is full, will start overwriting from beginning\r\n");

}

APP_PRINT("OSPI write position initialized at index: %lu\r\n", ospi_write_position);

/* Main thread loop */

while(1)

{

/* Check if mutex is available */

UBaseType_t mutex_count = uxSemaphoreGetCount(globalAccessLogMutex);

if (mutex_count > 0) /* Mutex is free */

{

/* Check if there are new entries to store */

if (last_stored_index < globalLogIndex)

{

/* Calculate number of entries to store */

uint16_t entries_to_store = globalLogIndex - last_stored_index;

uint32_t data_size = entries_to_store * sizeof(AccessLogEntry);

/* Check if we need to wrap around */

if ((ospi_write_position + entries_to_store) * sizeof(AccessLogEntry) >= OSPI_B_SECTOR_SIZE_256K)

{

APP_PRINT("\r\nOSPI storage reached end, wrapping to beginning\r\n");

ospi_write_position = 0;

}

/* Write new entries to OSPI */

err = R_OSPI_B_Write(&g_ospi_b_ctrl,

(uint8_t *)&globalAccessLog[last_stored_index],

p_ospi_address + (ospi_write_position * sizeof(AccessLogEntry)),

data_size);

if (err != FSP_SUCCESS) {

APP_PRINT("OSPI Write failed! Error code: %d\r\n", err);

continue;

}

/* Wait for write operation to complete */

err = ospi_b_wait_operation(OSPI_B_TIME_WRITE);

if (err != FSP_SUCCESS) {

APP_PRINT("OSPI Write operation timeout! Error code: %d\r\n", err);

continue;

}

/* Verify written data */

bool verification_error = false;

for (uint16_t i = 0; i < entries_to_store; i++)

{

AccessLogEntry verify_entry;

memcpy(&verify_entry,

p_ospi_address + ((ospi_write_position + i) * sizeof(AccessLogEntry)),

sizeof(AccessLogEntry));

if (memcmp(&verify_entry, &globalAccessLog[last_stored_index + i],

sizeof(AccessLogEntry)) != 0)

{

verification_error = true;

APP_PRINT("Data verification failed at entry %d\r\n",

ospi_write_position + i);

break;

}

}

if (!verification_error)

{

/* Update positions */

ospi_write_position += entries_to_store;

last_stored_index = globalLogIndex;

APP_PRINT("\r\n=== NEW ENTRIES STORED IN OSPI ===\r\n");

APP_PRINT("Stored %d new entries\r\n", entries_to_store);

/* Display last 20 entries */

APP_PRINT("\r\n=== LAST 20 ENTRIES ===\r\n");

APP_PRINT("Timestamp | RFID | Door | Action | Processed\r\n");

APP_PRINT("---------------------------------------------\r\n");

uint32_t start_idx = (ospi_write_position > 20) ?

(ospi_write_position - 20) : 0;

for (uint32_t i = start_idx; i < ospi_write_position; i++)

{

AccessLogEntry display_entry;

memcpy(&display_entry,

p_ospi_address + (i * sizeof(AccessLogEntry)),

sizeof(AccessLogEntry));

uint8_t hours = display_entry.timestamp / 3600;

uint8_t minutes = (display_entry.timestamp % 3600) / 60;

uint8_t seconds = display_entry.timestamp % 60;

APP_PRINT("[%02u:%02u:%02u] %u | %d | %s | %s\r\n",

hours, minutes, seconds,

display_entry.rfid,

display_entry.door_no,

display_entry.action,

display_entry.processed ? "Yes" : "No");

}

/* Print storage status */

float usage_percent = ((float)ospi_write_position * sizeof(AccessLogEntry)) /

OSPI_B_SECTOR_SIZE_256K * 100;

APP_PRINT("\r\n=== OSPI STORAGE STATUS ===\r\n");

APP_PRINT("Total Entries: %lu\r\n", ospi_write_position);

APP_PRINT("Storage Usage: %.1f%%\r\n", usage_percent);

APP_PRINT("Next Write Position: %lu\r\n", ospi_write_position);

APP_PRINT("============================\r\n");

}

else

{

APP_PRINT("Failed to verify written data. Retrying...\r\n");

}

}

}

/* Delay before next check */

vTaskDelay(pdMS_TO_TICKS(1000));

}

}