SD Card with Mojibake
Answer
12/5/17 8:11 AM

Hello,

Now I am trying to store the BMA280 and Aku340 sensor data into sd card. After reading the sdcardexample and the Datalogger demo, I created the following code: 

#include "XDKAppInfo.h"
#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_SDCARD_EXAMPLE

/* own header files */
#include "SDCardExample.h"

/* system header files */
#include <stdio.h>

/* additional interface header files */
#include "BCDS_SDCard_Driver.h"
#include "BCDS_CmdProcessor.h"
#include "BSP_BoardType.h"
#include "BCDS_BSP_LED.h"
#include "ff.h"
#include "BCDS_Assert.h"
#include <FreeRTOS.h>
#include <timers.h>
#include "XdkSensorHandle.h"
#include "BCDS_BSP_Mic_AKU340.h"


/* constant definitions ***************************************************** */

/* local variables ********************************************************** */
static xTimerHandle sdCardWriteReadHandle; /**< variable to store timer handle*/
static CmdProcessor_T *AppCmdProcessor; /**< Application Command Processor Instance */
static SDCardDriver_DiskStatus_T diskInitStatus = SDCARD_NOT_INITIALIZED;
#if FAT_FILE_SYSTEM==1
static FATFS FatFileSystemObject; /* File system specific objects */
#endif
/* global variables ********************************************************* */

/* local module global variable declarations */

uint8_t writeBuffer[SINGLE_SECTOR_LEN] = "XDK ASAMPLE TEST FOR MMC"; /**< Write Buffer for SD-Card */
uint8_t readBuffer[SINGLE_SECTOR_LEN]; /**< read buffer for SD-Card */

/* inline functions ********************************************************* */

static void initAccelSensor(void){

	Retcode_T accelerometerInitReturnValue = RETCODE_FAILURE;
	Retcode_T returnBandwidthValue = RETCODE_FAILURE;
	Retcode_T returnRangeValue = RETCODE_FAILURE;

accelerometerInitReturnValue =
Accelerometer_init(xdkAccelerometers_BMA280_Handle);

if (RETCODE_OK != accelerometerInitReturnValue) {
	printf("Acce Sensor initialization Failed\n\r");
}

returnBandwidthValue =
Accelerometer_setBandwidth(xdkAccelerometers_BMA280_Handle,
ACCELEROMETER_BMA280_BANDWIDTH_500HZ);

if (RETCODE_OK != returnBandwidthValue) {
	printf("Acce Sensor bandwidth setting Failed\n\r");
}

returnRangeValue =
Accelerometer_setRange(xdkAccelerometers_BMA280_Handle,ACCELEROMETER_BMA280_RANGE_16G);

if (RETCODE_OK != returnRangeValue) {
	printf("Acce Sensor range setting Failed\n\r");
}
}

static void initAkuSensor(void)
{
	Retcode_T returnValue = RETCODE_FAILURE;
	BSP_Mic_AKU340_Connect();
	returnValue = BSP_Mic_AKU340_Enable();
	if(RETCODE_OK != returnValue)
	{
		printf("Aku Sensor Initialization Failed\n\r");
	}
}

#if FAT_FILE_SYSTEM==1
/**
 * @brief
 *      The sdCardFatFileSystemWriteRead API uses the FAT file system library calls.
 *      This API will mount and create the file system, then it will open, seek write,
 *      read and close the files. This API will compare the contents which has been
 *      written and read.
 *
 * @retval
 *      SDCARD_APP_NO_ERROR - All the file operations are success
 *
 * @retval
 *      SDCARD_APP_ERROR - one of the file operation failed
 *
 * @retval
 *      SDCARD_INIT_FAILED - disk has not been initialized
 */
static Retcode_T sdCardFatFileSystemWriteRead(void)
{
	Retcode_T returnvalue = RETCODE_FAILURE;
    Accelerometer_XyzData_T bma280 = {INT32_C(0), INT32_C(0), INT32_C(0)};
	memset(&bma280, 0, sizeof(Accelerometer_XyzData_T));
	returnvalue = Accelerometer_readXyzGValue(xdkAccelerometers_BMA280_Handle,&bma280);

	int32_t sample;
	sample = BSP_Mic_AKU340_Sense();

    FIL fileObject; /* File objects */
    int8_t ramBufferWrite[BUFFER_SIZE]; /* Temporary buffer for write file */
    int8_t ramBufferRead[BUFFER_SIZE]; /* Temporary buffer for read file */
    int8_t stringTestBuffer[50];
    uint16_t fileSize;
    UINT bytesWritten;
    UINT bytesRead;
    uint8_t fileStatus = FILE_EQUAL;

    Retcode_T result;
    FRESULT fileSystemResult;

    /* read and print BMA280 accelerometer data */
    Retcode_T returnValue = RETCODE_FAILURE;

    returnValue = Accelerometer_init(xdkAccelerometers_BMA280_Handle);

    if ( RETCODE_OK != returnValue)
    {
    	 printf("return AccelSensor Data failed\n\r");
    }

    /*Step1 - Initialization of file buffer write */
    if (RETCODE_OK == returnvalue)
    {
         snprintf( stringTestBuffer, sizeof stringTestBuffer , "BMA280 X-data: %ld" , (long int) bma280.xAxisData);
         snprintf( stringTestBuffer, sizeof stringTestBuffer , "BMA280 y-data: %ld" , (long int) bma280.yAxisData);
         snprintf( stringTestBuffer, sizeof stringTestBuffer , "BMA280 z-data: %ld" , (long int) bma280.zAxisData);
         snprintf( stringTestBuffer, sizeof stringTestBuffer , "AKU340 %lu ",(unsigned long)sample);
    }

    /* step2 - Initialization of SD card */
    if (diskInitStatus != SDCARD_DISK_INITIALIZED) /*SD-Card Disk Not Initialized */
    {
        diskInitStatus = (SDCardDriver_DiskStatus_T)SDCardDriver_DiskInitialize(DRIVE_ZERO); /* Initialize SD card */
    }

    if (SDCARD_DISK_INITIALIZED == diskInitStatus)
    {
        /*Step1 - open the file to write */
        /*  If file does not exist create it*/
        fileSystemResult = f_open(&fileObject, TEST_FILENAME,
        FA_OPEN_ALWAYS | FA_WRITE);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot create the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_OPEN_ERROR);
        }

        /*Step2 - Set the file write pointer to first location */
        fileSystemResult = f_lseek(&fileObject, f_size(&fileObject));
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot set the file write pointer */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_LSEEK_ERROR);
        }

        /*Step3 - Write a buffer to file*/
        fileSystemResult = f_write(&fileObject, ramBufferWrite, fileSize,
                &bytesWritten);
        if ((fileSystemResult != FR_OK) || (fileSize != bytesWritten))
        {
            /* Error. Cannot write the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_WRITE_ERROR);
        }

        /*Step4 - Close the file */
        fileSystemResult = f_close(&fileObject);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot close the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_CLOSE_ERROR);
        }

        /*Step5 - Open the file for read */
        fileSystemResult = f_open(&fileObject, TEST_FILENAME, FA_READ);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot create the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_OPEN_ERROR);
        }

        /*Step6 - Set the file read pointer to first location */
        fileSystemResult = f_lseek(&fileObject, (f_size(&fileObject) - fileSize));
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot set the file pointer */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_LSEEK_ERROR);
        }

        /*Step7 - Read some data from file */
        fileSystemResult = f_read(&fileObject, ramBufferRead, fileSize,
                &bytesRead);
        if ((fileSystemResult != FR_OK) || (fileSize != bytesRead))
        {
            /* Error. Cannot read the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
        }

        /*Step8 - Close the file */
        fileSystemResult = f_close(&fileObject);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot close the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_CLOSE_ERROR);
        }

        /*Step9 - Compare ramBufferWrite and ramBufferRead */
        for (uint8_t index = 0; index < fileSize; index++)
        {
            if ((ramBufferWrite[index]) != (ramBufferRead[index]))
            {
                /* Error compare buffers*/
                fileStatus = FILE_NOT_EQUAL;
            }
        }

        if (FILE_EQUAL == fileStatus)
        {
            return RETCODE_OK;
        }
        else
        {
            return RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
        }
    }
    else
    {
        result = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_INIT_FAILED);
    }
    return (result);
}
#else

