Storage in SD-Card
Risposta
14/06/19 11.42

Hello everybody,

I still have problems storing the sensor data in the SD card. I tried to get SDCardExapmle and StreamSensorDataOverUsb but it just does not work. Can you help me please ? Below is my code from the Workbench.

regards

Michael

 

/*
* Licensee agrees that the example code provided to Licensee has been developed and released by Bosch solely as an example to be used as a potential reference for Licensee�s application development. 
* Fitness and suitability of the example code for any use within Licensee�s applications need to be verified by Licensee on its own authority by taking appropriate state of the art actions and measures (e.g. by means of quality assurance measures).
* Licensee shall be responsible for conducting the development of its applications as well as integration of parts of the example code into such applications, taking into account the state of the art of technology and any statutory regulations and provisions applicable for such applications. Compliance with the functional system requirements and testing there of (including validation of information/data security aspects and functional safety) and release shall be solely incumbent upon Licensee. 
* For the avoidance of doubt, Licensee shall be responsible and fully liable for the applications and any distribution of such applications into the market.
* 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are 
* met:
* 
*     (1) Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer. 
* 
*     (2) Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in
*     the documentation and/or other materials provided with the
*     distribution.  
*     
*     (3)The name of the author may not be used to
*     endorse or promote products derived from this software without
*     specific prior written permission.
* 
*  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 
*  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
*  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
*  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
*  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
*  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
*  POSSIBILITY OF SUCH DAMAGE.
*/
/*----------------------------------------------------------------------------*/

/**
 * @ingroup APPS_LIST
 *
 * @defgroup SD_CARD_EXAMPLE SdCardExample
 * @{
 *
 * @brief Demo application shows how to write a file to the SD card and later read back the file.
 *
 * @details The example will read the presence of an SD Card in the SD Card slot and turn on the Red LED if one is present. The device will then
 * create and write to the text file TEST_XDK.TXT the text. This content is created by SD card Read/Write
 * functionality using FAT32 file system. The will continue to write the SD Card again and
 * again. 
 *
 * @file
 **/

/* module includes ********************************************************** */

/* own header files */
#include "XdkAppInfo.h"
#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_APP_CONTROLLER

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

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

/* additional interface header files */
#include "XDK_Storage.h"
#include "XDK_LED.h"
#include "BCDS_SDCard_Driver.h"
#include "BCDS_CmdProcessor.h"
#include "BSP_BoardType.h"
#include "XDK_Sensor.h"
#include "BCDS_Assert.h"
#include <FreeRTOS.h>
#include <timers.h>
/* constant definitions ***************************************************** */
/* Ram buffers
 * BUFFERSIZE should be between 512 and 1024, depending on available ram on efm32
 */
#define BUFFER_SIZE                 UINT16_C(512)
#define SINGLE_BLOCK                UINT8_C(1)      /**< SD- Card Single block write or read */
#define DRIVE_ZERO                  UINT8_C(0)      /**< SD Card Drive 0 location */
#define SECTOR_VALUE                UINT8_C(6)      /**< SDC Disk sector value */
#define SINGLE_SECTOR_LEN           UINT32_C(512)   /**< Single sector size in SDcard */

/* constant definitions ***************************************************** */
#define APP_TEMPERATURE_OFFSET_CORRECTION   (-3459)

/* local variables ********************************************************** */
/* local module global variable declarations */
Storage_Setup_T StorageSetupInfo =
        {
                .SDCard = true,
                .WiFiFileSystem = false
        };/**< Storage setup parameters */

static CmdProcessor_T * AppCmdProcessor;/**< Handle to store the main Command processor handle to be used by run-time event driven threads */

static xTaskHandle AppControllerHandle = NULL;/**< OS thread handle for Application controller to be used by run-time blocking threads */

static xTimerHandle sensorHandle = NULL;