/**
 * @brief
 *      The sdCardSingleBlockWriteRead API is used to write some string and read the string.
 *      then validate the written and read string.
 *
 * @param[in] sector
 *        SDC Disk sector value for read/Write process.
 *
 * @retval
 *      SDCARD_INIT_FAILED - disk has not been initialized
 */
static Retcode_T sdCardSingleBlockWriteRead(uint32_t sector)
{

    Retcode_T sdcWriteReadStatus; /* Default return value is in Error state */

    if (diskInitStatus != SDCARD_DISK_INITIALIZED)
    { /*SD-Card Disk Not Initialized */
        diskInitStatus = SDCardDriver_DiskInitialize(DRIVE_ZERO);/* Initialize SD card */
    }

    if (diskInitStatus == SDCARD_DISK_INITIALIZED)
    {
        if (SDCardDriver_DiskWrite(DRIVE_ZERO, writeBuffer, sector, SINGLE_BLOCK) == RETCODE_OK)
        {/* Write Data into SD-Card */
            if (SDCardDriver_DiskRead(DRIVE_ZERO, readBuffer, sector, SINGLE_BLOCK) == RETCODE_OK)
            {/* Read Data's from the SD-CARD */
                int8_t sdCardWriteReadCheck; /* Validate the SD_card Write/read Buffer */
                sdCardWriteReadCheck = strncmp((const char*) writeBuffer, (const char*) readBuffer, sizeof(writeBuffer));
                if (INT8_C(0) == sdCardWriteReadCheck )
                {
                    sdcWriteReadStatus = RETCODE_OK;
                }
                else
                {
                    sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
                }
            }
            else
            { /* SDC Read failure */
                printf("\r\nSD_CARD Read failure\n\r");
                sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, FILE_READ_ERROR);
            }
        }
        else
        { /* SDC Write failure */
            printf("\r\nSD_CARD Write failure\n\r");
            sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, FILE_WRITE_ERROR);
        }
    }
    else
    {
        printf("\r\nSD_CARD Initialize failure\n\r");
        sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_INIT_FAILED);
    }

    return (sdcWriteReadStatus);
}

#endif

/** @brief
 *      The function used to write and read depending on the SD card Detect status .
 *      The status can be SD card inserted or not inserted.
 *
 *  @param[in] void *pvParameters
 *      Rtos task should be defined with the type void *(as argument).
 */
static void SDCardWriteRead(void *pvParameters)
{
    Retcode_T returnVal = RETCODE_OK;
    BCDS_UNUSED(pvParameters);
#if FAT_FILE_SYSTEM==1
    FRESULT FileSystemResult = FR_OK;
#endif
    static uint8_t sdcardeject = FALSE;
    static uint8_t sdcardInsert = FALSE;

    Retcode_T sdCardWriteReadReturn = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR); /* variable for SD-Card ReadWrite status check */

    /* Get the SD Card status as inserted in XDK or not */
    if (SDCARD_INSERTED == SDCardDriver_GetDetectStatus())
    {
        sdcardInsert = TRUE;
        printf("SD card is inserted in XDK\n\r");

        returnVal = BSP_LED_Switch((uint32_t) BSP_XDK_LED_R, (uint32_t) BSP_LED_COMMAND_ON); /**< Switch ON LED1 */

        if (returnVal != RETCODE_OK)
        {
            printf("SD card is inserted LED indication failure XDK\n\r");
        }
        if (sdcardeject == TRUE)
        {
            if (RETCODE_OK == returnVal)
            {
                returnVal = SDCardDriver_DiskInitialize(DRIVE_ZERO);
                if (RETCODE_OK == returnVal)
                {
                    diskInitStatus = SDCARD_DISK_INITIALIZED;
                }
            }

#if FAT_FILE_SYSTEM==1
            if (RETCODE_OK == returnVal)
            {
                FileSystemResult = f_mount(&FatFileSystemObject, DEFAULT_LOGICAL_DRIVE, FORCE_MOUNT);
                if (FR_OK != FileSystemResult)
                {
                    printf("f_mount failed hence read and write in Sdcard using FATfs is not possible \n\r");
                    assert(0);
                    return;
                }
            }
#endif
            sdcardeject = FALSE;
        }
#if FAT_FILE_SYSTEM==1 /* Already restrict this value to be 0 or 1. */
        /* SDC Disk FAT file system Write/Read functionality */
        sdCardWriteReadReturn = sdCardFatFileSystemWriteRead();
        if (sdCardWriteReadReturn == RETCODE_OK)
        {
            printf("Write and read using FAT file system success \n\r");
        }
        else
        {
            printf("Write and read using FAT file system failed\n\r");
        }
#else /* FAT_FILE_SYSTEM == 0 */
        /* SDC Disk  single block write and read without FAT file system  */
        sdCardWriteReadReturn = sdCardSingleBlockWriteRead(SECTOR_VALUE);
        if (sdCardWriteReadReturn == RETCODE_OK)
        {
            printf("single block write and read without FAT file system success \n\r");
        }
        else
        {
            printf("single block write and read without FAT file system failed \n\r");
        }
#endif /* FAT_FILE_SYSTEM == 1 */
    }
    else
    {
        if (TRUE == sdcardInsert)
        {
            sdcardeject = TRUE;
        }
        sdcardInsert = FALSE;
        printf("\r\nSD card is not inserted in XDK\n\r");

        returnVal = BSP_LED_Switch((uint32_t) BSP_XDK_LED_R, (uint32_t) BSP_LED_COMMAND_OFF); /**< Switch OFF LED1 */
        if (returnVal != RETCODE_OK)
        {
            printf("SD card is not inserted LED indication failure XDK\n\r");
        }
    }
}

/*
 * Defines the prototype to which timer callback functions must conform.
 */
/**
 * @brief        This is a application timer callback function used to enqueue SDCardwriteread function
 *               to the command processor.
 *
 * @param[in]    pvParameters unused parameter.
 */
static void EnqueueSDCardWriteread(void *pvParameters)
{
    BCDS_UNUSED(pvParameters);

    Retcode_T retVal = CmdProcessor_enqueue(AppCmdProcessor, (CmdProcessor_Func_T) SDCardWriteRead, NULL, UINT32_C(0));
    if (RETCODE_OK != retVal)
    {
        printf("Failed to Enqueue SDCard write read to Application Command Processor \r\n");
    }
}

/**
 * @brief
 *      The SDC_sdCardWriteReadInit API creates a Write/read task and starts the task.
 */