static Sensor_Setup_T SensorSetup =
        {
                .CmdProcessorHandle = NULL,
                .Enable =
                        {
                                .Accel = true,
                                .Mag = true,
                                .Gyro = true,
                                .Humidity = true,
                                .Temp = true,
                                .Pressure = true,
                                .Light = true,
                                .Noise = false,
                        },
                .Config =
                        {
                                .Accel =
                                        {
                                                .Type = SENSOR_ACCEL_BMA280,
                                                .IsRawData = true,//false,
                                                .IsInteruptEnabled = true,//false,

                                        },
                                .Gyro =
                                        {
                                                .Type = SENSOR_GYRO_BMG160,
                                                .IsRawData = true,//false,
                                        },
                                .Mag =
                                        {
                                                .IsRawData = true,//false,
                                        },
                                .Light =
                                        {
                                                .IsInteruptEnabled = true,//false,

                                        },
                                .Temp =
                                        {
                                                .OffsetCorrection = APP_TEMPERATURE_OFFSET_CORRECTION,
                                        },
                        },
        };/**< Sensor setup parameters */

/* global variables ********************************************************* */

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

static GetSensorData()
{
    //BCDS_UNUSED(pvParameters);

    //Retcode_T retcode = RETCODE_OK;
    Sensor_Value_T sensorValue;

    memset(&sensorValue, 0x00, sizeof(sensorValue));

        //retcode = Sensor_GetData(&sensorValue);
/*        if (RETCODE_OK == retcode)
        {*/

                printf("Accelerometer Converted data :\n\rx =%ld mg\n\ry =%ld mg\n\rz =%ld mg\r\n",
                        (long int) sensorValue.Accel.X,
                        (long int) sensorValue.Accel.Y,
                        (long int) sensorValue.Accel.Z);

                printf("Accelerometer Raw data :\n\rx =%ld \n\ry =%ld\n\rz =%ld\r\n",
                        (long int) sensorValue.Accel.X,
                        (long int) sensorValue.Accel.Y,
                        (long int) sensorValue.Accel.Z);

                printf("BME280 Environmental Conversion Data for Humidity:\n\rh =%ld %%rh\r\n",
                        (long int) sensorValue.RH);

                printf("BME280 Environmental Conversion Data for Pressure :\n\rp =%ld Pa\r\n",
                        (long int) sensorValue.Pressure);

                printf("BME280 Environmental Conversion Data for temperature :\n\rt =%ld mDeg\r\n",
                        (long int) sensorValue.Temp);

                printf("Magnetometer Converted data :\n\rx =%ld microTesla\n\ry =%ld microTesla\n\rz =%ld microTesla\n\rr =%ld\r\n",
                        (long int) sensorValue.Mag.X,
                        (long int) sensorValue.Mag.Y,
                        (long int) sensorValue.Mag.Z,
                        (long int) sensorValue.Mag.R);

                printf("Magnetometer Raw data :\n\rx =%ld\n\ry =%ld\n\rz =%ld \n\rr =%ld\r\n",
                        (long int) sensorValue.Mag.X,
                        (long int) sensorValue.Mag.Y,
                        (long int) sensorValue.Mag.Z,
                        (long int) sensorValue.Mag.R);

                printf("Gyro Converted Data :\n\rx =%ld mDeg\n\ry =%ld mDeg\n\rz =%ld mDeg\r\n",
                        (long int) sensorValue.Gyro.X,
                        (long int) sensorValue.Gyro.Y,
                        (long int) sensorValue.Gyro.Z);

                printf("Gyro Raw Data :\n\rx =%ld \n\ry =%ld \n\rz =%ld \r\n",
                        (long int) sensorValue.Gyro.X,
                        (long int) sensorValue.Gyro.Y,
                        (long int) sensorValue.Gyro.Z);

                printf("Light sensor data obtained in millilux :%d \n\r", (unsigned int) sensorValue.Light);

                printf("Noise Sensor RMS Voltage :\r\nVrms = %f \r\n", sensorValue.Noise);
                int int_p = sensorValue.Pressure;
                printf("int_p");
                printf("%ld",(long int) sensorValue.Pressure);
                return "%ld",(long int) sensorValue.Pressure;
      /*      }

        if (RETCODE_OK != retcode)
        {
            Retcode_RaiseError(retcode);
        }*/
}

/* local functions ********************************************************** */

static inputsys()
{
	//i=i+1;
	//char *test[50] = (char)i;
	//char test[] = "test";
	//printf("\n count =%i ascii=%s ",i,test);
	//printf("%i\n",i);
	//printf(test);
	char buffer[50];
	int place = 10;
	sprintf(buffer, place);
	return buffer;
}