static void Init(void)
{
    Retcode_T retVal;
#if FAT_FILE_SYSTEM==1
    FRESULT FileSystemResult = FR_OK;
    FILINFO FileInfo;
#endif
    static_assert((portTICK_RATE_MS != 0), "Tick rate MS is zero");

    retVal = SDCardDriver_Initialize();
    if (RETCODE_OK == retVal)
    {
        retVal = SDCardDriver_DiskInitialize(DRIVE_ZERO);
        if (RETCODE_OK == retVal)
        {
            diskInitStatus = SDCARD_DISK_INITIALIZED;
        }
    }

#if FAT_FILE_SYSTEM==1
    if (RETCODE_OK == retVal)
    {
        FileSystemResult = f_mount(&FatFileSystemObject, DEFAULT_LOGICAL_DRIVE, FORCE_MOUNT);
        if (FR_OK == FileSystemResult)
        {
            FileSystemResult = f_stat(TEST_FILENAME, &FileInfo);
            if (FR_OK == FileSystemResult)
            {
                FileSystemResult = f_unlink(TEST_FILENAME);
            }
            if (FR_NO_FILE == FileSystemResult)
            {
                printf("File does not exist. \n\r");
            }
        }
        else
        {
            printf("f_mount failed hence read and write in Sdcard using FATfs is not possible \n\r");
            assert(0);
            return;
        }
    }
#endif

    if (RETCODE_OK == retVal)
    {
        /* create timer task to write and read data form SDCard one second automatically*/
        sdCardWriteReadHandle = xTimerCreate(
                (const char * const ) "SDCardWriteRead",
                pdMS_TO_TICKS(WRITEREAD_DELAY), TIMER_AUTORELOAD_ON, NULL, EnqueueSDCardWriteread);

        if ((NULL != sdCardWriteReadHandle)) /* Timer was not created */
        {
            /* start the created timer */
            if (pdTRUE != xTimerStart(sdCardWriteReadHandle,
                    WRITEREAD_BLOCK_TIME))
            {
                printf("Failed to initialize because of SDCard/Command Processor/Timer Create fail \n");
                assert(false);
            }
        }
    }
}

/**
 * @brief This is a template function where the user can write his custom application.
 *
 */
void appInitSystem(void * CmdProcessorHandle, uint32_t param2)
{
 if (CmdProcessorHandle == NULL)
 {
 printf("Command processor handle is null \n\r");
 assert(false);
 }
 BCDS_UNUSED(param2);

    uint32_t timerBlockTime = UINT32_MAX;
    uint32_t oneSecondDelay = UINT32_C(5000);
    uint32_t timerAutoReloadOn = pdTRUE;

    xTimerHandle SensorHandle = NULL;
    SensorHandle = xTimerCreate((const char *) "sdCardFatFileSystemWriteRead",
    oneSecondDelay,timerAutoReloadOn, NULL, sdCardFatFileSystemWriteRead);

 initAccelSensor();
 initAkuSensor();
 Init();
 sdCardFatFileSystemWriteRead();
}


/**
 * @brief
 *      The SDC_sdCardWriteReadDeInit API Delete the Write/read task.
 *
 * @retval
 *      SDCARD_APP_NO_ERROR  Task was created successfully.
 */
Retcode_T DeInit(void)
{

    Retcode_T DeInitStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_DE_INIT_FAILED); /* Default return value is in Error Deinit state */

    if (pdFAIL != xTimerStop(sdCardWriteReadHandle,
            WRITEREAD_BLOCK_TIME))
    {
        DeInitStatus = RETCODE_OK;
    }

    return (DeInitStatus);

But what I got in sd card is a txt file containing random characters, not sensor data.

May I ask for some help upon this?

Regards

Zhefei

 

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/5/17 5:21 PM as a reply to Zhefei Xiao.

Hello Zhefei,

Thank you for opening a new thread for your SD card issue.

I analyzed your code and made some findings. The reason why you get random characters in the .txt file is that the function f_write() writes the content of the buffer ramBufferWrite to the SD card instead of the content of stringTestBuffer.

Since the ramBufferWrite is initialized but never written to, it will write whatever initial value it had to the SD card. In most cases, the initial value is random.

Furthermore, I noticed that you adapted the SdCardExample to your use case. Since you currently have a lot of overhead in your application, I would recommend to keep implementing your application as before in the XdkApplicationTemplate and only copy the code snippets for initializing the SD card module and writing to the SD card from the SdCardExample into it. This would allow you to more easily analyse your code, which helps finding errors like the one you opened this thread for.

Please let me know if that was helpful and feel free to ask if you have further questions.

Kind regards,
Franjo

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/5/17 6:38 PM as a reply to Franjo Stjepandic.

Hi Franjo!

Thank you for the reply! After reading the code again, I saw that it is ramBufferWrite, which was being written to the SD card.

So what I changed in my code is: I change the ramBufferWrite in the f_write() to stringTestBuffer.

After this, the content in the TXT file is still not the data but a repeating Japanese charactor.

Regards

Zhefei

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/6/17 4:45 PM as a reply to Zhefei Xiao.

Hello Zhefei,

regarding the repeating Japanese Character, this is the character for Yen, and is not a Japanese-specific character, since its part of the ASCII characters (it represents the decimal value 190 of a byte). This is most likely printed because of other issues.

These issues in your application that have to be addressed, are mostly within sdCardFatFileSystemWriteRead().

First of all, the f_write() call uses the variable fileSize, which is declared, but never initialized. Again, this will result in an arbitrary value for this, which is especially troubling, since that variable is used as the number of bytes that should be written to the file. I would recommend initializing this variable as 0, along with the following change on lines:

snprintf(stringTestBuffer, sizeof(stringTestBuffer),
        "BMA280 X-data: %ld", (long int) bma280.xAxisData);
snprintf(stringTestBuffer, sizeof stringTestBuffer ,
        "BMA280 y-data: %ld", (long int) bma280.yAxisData);
snprintf(stringTestBuffer, sizeof stringTestBuffer ,
        "BMA280 z-data: %ld", (long int) bma280.zAxisData);
snprintf(stringTestBuffer, sizeof stringTestBuffer, "AKU340 %lu ",
        (unsigned long) sample);

You don't use the result of snprintf(), which is the actually written length, to determine the next starting point for the buffer. Currently, the next snprintf() always overwrites the previous snprintf(), since they all start at index 0 of stringTestBuffer.

I would recommend modifying each line as follows (using the x-Axis as an example):

fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
                "BMA280 X-data: %ld", (long int) bma280.xAxisData);

This way, the total number of bytes written into stringTestBuffer will be stored into fileSize, which will then be reused as the number of bytes to write in f_write()

The final issue is the fact that the stringTesBuffer is too small. The three axes of the accelerometer alone will exceed the limit of 50. I recommend using 100 instead.

After making these changes, the result in the TEST_XDK.txt file is

BMA280 X-data: 5BMA280 y-data: 27BMA280 z-data: 1027AKU340 3

So I can confirm that this will work.

Please tell me if this was helpful, and do not hesitate to ask further questions.

Kind regards,
Franjo

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/6/17 6:22 PM as a reply to Franjo Stjepandic.

Dear Franjo,

Following your guidance, I changed my code, it is now:


/* module includes ********************************************************** */
#include "XDKAppInfo.h"
#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_SDCARD_EXAMPLE

/* own header files */
#include "SDCardExample.h"

/* system header files */
#include <stdio.h>

/* additional interface header files */
#include "BCDS_SDCard_Driver.h"
#include "BCDS_CmdProcessor.h"
#include "BSP_BoardType.h"
#include "BCDS_BSP_LED.h"
#include "ff.h"
#include "BCDS_Assert.h"
#include <FreeRTOS.h>
#include <timers.h>
#include "XdkSensorHandle.h"
#include "BCDS_BSP_Mic_AKU340.h"

/* constant definitions ***************************************************** */

/* local variables ********************************************************** */
static xTimerHandle sdCardWriteReadHandle; /**< variable to store timer handle*/
static CmdProcessor_T *AppCmdProcessor; /**< Application Command Processor Instance */
static SDCardDriver_DiskStatus_T diskInitStatus = SDCARD_NOT_INITIALIZED;
#if FAT_FILE_SYSTEM==1
static FATFS FatFileSystemObject; /* File system specific objects */
#endif
/* global variables ********************************************************* */

/* local module global variable declarations */

uint8_t writeBuffer[SINGLE_SECTOR_LEN] = "XDK ASAMPLE TEST FOR MMC"; /**< Write Buffer for SD-Card */
uint8_t readBuffer[SINGLE_SECTOR_LEN]; /**< read buffer for SD-Card */