#if FAT_FILE_SYSTEM==1
/**
 * @brief
 *      ThIS API uses the FAT file system library calls.
 *      This API will write and read files and it will compare the contents which has been
 *      written and read.
 *
 * @retval
 *      RETCODE_OK - All the file operations are success
 *
 * @retval
 *      #SDCARD_APP_ERROR - when there is a mismatch in read and write buffer
 *
 * @retval
 *      #FILE_WRITE_ERROR - when file system write is failed
 *
 * @retval
 *      #FILE_READ_ERROR - when file system read is failed
 */
static Retcode_T AppControllerFatFileSystemWriteRead(void)
{
    uint8_t ramBufferWrite[BUFFER_SIZE]; /* Temporary buffer for write file */
    uint8_t ramBufferRead[BUFFER_SIZE]; /* Temporary buffer for read file */
	//int test;
	//[]="test";
    //test = inputsys();
    //test =
	Retcode_T test = GetSensorData();
	
    printf("test");
    //printf(test[1]);

    int8_t stringTestBuffer[strlen(test)-1];
	strcpy(stringTestBuffer,test);//DATA_TO_WRITE_IN_SDCARD;
    uint16_t fileSize = strlen(test);//DATA_TO_WRITE_IN_SDCARD);
    static uint32_t writeOffset = 0, readOffset = 0;
    Retcode_T retcode = RETCODE_OK;
    for (uint32_t index = 0; index < fileSize; index++)
    {
        ramBufferWrite[index] = stringTestBuffer[index];
    }
    Storage_Read_T readCredentials =
            {
                    .FileName = TEST_FILENAME,
                    .ReadBuffer = ramBufferRead,
                    .BytesToRead = fileSize,
                    .ActualBytesRead = 0UL,
                    .Offset = 0UL,
            };
    Storage_Write_T writeCredentials =
            {
                    .FileName = TEST_FILENAME,
                    .WriteBuffer = ramBufferWrite,
                    .BytesToWrite = fileSize,
                    .ActualBytesWritten = 0UL,
                    .Offset = 0UL,
            };
    writeCredentials.Offset = writeOffset;
    retcode = Storage_Write(STORAGE_MEDIUM_SD_CARD, &writeCredentials);
    if (RETCODE_OK == retcode)
    {
        if (writeCredentials.BytesToWrite == writeCredentials.ActualBytesWritten)
        {
            writeOffset = writeOffset + writeCredentials.BytesToWrite;
            readCredentials.Offset = readOffset;
            retcode = Storage_Read(STORAGE_MEDIUM_SD_CARD, &readCredentials);
        }
        else
        {
            retcode = RETCODE(RETCODE_SEVERITY_ERROR, FILE_WRITE_ERROR);
        }
    }
    if (RETCODE_OK == retcode)
    {
        if (readCredentials.BytesToRead == readCredentials.ActualBytesRead)

        {
            readOffset = writeOffset - readCredentials.BytesToRead;
        }
        else
        {
            retcode = RETCODE(RETCODE_SEVERITY_ERROR, FILE_READ_ERROR);
        }
    }
    if (RETCODE_OK == retcode)
    {
        for (uint8_t index = 0; index < fileSize; index++)
        {
            if ((ramBufferWrite[index]) != (ramBufferRead[index]))
            {
                /* Error compare buffers*/
                retcode = RETCODE(RETCODE_SEVERITY_ERROR, SDCARD_APP_ERROR);
            }
        }
    }
    return (retcode);
}
#else
/**
 * @brief
 *      This 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_APP_ERROR - when there is a mismatch in read and write buffer
 *
 * @retval
 *      #FILE_WRITE_ERROR - when file system write is failed
 *
 * @retval
 *      #FILE_READ_ERROR - when file system read is failed
 */
static Retcode_T AppControllerSingleBlockWriteRead(uint32_t sector)
{
    Retcode_T sdcWriteReadStatus; /* Default return value is in Error state */
    /**< Write Buffer for SD-Card */
    uint8_t writeBuffer[SINGLE_SECTOR_LEN] =DATA_TO_WRITE_IN_SDCARD;
    /**< read buffer for SD-Card */
    uint8_t readBuffer[SINGLE_SECTOR_LEN];

    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);
    }

    return (sdcWriteReadStatus);
}
#endif
/**
 * @brief Responsible for controlling the SD card example flow
 *
 * - Check whether the storage medium (SD Card)is available or not
 * - if FAT_FILE_SYSTEM==1 then will write and read files and it will compare the contents which has been
 *   written and read.
 * - if FAT_FILE_SYSTEM==0 then it will write some string and read the string.
 *   then validate the written and read string.
 *
 * @param[in] pvParameters
 * Unused
 */