static void initAccelSensor(void){

	Retcode_T accelerometerInitReturnValue = RETCODE_FAILURE;
	Retcode_T returnBandwidthValue = RETCODE_FAILURE;
	Retcode_T returnRangeValue = RETCODE_FAILURE;

accelerometerInitReturnValue =
Accelerometer_init(xdkAccelerometers_BMA280_Handle);

if (RETCODE_OK != accelerometerInitReturnValue) {
	printf("Acce Sensor initialization Failed\n\r");
}

returnBandwidthValue =
Accelerometer_setBandwidth(xdkAccelerometers_BMA280_Handle,
ACCELEROMETER_BMA280_BANDWIDTH_500HZ);

if (RETCODE_OK != returnBandwidthValue) {
	printf("Acce Sensor bandwidth setting Failed\n\r");
}

returnRangeValue =
Accelerometer_setRange(xdkAccelerometers_BMA280_Handle,ACCELEROMETER_BMA280_RANGE_16G);

if (RETCODE_OK != returnRangeValue) {
	printf("Acce Sensor range setting Failed\n\r");
}
}

static void initAkuSensor(void)
{
	Retcode_T returnValue = RETCODE_FAILURE;
	BSP_Mic_AKU340_Connect();
	returnValue = BSP_Mic_AKU340_Enable();
	if(RETCODE_OK != returnValue)
	{
		printf("Aku Sensor Initialization Failed\n\r");
	}
}

#if FAT_FILE_SYSTEM==1
/**
 * @brief
 *      The sdCardFatFileSystemWriteRead API uses the FAT file system library calls.
 *      This API will mount and create the file system, then it will open, seek write,
 *      read and close the files. This API will compare the contents which has been
 *      written and read.
 *
 * @retval
 *      SDCARD_APP_NO_ERROR - All the file operations are success
 *
 * @retval
 *      SDCARD_APP_ERROR - one of the file operation failed
 *
 * @retval
 *      SDCARD_INIT_FAILED - disk has not been initialized
 */
static Retcode_T sdCardFatFileSystemWriteRead(void)
{
	Retcode_T returnvalue = RETCODE_FAILURE;
	Accelerometer_XyzData_T bma280 = {INT32_C(0), INT32_C(0), INT32_C(0)};
	memset(&bma280, 0, sizeof(Accelerometer_XyzData_T));
	returnvalue = Accelerometer_readXyzGValue(xdkAccelerometers_BMA280_Handle,&bma280);

	int32_t sample;
	sample = BSP_Mic_AKU340_Sense();

	Retcode_T returnValue = RETCODE_FAILURE;
    returnValue = Accelerometer_init(xdkAccelerometers_BMA280_Handle);
    if ( RETCODE_OK != returnValue)
	    {
	    	 printf("return AccelSensor Data failed\n\r");
	    }

    FIL fileObject; /* File objects */
    int8_t ramBufferWrite[BUFFER_SIZE]; /* Temporary buffer for write file */
    int8_t ramBufferRead[BUFFER_SIZE]; /* Temporary buffer for read file */
    int8_t stringTestBuffer[100];
    uint16_t fileSize;
    UINT bytesWritten;
    UINT bytesRead;
    uint8_t fileStatus = FILE_EQUAL;

    Retcode_T result;
    FRESULT fileSystemResult;

    /*Step1 - Initialization of file buffer write */
    fileSize = 0;
    if (RETCODE_OK == returnvalue)
        {
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	                "BMA280 X-data: %ld", (long int) bma280.xAxisData);
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	        	                "BMA280 Y-data: %ld", (long int) bma280.yAxisData);
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	        	                "BMA280 Z-data: %ld", (long int) bma280.zAxisData);
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	        	                "AKU340 : %lu", (long int) sample);
        }

    /* step2 - Initialization of SD card */
    if (diskInitStatus != SDCARD_DISK_INITIALIZED) /*SD-Card Disk Not Initialized */
    {
        diskInitStatus = (SDCardDriver_DiskStatus_T)SDCardDriver_DiskInitialize(DRIVE_ZERO); /* Initialize SD card */
    }

    if (SDCARD_DISK_INITIALIZED == diskInitStatus)
    {
        /*Step1 - open the file to write */
        /*  If file does not exist create it*/
        fileSystemResult = f_open(&fileObject, TEST_FILENAME,
        FA_OPEN_ALWAYS | FA_WRITE);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot create the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_OPEN_ERROR);
        }

        /*Step2 - Set the file write pointer to first location */
        fileSystemResult = f_lseek(&fileObject, f_size(&fileObject));
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot set the file write pointer */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_LSEEK_ERROR);
        }

        /*Step3 - Write a buffer to file*/
        fileSystemResult = f_write(&fileObject, ramBufferWrite, fileSize,
                &bytesWritten);
        if ((fileSystemResult != FR_OK) || (fileSize != bytesWritten))
        {
            /* Error. Cannot write the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_WRITE_ERROR);
        }

        /*Step4 - Close the file */
        fileSystemResult = f_close(&fileObject);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot close the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_CLOSE_ERROR);
        }

        /*Step5 - Open the file for read */
        fileSystemResult = f_open(&fileObject, TEST_FILENAME, FA_READ);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot create the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_OPEN_ERROR);
        }

        /*Step6 - Set the file read pointer to first location */
        fileSystemResult = f_lseek(&fileObject, (f_size(&fileObject) - fileSize));
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot set the file pointer */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_LSEEK_ERROR);
        }

        /*Step7 - Read some data from file */
        fileSystemResult = f_read(&fileObject, ramBufferRead, fileSize,
                &bytesRead);
        if ((fileSystemResult != FR_OK) || (fileSize != bytesRead))
        {
            /* Error. Cannot read the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
        }

        /*Step8 - Close the file */
        fileSystemResult = f_close(&fileObject);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot close the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_CLOSE_ERROR);
        }

        /*Step9 - Compare ramBufferWrite and ramBufferRead */
        for (uint8_t index = 0; index < fileSize; index++)
        {
            if ((ramBufferWrite[index]) != (ramBufferRead[index]))
            {
                /* Error compare buffers*/
                fileStatus = FILE_NOT_EQUAL;
            }
        }

        if (FILE_EQUAL == fileStatus)
        {
            return RETCODE_OK;
        }
        else
        {
            return RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
        }
    }
    else
    {
        result = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_INIT_FAILED);
    }
    return (result);
}
#else

/**
 * @brief
 *      The sdCardSingleBlockWriteRead API is used to write some string and read the string.
 *      then validate the written and read string.
 *
 * @param[in] sector
 *        SDC Disk sector value for read/Write process.
 *
 * @retval
 *      SDCARD_INIT_FAILED - disk has not been initialized
 */
static Retcode_T sdCardSingleBlockWriteRead(uint32_t sector)
{

    Retcode_T sdcWriteReadStatus; /* Default return value is in Error state */

    if (diskInitStatus != SDCARD_DISK_INITIALIZED)
    { /*SD-Card Disk Not Initialized */
        diskInitStatus = SDCardDriver_DiskInitialize(DRIVE_ZERO);/* Initialize SD card */
    }

    if (diskInitStatus == SDCARD_DISK_INITIALIZED)
    {
        if (SDCardDriver_DiskWrite(DRIVE_ZERO, writeBuffer, sector, SINGLE_BLOCK) == RETCODE_OK)
        {/* Write Data into SD-Card */
            if (SDCardDriver_DiskRead(DRIVE_ZERO, readBuffer, sector, SINGLE_BLOCK) == RETCODE_OK)
            {/* Read Data's from the SD-CARD */
                int8_t sdCardWriteReadCheck; /* Validate the SD_card Write/read Buffer */
                sdCardWriteReadCheck = strncmp((const char*) writeBuffer, (const char*) readBuffer, sizeof(writeBuffer));
                if (INT8_C(0) == sdCardWriteReadCheck )
                {
                    sdcWriteReadStatus = RETCODE_OK;
                }
                else
                {
                    sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
                }
            }
            else
            { /* SDC Read failure */
                printf("\r\nSD_CARD Read failure\n\r");
                sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, FILE_READ_ERROR);
            }
        }
        else
        { /* SDC Write failure */
            printf("\r\nSD_CARD Write failure\n\r");
            sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, FILE_WRITE_ERROR);
        }
    }
    else
    {
        printf("\r\nSD_CARD Initialize failure\n\r");
        sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_INIT_FAILED);
    }

    return (sdcWriteReadStatus);
}

#endif

/** @brief
 *      The function used to write and read depending on the SD card Detect status .
 *      The status can be SD card inserted or not inserted.
 *
 *  @param[in] void *pvParameters
 *      Rtos task should be defined with the type void *(as argument).
 */
static void SDCardWriteRead(void *pvParameters)
{
    Retcode_T returnVal = RETCODE_OK;
    BCDS_UNUSED(pvParameters);
#if FAT_FILE_SYSTEM==1
    FRESULT FileSystemResult = FR_OK;
#endif
    static uint8_t sdcardeject = FALSE;
    static uint8_t sdcardInsert = FALSE;

    Retcode_T sdCardWriteReadReturn = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR); /* variable for SD-Card ReadWrite status check */

    /* Get the SD Card status as inserted in XDK or not */
    if (SDCARD_INSERTED == SDCardDriver_GetDetectStatus())
    {
        sdcardInsert = TRUE;
        printf("SD card is inserted in XDK\n\r");

        returnVal = BSP_LED_Switch((uint32_t) BSP_XDK_LED_R, (uint32_t) BSP_LED_COMMAND_ON); /**< Switch ON LED1 */

        if (returnVal != RETCODE_OK)
        {
            printf("SD card is inserted LED indication failure XDK\n\r");
        }
        if (sdcardeject == TRUE)
        {
            if (RETCODE_OK == returnVal)
            {
                returnVal = SDCardDriver_DiskInitialize(DRIVE_ZERO);
                if (RETCODE_OK == returnVal)
                {
                    diskInitStatus = SDCARD_DISK_INITIALIZED;
                }
            }

#if FAT_FILE_SYSTEM==1
            if (RETCODE_OK == returnVal)
            {
                FileSystemResult = f_mount(&FatFileSystemObject, DEFAULT_LOGICAL_DRIVE, FORCE_MOUNT);
                if (FR_OK != FileSystemResult)
                {
                    printf("f_mount failed hence read and write in Sdcard using FATfs is not possible \n\r");
                    assert(0);
                    return;
                }
            }
#endif
            sdcardeject = FALSE;
        }
#if FAT_FILE_SYSTEM==1 /* Already restrict this value to be 0 or 1. */
        /* SDC Disk FAT file system Write/Read functionality */
        sdCardWriteReadReturn = sdCardFatFileSystemWriteRead();
        if (sdCardWriteReadReturn == RETCODE_OK)
        {
            printf("Write and read using FAT file system success \n\r");
        }
        else
        {
            printf("Write and read using FAT file system failed\n\r");
        }
#else /* FAT_FILE_SYSTEM == 0 */
        /* SDC Disk  single block write and read without FAT file system  */
        sdCardWriteReadReturn = sdCardSingleBlockWriteRead(SECTOR_VALUE);
        if (sdCardWriteReadReturn == RETCODE_OK)
        {
            printf("single block write and read without FAT file system success \n\r");
        }
        else
        {
            printf("single block write and read without FAT file system failed \n\r");
        }
#endif /* FAT_FILE_SYSTEM == 1 */
    }
    else
    {
        if (TRUE == sdcardInsert)
        {
            sdcardeject = TRUE;
        }
        sdcardInsert = FALSE;
        printf("\r\nSD card is not inserted in XDK\n\r");

        returnVal = BSP_LED_Switch((uint32_t) BSP_XDK_LED_R, (uint32_t) BSP_LED_COMMAND_OFF); /**< Switch OFF LED1 */
        if (returnVal != RETCODE_OK)
        {
            printf("SD card is not inserted LED indication failure XDK\n\r");
        }
    }
}

/*
 * Defines the prototype to which timer callback functions must conform.
 */
/**
 * @brief        This is a application timer callback function used to enqueue SDCardwriteread function
 *               to the command processor.
 *
 * @param[in]    pvParameters unused parameter.
 */
static void EnqueueSDCardWriteread(void *pvParameters)
{
    BCDS_UNUSED(pvParameters);

    Retcode_T retVal = CmdProcessor_enqueue(AppCmdProcessor, (CmdProcessor_Func_T) SDCardWriteRead, NULL, UINT32_C(0));
    if (RETCODE_OK != retVal)
    {
        printf("Failed to Enqueue SDCard write read to Application Command Processor \r\n");
    }
}

/**
 * @brief
 *      The SDC_sdCardWriteReadInit API creates a Write/read task and starts the task.
 */
static void Init(void)
{
    Retcode_T retVal;
#if FAT_FILE_SYSTEM==1
    FRESULT FileSystemResult = FR_OK;
    FILINFO FileInfo;
#endif
    static_assert((portTICK_RATE_MS != 0), "Tick rate MS is zero");

    retVal = SDCardDriver_Initialize();
    if (RETCODE_OK == retVal)
    {
        retVal = SDCardDriver_DiskInitialize(DRIVE_ZERO);
        if (RETCODE_OK == retVal)
        {
            diskInitStatus = SDCARD_DISK_INITIALIZED;
        }
    }

#if FAT_FILE_SYSTEM==1
    if (RETCODE_OK == retVal)
    {
        FileSystemResult = f_mount(&FatFileSystemObject, DEFAULT_LOGICAL_DRIVE, FORCE_MOUNT);
        if (FR_OK == FileSystemResult)
        {
            FileSystemResult = f_stat(TEST_FILENAME, &FileInfo);
            if (FR_OK == FileSystemResult)
            {
                FileSystemResult = f_unlink(TEST_FILENAME);
            }
            if (FR_NO_FILE == FileSystemResult)
            {
                printf("File does not exist. \n\r");
            }
        }
        else
        {
            printf("f_mount failed hence read and write in Sdcard using FATfs is not possible \n\r");
            assert(0);
            return;
        }
    }
#endif

    if (RETCODE_OK == retVal)
    {
        /* create timer task to write and read data form SDCard one second automatically*/
        sdCardWriteReadHandle = xTimerCreate(
                (const char * const ) "SDCardWriteRead",
                pdMS_TO_TICKS(WRITEREAD_DELAY), TIMER_AUTORELOAD_ON, NULL, EnqueueSDCardWriteread);

        if ((NULL != sdCardWriteReadHandle)) /* Timer was not created */
        {
            /* start the created timer */
            if (pdTRUE != xTimerStart(sdCardWriteReadHandle,
                    WRITEREAD_BLOCK_TIME))
            {
                printf("Failed to initialize because of SDCard/Command Processor/Timer Create fail \n");
                assert(false);
            }
        }
    }
}

/**
 * @brief This is a template function where the user can write his custom application.
 *
 */
void appInitSystem(void * CmdProcessorHandle, uint32_t param2)
{
	if (CmdProcessorHandle == NULL)
	 {
	 printf("Command processor handle is null \n\r");
	 assert(false);
	 }
	 BCDS_UNUSED(param2);

	    uint32_t timerBlockTime = UINT32_MAX;
	    uint32_t oneSecondDelay = UINT32_C(5000);
	    uint32_t timerAutoReloadOn = pdTRUE;

	    xTimerHandle SensorHandle = NULL;
	    SensorHandle = xTimerCreate((const char *) "sdCardFatFileSystemWriteRead",
	    oneSecondDelay,timerAutoReloadOn, NULL, sdCardFatFileSystemWriteRead);

	 initAccelSensor();
	 initAkuSensor();
	 Init();
	 sdCardFatFileSystemWriteRead();
}