static void AppControllerFire(void* pvParameters)
{
    BCDS_UNUSED(pvParameters);
    Retcode_T retcode = RETCODE_OK, ledRetcode = RETCODE_OK;
    Sensor_Value_T sensorValue;
    memset(&sensorValue, 0x00, sizeof(sensorValue));
    bool sdcardEject = false, status = false, sdcardInsert = false;
    while (1)
    {
        retcode = Storage_IsAvailable(STORAGE_MEDIUM_SD_CARD, &status);
        if ((RETCODE_OK == retcode) && (true == status))
        {
            sdcardInsert = true;
            printf("SD card is inserted in XDK\n\r");
            ledRetcode = LED_On(LED_INBUILT_RED);
            if (RETCODE_OK != ledRetcode)
            {
                printf("SD card is inserted LED indication failure XDK\n\r");
            }
            if (sdcardEject == true)
            {
                retcode = Storage_Disable(STORAGE_MEDIUM_SD_CARD);
                if (RETCODE_OK == retcode)
                {
                    retcode = Storage_Enable();
                }
                if (RETCODE_OK == retcode)
                {
                    sdcardEject = false;
                }
            }
            /* Already restrict this value to be 0 or 1. */
#if FAT_FILE_SYSTEM==1
            if (RETCODE_OK == retcode)
            {
            	//retcode = Sensor_GetData(&sensorValue);
				/*const char* test;
				test = "test";
				printf(test);*/
				//char test = (char)i;
				//printf(test);
				//sprintf(test,"%i",i);
				//char absatz = "\n";
				//char *strcat(char *test,char *absatz);
                retcode = AppControllerFatFileSystemWriteRead();
            }
            if (RETCODE_OK == retcode)
            {
                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  */
            if (RETCODE_OK == retcode)
            {
                retcode = AppControllerSingleBlockWriteRead(SECTOR_VALUE);
            }
            if (RETCODE_OK == retcode)
            {
                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
        }
        else
        {
            if (Retcode_GetCode(retcode) == (Retcode_T) RETCODE_STORAGE_SDCARD_UNINITIALIZED)
            {
                printf("\r\n SD card is not inserted in XDK\n\r");
                retcode = Storage_Enable();
            }
            else
            {
                if (true == sdcardInsert)
                {
                    sdcardEject = true;
                }
                sdcardInsert = false;
                printf("\r\nSD card is removed from XDK\n\r");
                ledRetcode = LED_Off(LED_INBUILT_RED);
                if (RETCODE_OK != ledRetcode)
                {
                    printf("SD card is not inserted LED indication failure XDK\n\r");
                }

            }
        }
        if (RETCODE_OK != retcode)
        {
            Retcode_RaiseError(retcode);
        }
        vTaskDelay(pdMS_TO_TICKS(WRITEREAD_DELAY));
    }
}

/**
 * @brief To enable the necessary modules for the application
 * - SD Card
 * - LED
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerEnable(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);
    Retcode_T retcode, fileDeleteRetcode = RETCODE_OK;
    retcode = Storage_Enable();
    if ((Retcode_T) RETCODE_STORAGE_SDCARD_NOT_AVAILABLE == Retcode_GetCode((retcode)))
    {
        /* This is only a warning error. So we will raise and proceed */
        Retcode_RaiseError(retcode);
        retcode = RETCODE_OK; /* SD card was not inserted */
    }
    if (RETCODE_OK == retcode)
    {
        fileDeleteRetcode = Storage_Delete(STORAGE_MEDIUM_SD_CARD, TEST_FILENAME);
        if (RETCODE_OK != fileDeleteRetcode)
        {
            printf("File does not exist. \n\r");
        }
    }
    if (RETCODE_OK == retcode)
    {
        retcode = LED_Enable();
    }
    if (RETCODE_OK == retcode)
    {
        if (pdPASS != xTaskCreate(AppControllerFire, (const char * const ) "AppController", TASK_STACK_SIZE_APP_CONTROLLER, NULL, TASK_PRIO_APP_CONTROLLER, &AppControllerHandle))
        {
            retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_OUT_OF_RESOURCES);
        }
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerEnable : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

/**
 * @brief To setup the necessary modules for the application
 * - SD Card
 * - LED
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerSetup(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);

    Retcode_T retcode = RETCODE_OK;
    retcode = Storage_Setup(&StorageSetupInfo);
    if (RETCODE_OK == retcode)
    {
        retcode = LED_Setup();
    }
    if (RETCODE_OK == retcode)
    {
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerEnable, NULL, UINT32_C(0));
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerSetup : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

/* global functions ********************************************************* */

/** Refer interface header for description */
void AppController_Init(void * cmdProcessorHandle, uint32_t param2)
{
    BCDS_UNUSED(param2);

    Retcode_T retcode = RETCODE_OK;

    if (cmdProcessorHandle == NULL)
    {
        printf("AppController_Init : Command processor handle is NULL \r\n");
        retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_NULL_POINTER);
    }
    else
    {
        AppCmdProcessor = (CmdProcessor_T *) cmdProcessorHandle;
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerSetup, NULL, UINT32_C(0));
    }

    if (RETCODE_OK != retcode)
    {
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

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

 

0 (0 Voti)
RE: Storage in SD-Card
Risposta
17/06/19 11.17 come risposta a Michael Österreicher.

Hi Michael,

I will test your code. It will take a while so please be patient. Tell me if you have already found the bug.

regards

Saeid

 

+1 (1 Voto)
RE: Storage in SD-Card
Risposta
17/06/19 12.04 come risposta a Saeid Kajlar.

Hello Saeid,

thank you for your help. Unfortunately i haven't found the bug yet.

regards

Michael

0 (0 Voti)
RE: Storage in SD-Card
Risposta
17/06/19 15.41 come risposta a Michael Österreicher.

Hi Michael,

I did not have time to analyze your code, but I found an example. You will see that it is just like the USB example but instead of sending the data via USB, it will write data to the SD card. I hope it helps. If not then let me know. Do not forget to activate the XDK_UTILITY_STORAGE on the makefile.

/*
* Licensee agrees that the example code provided to Licensee has been developed and released by Bosch solely as an example to be used as a potential reference for application development by Licensee. 
* Fitness and suitability of the example code for any use within application developed by Licensee need to be verified by Licensee on its own authority by taking appropriate state of the art actions and measures (e.g. by means of quality assurance measures).
* Licensee shall be responsible for conducting the development of its applications as well as integration of parts of the example code into such applications, taking into account the state of the art of technology and any statutory regulations and provisions applicable for such applications. Compliance with the functional system requirements and testing there of (including validation of information/data security aspects and functional safety) and release shall be solely incumbent upon Licensee. 
* For the avoidance of doubt, Licensee shall be responsible and fully liable for the applications and any distribution of such applications into the market.
* 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are 
* met:
* 
*     (1) Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer. 
* 
*     (2) Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in
*     the documentation and/or other materials provided with the
*     distribution.  
*     
*     (3)The name of the author may not be used to
*     endorse or promote products derived from this software without
*     specific prior written permission.
* 
*  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 
*  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
*  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
*  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
*  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
*  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
*  POSSIBILITY OF SUCH DAMAGE.
*/
/*----------------------------------------------------------------------------*/

/**
 * @ingroup APPS_LIST
 *
 * @defgroup STREAM_SENSOR_DATA_OVER_USB StreamSensorDataOverUsb
 * @{
 *
 * @brief Application of printing all the defined sensors on serialport
 *
 * @details Demo application of printing all the defined sensors on serialport(USB virtual comport)
 *          every configured interval (#APP_CONTROLLER_TX_DELAY)
 *
 * @file
 **/

/* module includes ********************************************************** */

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

#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_APP_CONTROLLER

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

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

/* additional interface header files */
#include "XDK_Sensor.h"
#include "XDK_Utils.h"
#include "BCDS_Assert.h"
#include "BCDS_CmdProcessor.h"
#include "FreeRTOS.h"
#include "task.h"
#include "BCDS_SDCard_Driver.h"
#include "ff.h"

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

/* local variables ********************************************************** */

static CmdProcessor_T *AppCmdProcessor;/**< Handle to store the main Command processor handle to be reused by ServalPAL thread */

static xTaskHandle AppControllerHandle = NULL;/**< OS thread handle for Application controller to be used by run-time blocking threads */

const char Filename[] = "test_xdk.txt";
#define DEFAULT_LOGICAL_DRIVE   ""
#define DRIVE_ZERO              UINT8_C(0)
#define FORCE_MOUNT             UINT8_C(1)
#define FIRST_LOCATION          UINT8_C(0)

static FIL fileObject;

static Sensor_Setup_T SensorSetup =
        {
                .CmdProcessorHandle = NULL,
                .Enable =
                        {
                                .Accel = true,
                                .Mag = true,
                                .Gyro = true,
                                .Humidity = true,
                                .Temp = true,
                                .Pressure = true,
                                .Light = true,
                                .Noise = false,
                        },
                .Config =
                        {
                                .Accel =
                                        {
                                                .Type = SENSOR_ACCEL_BMA280,
                                                .IsRawData = false,
                                                .IsInteruptEnabled = false,
                                                .Callback = NULL,
                                        },
                                .Gyro =
                                        {
                                                .Type = SENSOR_GYRO_BMG160,
                                                .IsRawData = false,
                                        },
                                .Mag =
                                        {
                                                .IsRawData = false,
                                        },
                                .Light =
                                        {
                                                .IsInteruptEnabled = false,
                                                .Callback = NULL,
                                        },
                                .Temp =
                                        {
                                                .OffsetCorrection = APP_TEMPERATURE_OFFSET_CORRECTION,
                                        },
                        },
        };/**< Sensor setup parameters */

/* global variables ********************************************************* */

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

/* local functions ********************************************************** */

void InitSdCard(void){
  Retcode_T retVal = RETCODE_FAILURE;
  FRESULT FileSystemResult = FR_OK;
  static FATFS FatFileSystemObject;
  SDCardDriver_Initialize();
  if(SDCARD_INSERTED == SDCardDriver_GetDetectStatus()){
    retVal = SDCardDriver_DiskInitialize(DRIVE_ZERO);
    if(RETCODE_OK == retVal){
      printf("SD Card Disk initialize succeeded \n\r");
      FileSystemResult = f_mount(&FatFileSystemObject, DEFAULT_LOGICAL_DRIVE,
                                    FORCE_MOUNT);
      if (FR_OK != FileSystemResult){
        printf("Mounting SD card failed \n\r");
      }
    }
  }
}

Retcode_T searchForFileOnSdCard(const char* filename, FILINFO* fileData){
  if(FR_OK == f_stat(filename, fileData)){
    printf("File %s found on SD card. \n\r",filename);
    return RETCODE_OK;
  } else {
    printf("File %s does not exist. \n\r",filename);
    return RETCODE_FAILURE;
  }
}

void deleteFileOnSdCard(const char* filename){
  f_unlink(filename);
}

void createFileOnSdCard(const char* filename){
  if(FR_OK == f_open(&fileObject, filename, FA_CREATE_NEW)){
    printf("File %s was created successfully \n\r",filename);
  }
}

void writeDataIntoFileOnSdCard(const char* filename, const char* dataBuffer){
    FRESULT fileSystemResult;
    char ramBufferWrite[UINT16_C(512)]; // Temporay buffer for write file
    uint16_t fileSize;
    UINT bytesWritten;
    fileSize = (uint16_t) strlen(dataBuffer);

    for(uint32_t index = 0; index < fileSize; index++){
        ramBufferWrite[index] = dataBuffer[index];
    }
    f_open(&fileObject, filename, FA_OPEN_EXISTING | FA_WRITE);
    f_lseek(&fileObject, f_size(&fileObject));
    fileSystemResult = f_write(&fileObject, ramBufferWrite, fileSize, &bytesWritten);

    if((fileSystemResult != FR_OK) || (fileSize != bytesWritten)){
        printf("Error: Cannot write to file %s \n\r", filename);
    }
    fileSystemResult = f_close(&fileObject);
}

void readDataFromFileOnSdCard(const char* filename){
    FRESULT fileSystemResult;
    FILINFO fileInfo;
    char ramBufferRead[UINT16_C(512)]; // Temporary buffer for read file
    UINT bytesRead;

    if(RETCODE_OK == searchForFileOnSdCard(filename, &fileInfo)){
        f_open(&fileObject, filename, FA_OPEN_EXISTING | FA_READ);
        f_lseek(&fileObject, FIRST_LOCATION);
        fileSystemResult = f_read(&fileObject, ramBufferRead, fileInfo.fsize, &bytesRead);

        if((fileSystemResult != FR_OK) || (fileInfo.fsize != bytesRead)){
            printf("Error: Cannot read file %s \n\r", filename);
        }
        else{
            ramBufferRead[bytesRead] = '\0';
            printf("Read data from file %s of the SD card \n\r", filename);
            printf(ramBufferRead);
            printf("\n\r");
        }
        f_close(&fileObject);
    }
    else{
        printf("No file with name %s exists on the SD card \n\r", filename);
    }
}


/**
 * @brief This function controls the application flow
 * - Triggers Sensor data sampling
 * - Read the sampled Sensor data
 *
 * @param[in] pvParameters
 * Unused
 */
static void AppControllerFire(void* pvParameters)
{
    BCDS_UNUSED(pvParameters);

    Retcode_T retcode = RETCODE_OK;
    Sensor_Value_T sensorValue;
    char FileContent[512];

    while (1)
    {
        memset(&sensorValue, 0x00, sizeof(sensorValue));

        retcode = Sensor_GetData(&sensorValue);
        if (RETCODE_OK == retcode)
        {
            if (SensorSetup.Enable.Accel && !(SensorSetup.Config.Accel.IsRawData))
            {
                sprintf(FileContent, "Accelerometer Converted data :\n\rx =%ld mg\n\ry =%ld mg\n\rz =%ld mg\r\n",
                        (long int) sensorValue.Accel.X,
                        (long int) sensorValue.Accel.Y,
                        (long int) sensorValue.Accel.Z);
                writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Accel && (SensorSetup.Config.Accel.IsRawData))
            {
            	sprintf(FileContent, "Accelerometer Raw data :\n\rx =%ld \n\ry =%ld\n\rz =%ld\r\n",
                        (long int) sensorValue.Accel.X,
                        (long int) sensorValue.Accel.Y,
                        (long int) sensorValue.Accel.Z);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Humidity)
            {
            	sprintf(FileContent, "BME280 Environmental Conversion Data for Humidity:\n\rh =%ld %%rh\r\n",
                        (long int) sensorValue.RH);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Pressure)
            {
            	sprintf(FileContent, "BME280 Environmental Conversion Data for Pressure :\n\rp =%ld Pa\r\n",
                        (long int) sensorValue.Pressure);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Temp)
            {
            	sprintf(FileContent, "BME280 Environmental Conversion Data for temperature :\n\rt =%ld mDeg\r\n",
                        (long int) sensorValue.Temp);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Mag && !(SensorSetup.Config.Mag.IsRawData))
            {
            	sprintf(FileContent, "Magnetometer Converted data :\n\rx =%ld microTesla\n\ry =%ld microTesla\n\rz =%ld microTesla\n\rr =%ld\r\n",
                        (long int) sensorValue.Mag.X,
                        (long int) sensorValue.Mag.Y,
                        (long int) sensorValue.Mag.Z,
                        (long int) sensorValue.Mag.R);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Mag && SensorSetup.Config.Mag.IsRawData)
            {
            	sprintf(FileContent, "Magnetometer Raw data :\n\rx =%ld\n\ry =%ld\n\rz =%ld \n\rr =%ld\r\n",
                        (long int) sensorValue.Mag.X,
                        (long int) sensorValue.Mag.Y,
                        (long int) sensorValue.Mag.Z,
                        (long int) sensorValue.Mag.R);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Gyro && !(SensorSetup.Config.Gyro.IsRawData))
            {
            	sprintf(FileContent, "Gyro Converted Data :\n\rx =%ld mDeg\n\ry =%ld mDeg\n\rz =%ld mDeg\r\n",
                        (long int) sensorValue.Gyro.X,
                        (long int) sensorValue.Gyro.Y,
                        (long int) sensorValue.Gyro.Z);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Gyro && SensorSetup.Config.Gyro.IsRawData)
            {
            	sprintf(FileContent, "Gyro Raw Data :\n\rx =%ld \n\ry =%ld \n\rz =%ld \r\n",
                        (long int) sensorValue.Gyro.X,
                        (long int) sensorValue.Gyro.Y,
                        (long int) sensorValue.Gyro.Z);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Light)
            {
            	sprintf(FileContent, "Light sensor data obtained in millilux :%d \n\r", (unsigned int) sensorValue.Light);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
            if (SensorSetup.Enable.Noise)
            {
            	sprintf(FileContent, "Noise Sensor RMS Voltage :\r\nVrms = %f \r\n", sensorValue.Noise);
            	writeDataIntoFileOnSdCard(Filename, FileContent);
                memset(&FileContent, 0x00, sizeof(FileContent));
            }
        }
        if (RETCODE_OK != retcode)
        {
            Retcode_RaiseError(retcode);
        }
        vTaskDelay(pdMS_TO_TICKS(APP_CONTROLLER_TX_DELAY));
    }
}

/**
 * @brief To enable the necessary modules for the application
 * - Sensor
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerEnable(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);

    createFileOnSdCard(Filename);

    Retcode_T retcode = Sensor_Enable();
    if (RETCODE_OK == retcode)
    {
        if (pdPASS != xTaskCreate(AppControllerFire, (const char * const ) "AppController", TASK_STACK_SIZE_APP_CONTROLLER, NULL, TASK_PRIO_APP_CONTROLLER, &AppControllerHandle))
        {
            retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_OUT_OF_RESOURCES);
        }
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerEnable : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
    Utils_PrintResetCause();
}

/**
 * @brief To setup the necessary modules for the application
 * - Sensor
 *
 * @param[in] param1
 * Unused
 *
 * @param[in] param2
 * Unused
 */
static void AppControllerSetup(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);

    SensorSetup.CmdProcessorHandle = AppCmdProcessor;
    Retcode_T retcode = Sensor_Setup(&SensorSetup);

    InitSdCard();

    if (RETCODE_OK == retcode)
    {
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerEnable, NULL, UINT32_C(0));
    }
    if (RETCODE_OK != retcode)
    {
        printf("AppControllerSetup : Failed \r\n");
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

/* global functions ********************************************************** */

/** Refer interface header for description */
void AppController_Init(void * cmdProcessorHandle, uint32_t param2)
{
    BCDS_UNUSED(param2);

    Retcode_T retcode = RETCODE_OK;

    if (cmdProcessorHandle == NULL)
    {
        printf("AppController_Init : Command processor handle is NULL \r\n");
        retcode = RETCODE(RETCODE_SEVERITY_ERROR, RETCODE_NULL_POINTER);
    }
    else
    {
        AppCmdProcessor = (CmdProcessor_T *) cmdProcessorHandle;
        retcode = CmdProcessor_Enqueue(AppCmdProcessor, AppControllerSetup, NULL, UINT32_C(0));
    }

    if (RETCODE_OK != retcode)
    {
        Retcode_RaiseError(retcode);
        assert(0); /* To provide LED indication for the user */
    }
}

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

 

0 (0 Voti)
RE: Storage in SD-Card
Risposta
18/06/19 6.21 come risposta a Saeid Kajlar.

Hello Saeid,

thanks for your help. But i have 3 questions

- What i have to do exactly to activate the XDK_UTILITY_STORAGE on the makefile.

- I have problems with the "FR_OK" Symbol and i can´t build my project or flash my XDK

- i get an undefined reference to "Utils_PrintResetCause"

regards

Michael

0 (0 Voti)
RE: Storage in SD-Card
Risposta
18/06/19 8.39 come risposta a Michael Österreicher.

Hi Michael,

Please use the example program "StreamSensorDataOverUsb" and replace the AppController.c with the example from me. Then there should be no problems. You can ignore the "FR_OK" error and change the makefile as shown in the picture.

0 (0 Voti)
RE: Storage in SD-Card
Risposta
05/08/19 11.33 come risposta a Saeid Kajlar.

Hi Saeid,

I am using the given block of code in the StreamSensorDataOverUSB example and also modifed the makefile like you have said, But I am getting these errors. Can tell me why? 

0 (0 Voti)