/**
 * @brief
 *      The SDC_sdCardWriteReadDeInit API Delete the Write/read task.
 *
 * @retval
 *      SDCARD_APP_NO_ERROR  Task was created successfully.
 */
Retcode_T DeInit(void)
{

    Retcode_T DeInitStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_DE_INIT_FAILED); /* Default return value is in Error Deinit state */

    if (pdFAIL != xTimerStop(sdCardWriteReadHandle,
            WRITEREAD_BLOCK_TIME))
    {
        DeInitStatus = RETCODE_OK;
    }

    return (DeInitStatus);

}

/**@} */
/** ************************************************************************* */

But after flashing to the devise, this showed up:

XDK DEVICE 1: Failed to Enqueue SDCard write read to Application Command Processor .

I did not meet this with my previous code and since the code was successfully built, I think it is not from the code.

Could you tell me how to solve the problem?

Regards

ZHefei

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/7/17 5:33 PM as a reply to Zhefei Xiao.

Hello Zhefei,

first of all, does the correct output appear in your text file now?

Secondly, the message appears because of some leftover fragments from using the SdCardExample. Inside the function Init(), you will find the following code:

sdCardWriteReadHandle = xTimerCreate(
                (const char * const ) "SDCardWriteRead",
                pdMS_TO_TICKS(WRITEREAD_DELAY), TIMER_AUTORELOAD_ON, NULL, EnqueueSDCardWriteread);

This is a timer you don't need, since you create your own timer for writing inside the function appInitSystem(). To be more precise, the code I mentioned uses the function

EnqueueSDCardWriteread(), and if you take a look into the function, you will find that it makes the following call:

 

Retcode_T retVal = CmdProcessor_enqueue(AppCmdProcessor, (CmdProcessor_Func_T) SDCardWriteRead, NULL, UINT32_C(0));


This basically calls SDCardWriteRead(), which in return calls the function sdCardFatFileSystemWriteRead().

I would recommend to either remove the creation of the timer, or utilize the timer that is already given, by adding the following code to your appInitSystem():
 

AppCmdProcessor = (CmdProcessor_T *)CmdProcessorHandle;


You probably removed this exact line of code from the original example, which is why that message is printed in the first place.

Please tell me if this was helpful, and do not hesitate to ask further questions.

Kind regards,
Franjo

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/8/17 8:59 AM as a reply to Franjo Stjepandic.

Hi Franjo,

my outcoming is still the Japanese character.

Actually, the code I attached at the beginning did not have 

AppCmdProcessor = (CmdProcessor_T *)CmdProcessorHandle;

and the two timers also existed, but the error

XDK DEVICE 1: Failed to Enqueue SDCard write read to Application Command Processor .

did not show up.

I assume the code you confirmed that would work was an adjusted version of the code I attached on 5th Dec. 

I think it does not work with me if the code on 6th Dec is the proper adjusted version.

Furthermore, following what you said, I deleted the  superfluous timer and even commentated the EnqueueSDCardWriteread(), I still got the same error.


/* module includes ********************************************************** */
#include "XDKAppInfo.h"
#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_SDCARD_EXAMPLE

/* own header files */
#include "SDCardExample.h"

/* system header files */
#include <stdio.h>

/* additional interface header files */
#include "BCDS_SDCard_Driver.h"
#include "BCDS_CmdProcessor.h"
#include "BSP_BoardType.h"
#include "BCDS_BSP_LED.h"
#include "ff.h"
#include "BCDS_Assert.h"
#include <FreeRTOS.h>
#include <timers.h>
#include "XdkSensorHandle.h"
#include "BCDS_BSP_Mic_AKU340.h"

/* constant definitions ***************************************************** */

/* local variables ********************************************************** */
static xTimerHandle sdCardWriteReadHandle; /**< variable to store timer handle*/
static CmdProcessor_T *AppCmdProcessor; /**< Application Command Processor Instance */
static SDCardDriver_DiskStatus_T diskInitStatus = SDCARD_NOT_INITIALIZED;
#if FAT_FILE_SYSTEM==1
static FATFS FatFileSystemObject; /* File system specific objects */
#endif
/* global variables ********************************************************* */

/* local module global variable declarations */

uint8_t writeBuffer[SINGLE_SECTOR_LEN] = "XDK ASAMPLE TEST FOR MMC"; /**< Write Buffer for SD-Card */
uint8_t readBuffer[SINGLE_SECTOR_LEN]; /**< read buffer for SD-Card */

static void initAccelSensor(void){

	Retcode_T accelerometerInitReturnValue = RETCODE_FAILURE;
	Retcode_T returnBandwidthValue = RETCODE_FAILURE;
	Retcode_T returnRangeValue = RETCODE_FAILURE;

accelerometerInitReturnValue =
Accelerometer_init(xdkAccelerometers_BMA280_Handle);

if (RETCODE_OK != accelerometerInitReturnValue) {
	printf("Acce Sensor initialization Failed\n\r");
}

returnBandwidthValue =
Accelerometer_setBandwidth(xdkAccelerometers_BMA280_Handle,
ACCELEROMETER_BMA280_BANDWIDTH_500HZ);

if (RETCODE_OK != returnBandwidthValue) {
	printf("Acce Sensor bandwidth setting Failed\n\r");
}

returnRangeValue =
Accelerometer_setRange(xdkAccelerometers_BMA280_Handle,ACCELEROMETER_BMA280_RANGE_16G);

if (RETCODE_OK != returnRangeValue) {
	printf("Acce Sensor range setting Failed\n\r");
}
}

static void initAkuSensor(void)
{
	Retcode_T returnValue = RETCODE_FAILURE;
	BSP_Mic_AKU340_Connect();
	returnValue = BSP_Mic_AKU340_Enable();
	if(RETCODE_OK != returnValue)
	{
		printf("Aku Sensor Initialization Failed\n\r");
	}
}

#if FAT_FILE_SYSTEM==1
/**
 * @brief
 *      The sdCardFatFileSystemWriteRead API uses the FAT file system library calls.
 *      This API will mount and create the file system, then it will open, seek write,
 *      read and close the files. This API will compare the contents which has been
 *      written and read.
 *
 * @retval
 *      SDCARD_APP_NO_ERROR - All the file operations are success
 *
 * @retval
 *      SDCARD_APP_ERROR - one of the file operation failed
 *
 * @retval
 *      SDCARD_INIT_FAILED - disk has not been initialized
 */
static Retcode_T sdCardFatFileSystemWriteRead(void)
{
	Retcode_T returnvalue = RETCODE_FAILURE;
	Accelerometer_XyzData_T bma280 = {INT32_C(0), INT32_C(0), INT32_C(0)};
	memset(&bma280, 0, sizeof(Accelerometer_XyzData_T));
	returnvalue = Accelerometer_readXyzGValue(xdkAccelerometers_BMA280_Handle,&bma280);

	int32_t sample;
	sample = BSP_Mic_AKU340_Sense();

	Retcode_T returnValue = RETCODE_FAILURE;
    returnValue = Accelerometer_init(xdkAccelerometers_BMA280_Handle);
    if ( RETCODE_OK != returnValue)
	    {
	    	 printf("return AccelSensor Data failed\n\r");
	    }

    FIL fileObject; /* File objects */
    int8_t ramBufferWrite[BUFFER_SIZE]; /* Temporary buffer for write file */
    int8_t ramBufferRead[BUFFER_SIZE]; /* Temporary buffer for read file */
    int8_t stringTestBuffer[100];
    uint16_t fileSize;
    UINT bytesWritten;
    UINT bytesRead;
    uint8_t fileStatus = FILE_EQUAL;

    Retcode_T result;
    FRESULT fileSystemResult;

    /*Step1 - Initialization of file buffer write */
    fileSize = 0;
    if (RETCODE_OK == returnvalue)
        {
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	                "BMA280 X-data: %ld", (long int) bma280.xAxisData);
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	        	    "BMA280 Y-data: %ld", (long int) bma280.yAxisData);
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	        	    "BMA280 Z-data: %ld", (long int) bma280.zAxisData);
        	fileSize+= snprintf(stringTestBuffer + fileSize, sizeof(stringTestBuffer) - fileSize,
        	        	    "AKU340 : %lu", (long int) sample);
        }

    /* step2 - Initialization of SD card */
    if (diskInitStatus != SDCARD_DISK_INITIALIZED) /*SD-Card Disk Not Initialized */
    {
        diskInitStatus = (SDCardDriver_DiskStatus_T)SDCardDriver_DiskInitialize(DRIVE_ZERO); /* Initialize SD card */
    }

    if (SDCARD_DISK_INITIALIZED == diskInitStatus)
    {
        /*Step1 - open the file to write */
        /*  If file does not exist create it*/
        fileSystemResult = f_open(&fileObject, TEST_FILENAME,
        FA_OPEN_ALWAYS | FA_WRITE);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot create the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_OPEN_ERROR);
        }

        /*Step2 - Set the file write pointer to first location */
        fileSystemResult = f_lseek(&fileObject, f_size(&fileObject));
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot set the file write pointer */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_LSEEK_ERROR);
        }

        /*Step3 - Write a buffer to file*/
        fileSystemResult = f_write(&fileObject, stringTestBuffer, fileSize,
                &bytesWritten);
        if ((fileSystemResult != FR_OK) || (fileSize != bytesWritten))
        {
            /* Error. Cannot write the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_WRITE_ERROR);
        }

        /*Step4 - Close the file */
        fileSystemResult = f_close(&fileObject);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot close the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_CLOSE_ERROR);
        }

        /*Step5 - Open the file for read */
        fileSystemResult = f_open(&fileObject, TEST_FILENAME, FA_READ);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot create the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_OPEN_ERROR);
        }

        /*Step6 - Set the file read pointer to first location */
        fileSystemResult = f_lseek(&fileObject, (f_size(&fileObject) - fileSize));
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot set the file pointer */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_LSEEK_ERROR);
        }

        /*Step7 - Read some data from file */
        fileSystemResult = f_read(&fileObject, ramBufferRead, fileSize,
                &bytesRead);
        if ((fileSystemResult != FR_OK) || (fileSize != bytesRead))
        {
            /* Error. Cannot read the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
        }

        /*Step8 - Close the file */
        fileSystemResult = f_close(&fileObject);
        if (fileSystemResult != FR_OK)
        {
            /* Error. Cannot close the file */
            return RETCODE(RETCODE_SEVERITY_ERROR, FILE_CLOSE_ERROR);
        }

        /*Step9 - Compare ramBufferWrite and ramBufferRead */
        for (uint8_t index = 0; index < fileSize; index++)
        {
            if ((ramBufferWrite[index]) != (ramBufferRead[index]))
            {
                /* Error compare buffers*/
                fileStatus = FILE_NOT_EQUAL;
            }
        }

        if (FILE_EQUAL == fileStatus)
        {
            return RETCODE_OK;
        }
        else
        {
            return RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
        }
    }
    else
    {
        result = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_INIT_FAILED);
    }
    return (result);
}
#else

/**
 * @brief
 *      The sdCardSingleBlockWriteRead API is used to write some string and read the string.
 *      then validate the written and read string.
 *
 * @param[in] sector
 *        SDC Disk sector value for read/Write process.
 *
 * @retval
 *      SDCARD_INIT_FAILED - disk has not been initialized
 */
static Retcode_T sdCardSingleBlockWriteRead(uint32_t sector)
{

    Retcode_T sdcWriteReadStatus; /* Default return value is in Error state */

    if (diskInitStatus != SDCARD_DISK_INITIALIZED)
    { /*SD-Card Disk Not Initialized */
        diskInitStatus = SDCardDriver_DiskInitialize(DRIVE_ZERO);/* Initialize SD card */
    }

    if (diskInitStatus == SDCARD_DISK_INITIALIZED)
    {
        if (SDCardDriver_DiskWrite(DRIVE_ZERO, writeBuffer, sector, SINGLE_BLOCK) == RETCODE_OK)
        {/* Write Data into SD-Card */
            if (SDCardDriver_DiskRead(DRIVE_ZERO, readBuffer, sector, SINGLE_BLOCK) == RETCODE_OK)
            {/* Read Data's from the SD-CARD */
                int8_t sdCardWriteReadCheck; /* Validate the SD_card Write/read Buffer */
                sdCardWriteReadCheck = strncmp((const char*) writeBuffer, (const char*) readBuffer, sizeof(writeBuffer));
                if (INT8_C(0) == sdCardWriteReadCheck )
                {
                    sdcWriteReadStatus = RETCODE_OK;
                }
                else
                {
                    sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
                }
            }
            else
            { /* SDC Read failure */
                printf("\r\nSD_CARD Read failure\n\r");
                sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, FILE_READ_ERROR);
            }
        }
        else
        { /* SDC Write failure */
            printf("\r\nSD_CARD Write failure\n\r");
            sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, FILE_WRITE_ERROR);
        }
    }
    else
    {
        printf("\r\nSD_CARD Initialize failure\n\r");
        sdcWriteReadStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_INIT_FAILED);
    }

    return (sdcWriteReadStatus);
}

#endif

/** @brief
 *      The function used to write and read depending on the SD card Detect status .
 *      The status can be SD card inserted or not inserted.
 *
 *  @param[in] void *pvParameters
 *      Rtos task should be defined with the type void *(as argument).
 */
static void SDCardWriteRead(void *pvParameters)
{
    Retcode_T returnVal = RETCODE_OK;
    BCDS_UNUSED(pvParameters);
#if FAT_FILE_SYSTEM==1
    FRESULT FileSystemResult = FR_OK;
#endif
    static uint8_t sdcardeject = FALSE;
    static uint8_t sdcardInsert = FALSE;

    Retcode_T sdCardWriteReadReturn = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR); /* variable for SD-Card ReadWrite status check */

    /* Get the SD Card status as inserted in XDK or not */
    if (SDCARD_INSERTED == SDCardDriver_GetDetectStatus())
    {
        sdcardInsert = TRUE;
        printf("SD card is inserted in XDK\n\r");

        returnVal = BSP_LED_Switch((uint32_t) BSP_XDK_LED_R, (uint32_t) BSP_LED_COMMAND_ON); /**< Switch ON LED1 */

        if (returnVal != RETCODE_OK)
        {
            printf("SD card is inserted LED indication failure XDK\n\r");
        }
        if (sdcardeject == TRUE)
        {
            if (RETCODE_OK == returnVal)
            {
                returnVal = SDCardDriver_DiskInitialize(DRIVE_ZERO);
                if (RETCODE_OK == returnVal)
                {
                    diskInitStatus = SDCARD_DISK_INITIALIZED;
                }
            }

#if FAT_FILE_SYSTEM==1
            if (RETCODE_OK == returnVal)
            {
                FileSystemResult = f_mount(&FatFileSystemObject, DEFAULT_LOGICAL_DRIVE, FORCE_MOUNT);
                if (FR_OK != FileSystemResult)
                {
                    printf("f_mount failed hence read and write in Sdcard using FATfs is not possible \n\r");
                    assert(0);
                    return;
                }
            }
#endif
            sdcardeject = FALSE;
        }
#if FAT_FILE_SYSTEM==1 /* Already restrict this value to be 0 or 1. */
        /* SDC Disk FAT file system Write/Read functionality */
        sdCardWriteReadReturn = sdCardFatFileSystemWriteRead();
        if (sdCardWriteReadReturn == RETCODE_OK)
        {
            printf("Write and read using FAT file system success \n\r");
        }
        else
        {
            printf("Write and read using FAT file system failed\n\r");
        }
#else /* FAT_FILE_SYSTEM == 0 */
        /* SDC Disk  single block write and read without FAT file system  */
        sdCardWriteReadReturn = sdCardSingleBlockWriteRead(SECTOR_VALUE);
        if (sdCardWriteReadReturn == RETCODE_OK)
        {
            printf("single block write and read without FAT file system success \n\r");
        }
        else
        {
            printf("single block write and read without FAT file system failed \n\r");
        }
#endif /* FAT_FILE_SYSTEM == 1 */
    }
    else
    {
        if (TRUE == sdcardInsert)
        {
            sdcardeject = TRUE;
        }
        sdcardInsert = FALSE;
        printf("\r\nSD card is not inserted in XDK\n\r");

        returnVal = BSP_LED_Switch((uint32_t) BSP_XDK_LED_R, (uint32_t) BSP_LED_COMMAND_OFF); /**< Switch OFF LED1 */
        if (returnVal != RETCODE_OK)
        {
            printf("SD card is not inserted LED indication failure XDK\n\r");
        }
    }
}

/*
 * Defines the prototype to which timer callback functions must conform.
 */
/**
 * @brief        This is a application timer callback function used to enqueue SDCardwriteread function
 *               to the command processor.
 *
 * @param[in]    pvParameters unused parameter.
 */
/*static void EnqueueSDCardWriteread(void *pvParameters)
{
    BCDS_UNUSED(pvParameters);

    Retcode_T retVal = CmdProcessor_enqueue(AppCmdProcessor, (CmdProcessor_Func_T) SDCardWriteRead, NULL, UINT32_C(0));
    if (RETCODE_OK != retVal)
    {
        printf("Failed to Enqueue SDCard write read to Application Command Processor \r\n");
    }
}*/
/**
 * @brief
 *      The SDC_sdCardWriteReadInit API creates a Write/read task and starts the task.
 */
static void Init(void)
{
    Retcode_T retVal;
#if FAT_FILE_SYSTEM==1
    FRESULT FileSystemResult = FR_OK;
    FILINFO FileInfo;
#endif
    static_assert((portTICK_RATE_MS != 0), "Tick rate MS is zero");

    retVal = SDCardDriver_Initialize();
    if (RETCODE_OK == retVal)
    {
        retVal = SDCardDriver_DiskInitialize(DRIVE_ZERO);
        if (RETCODE_OK == retVal)
        {
            diskInitStatus = SDCARD_DISK_INITIALIZED;
        }
    }

#if FAT_FILE_SYSTEM==1
    if (RETCODE_OK == retVal)
    {
        FileSystemResult = f_mount(&FatFileSystemObject, DEFAULT_LOGICAL_DRIVE, FORCE_MOUNT);
        if (FR_OK == FileSystemResult)
        {
            FileSystemResult = f_stat(TEST_FILENAME, &FileInfo);
            if (FR_OK == FileSystemResult)
            {
                FileSystemResult = f_unlink(TEST_FILENAME);
            }
            if (FR_NO_FILE == FileSystemResult)
            {
                printf("File does not exist. \n\r");
            }
        }
        else
        {
            printf("f_mount failed hence read and write in Sdcard using FATfs is not possible \n\r");
            assert(0);
            return;
        }
    }
#endif
}

/**
 * @brief This is a template function where the user can write his custom application.
 *
 */
void appInitSystem(void * CmdProcessorHandle, uint32_t param2)
{
	if (CmdProcessorHandle == NULL)
	 {
	 printf("Command processor handle is null \n\r");
	 assert(false);
	 }
	 /*AppCmdProcessor = (CmdProcessor_T *)CmdProcessorHandle;*/
	 BCDS_UNUSED(param2);

	   uint32_t timerBlockTime = UINT32_MAX;
	   uint32_t oneSecondDelay = UINT32_C(5000);
	   uint32_t timerAutoReloadOn = pdTRUE;

	   xTimerHandle SensorHandle = NULL;
	   SensorHandle = xTimerCreate((const char *) "sdCardFatFileSystemWriteRead",
	   oneSecondDelay,timerAutoReloadOn, NULL, sdCardFatFileSystemWriteRead);



	 initAccelSensor();
	 initAkuSensor();
	 Init();
	 sdCardFatFileSystemWriteRead();
}

/**
 * @brief
 *      The SDC_sdCardWriteReadDeInit API Delete the Write/read task.
 *
 * @retval
 *      SDCARD_APP_NO_ERROR  Task was created successfully.
 */
Retcode_T DeInit(void)
{

    Retcode_T DeInitStatus = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_DE_INIT_FAILED); /* Default return value is in Error Deinit state */

    if (pdFAIL != xTimerStop(sdCardWriteReadHandle,
            WRITEREAD_BLOCK_TIME))
    {
        DeInitStatus = RETCODE_OK;
    }

    return (DeInitStatus);

}

/**@} */
/** ************************************************************************* */

Is it some hardware problems or sth about my workbench version?

Regards

Zhefei

 

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/11/17 4:52 PM as a reply to Zhefei Xiao.

Hello Zhefei,

I don't assume that there is something wrong with the XDK hardware or your XDK-Workbench version. I actually tested the code you posted on the 8th of december (the most recent one), and I can confirm that it works. As an example, it produced the following output:

BMA280 X-data: 52BMA280 Y-data: -1017BMA280 Z-data: -31AKU340 : 8

As a first possible reason for why the application still produces the same output, I would like to know if you saved the implementation file, before you rebuilt and flashed the application onto the XDK. I know it may sound trivial, but there were cases like this before, where users forgot to save the files. The Workbench won't recognize the changes in the editor, until they are saved.

Another possibility would be that the editor you use to view the file on your PC actually misinterprets the bytes on the file. If the editor interprets every byte as a single character, it should correctly interpret the characters. If the editor actually expectes characters with a length of two (or more) bytes, then that would most likely be the reason for the Japanese characters.

For this, I would like you to try out the unmodified SDCardExample, to see if the correct output is produced, or if the original Example also produces Japanese characters for you.

Additionally, I would advise you to change how you setup the timer for reading and writing. Currently, the function sdCardFatFileSystemWriteRead() has the following signature:

static Retcode_T sdCardFatFileSystemWriteRead(void)

I would recommend that you use another function, such as the following:

static void writeReadTimerCallback(xTimerHandle timer) {
  sdCardFatFileSystemWriteRead();
}

And use that function for the creation of the timer.

Please tell me if this was helpful, and do not hesitate to ask further questions.

Kind regards,
Franjo

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/12/17 10:25 AM as a reply to Franjo Stjepandic.

Hi Franjo,

unfortunately, the code still does not work on my computer.

I want to make sure I did the right thing:

I copy the code I submitted on 8th Dec and paste the code to SDCardExample.c and leave other files in the SDCardExample application unchanged. And then build and flash.

After all these, I still get the

XDK DEVICE 1: Failed to Enqueue SDCard write read to Application Command Processor .

even with commentated EnqueueSDCardWriteread(). And the output is always the ウ.

But the output of the original SDCardExample is correct.

Furthermore, I am quite sure that I save the file everytime before rebuilding.

Regards

Zhefei

 

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/12/17 11:24 AM as a reply to Zhefei Xiao.

Hi Franjo!

Great news!

I reinstalled workbench, and I have what I wanted now! I cannot finish the application I need without your help!

Really thank you for all the help from you!

Thank you!

Regards

Zhefei

0 (0 Votes)
RE: SD Card with Mojibake
Answer
12/12/17 5:14 PM as a reply to Zhefei Xiao.

Hello Zhefei,

I am glad that you were able to solve the issue, and thank you for your kind words. I am always glad to help.

If there is anything else I can do for you, feel free to ask a question in a new thread.

Kind regards,
Franjo

0 (0 Votes)