FreeRTOS FAT SL – F_FS_THREAD_AWARE

Summary

If you have been following this series of articles about the FreeRTOS FAT SL filesystem, you might have read my post called “FreeRTOS FAT SL – Musings on my Implementation”.  In that post I asked myself “Why do I get the error message ‘undefined reference to xQueueCreateMutex'”.  Here is a screen shot from PSoC Creator

FreeRTOS FAT SL Error Message

When I traced through the problem I noticed that it comes from this block of code:

#if F_FS_THREAD_AWARE == 1
	{
		extern SemaphoreHandle_t fs_lock_semaphore;

		if( fs_lock_semaphore == NULL )
		{
			fs_lock_semaphore = xSemaphoreCreateMutex();
            
			if( fs_lock_semaphore == NULL )
			{
				return F_ERR_OS;
			}
		}
	}
#endif /* F_FS_THREAD_AWARE */

Which gave me the hint that it had something to do with F_FS_THREAD_AWARE being turned on.  When I got the error message I assumed that it had something to do with the tangled mess of include files that I had created.  This flag is set in config_fat_sl.h

/**************************************************************************
**
**  FAT SL user settings
**
**************************************************************************/
#define F_SECTOR_SIZE           512  /* Disk sector size. */
#define F_FS_THREAD_AWARE       1     /* Set to one if the file system will be access from more than one task. */
#define F_MAXPATH               16    /* Maximum length a file name (including its full path) can be. */
#define F_MAX_LOCK_WAIT_TICKS   20

So, to “solve” the problem I just turned it off, knowing that I would need to come back to it to figure out because for sure if you are using the FreeRTOS FAT SL filesystem in an RTOS, which I am, you had better have the thread awareness turned on.  Specifically what the flag does is create and use a mutex around the actual “disk” to prevent re-entrant code from hosing you.

This morning I sat down and figured it out.  The answer is that I am an idiot.  Almost all of the features of FreeRTOS that you might want to use need to be turned on in the FreeRTOSConfig.h file.  This is true of mutex.  Here is the section of the file with the issue… look at line 19

#define configUSE_PREEMPTION                    1
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
#define configUSE_TICKLESS_IDLE                 0
#define configCPU_CLOCK_HZ                      ( ( unsigned long ) CYDEV_BCLK__SYSCLK__HZ )
#define configTICK_RATE_HZ                      1000
#define configMAX_PRIORITIES                    5
#define configMINIMAL_STACK_SIZE                128
#define configMAX_TASK_NAME_LEN                 16
#define configUSE_16_BIT_TICKS                  0
#define configIDLE_SHOULD_YIELD                 1
#define configUSE_TASK_NOTIFICATIONS            1
#define configUSE_MUTEXES                       0 // <=== here is the problem line
#define configUSE_RECURSIVE_MUTEXES             0
#define configUSE_COUNTING_SEMAPHORES           0
#define configUSE_ALTERNATIVE_API               0 /* Deprecated! */
#define configQUEUE_REGISTRY_SIZE               10
#define configUSE_QUEUE_SETS                    0
#define configUSE_TIME_SLICING                  0
#define configUSE_NEWLIB_REENTRANT              0
#define configENABLE_BACKWARD_COMPATIBILITY     0
#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 5

When I turn on the configUSE_MUTEXS things compile just fine and I can get on with my life.

FreeRTOS FAT SL – Musings on my Implementation

Summary

I just finished writing the “last” article about building a FreeRTOS FAT SL filesystem into the Cypress FM24V10 FRAM using a CY8CKIT-044.  My implementation works pretty well…. but I am not really that happy with it.  As I sit here and write this article I am not totally sure what I should do next.

I suppose the first thing to do is talk about the things that I don’t like in what I did.

  1. Real Time Clock
  2. Command Line Interpreter
  3. DMA Media Driver
  4. Include files
  5. F_FS_THREAD_AWARE 0
  6. Template project
  7. Performance Metrics
  8. Wear Leveling
  9. Performance Metrics
  10. Discussion of FAT Filesystems

Real Time Clock

As part of the port, you are supposed to provide psp_rtc.c which has one function, psp_getcurrentimedate.  This function is used to get the time to use as a timestamp on files.  I left it default, which means every transaction is timestamped the same, probably not good.  Moreover, there is an RTC in the PSoC4200M that is on the CY8CKIT-044.  The board also has the watch crystal which drives the RTC populated so there is really no good reason not to turn it on.

FreeRTOS FAT SL PSoC RTC

However, when I wrote the original example the command line interpreter that I build only took one character at a time, so there was no good way to set the clock.   Which brings me to the next problem.

Command Line Interpreter (CLI)

When I originally build the example project my command interpreter just had an infinite loop that waited for a character from the keyboard, then did one command based on that character.  It looks like this:

   while(1)
    {
        ulTaskNotifyTake(pdTRUE,portMAX_DELAY);
        
        while(UART_SpiUartGetRxBufferSize()) // if there is data then read and process
        {
            char c;
            
            c= UART_UartGetChar();
			switch(c)
			{
				case 'i': 
				break;
				
			
                case '?': // Print out the list of commands
                    
                break;
                    
                default:
                break;
			}
        }
        // Turn the interrupts back on
        UART_ClearRxInterruptSource(UART_INTR_RX_NOT_EMPTY); 
        UART_SetRxInterruptMode(UART_INTR_RX_NOT_EMPTY);
    }

What I did was cheap and easy… but, FreeRTOS has a CLI built in, so I suppose that I should have used.

DMA Media Driver

When I read and write from the FRAM I put in code that is blocking.  Meaning that it essentially hangs the entire system until they return.  Not really good given that this is an RTOS.  This is what all of the I2C_ functions below do.

  status = I2C_I2CMasterSendStart( calcI2CAddress(sector),I2C_I2C_WRITE_XFER_MODE);
    if(status != I2C_I2C_MSTR_NO_ERROR)
    {
        UART_UartPutString("I2C Error\n");
        return MDRIVER_RAM_ERR_SECTOR;
    }
    int i;
    I2C_I2CMasterWriteByte((address>>8)&0xFF);
    I2C_I2CMasterWriteByte(address & 0xFF); //

There is no reason that I shouldn’t have used the DMA engine to read and write the FRAM which would have freed up the processor.

Include files

I absolutely hate the scheme that I used to name and use the includes in the FreeRTOS FAT SL port.  I should fix this for sure.

F_FS_THREAD_AWARE 0

When I originally tried to compile this project I marked this #define from “config_fat_sl.h” as “1”.  However when I do that, I end up with this error which I should for sure fix as the code is not reentrant and this #define protects you.

An RTOS bug in the FreeRTOS FAT SL Implementation

Template project

My good friend Mark Saunders pointed out PSoC Creator has a new feature which you can use to make template projects.. which I didnt know about until he told me.  Obviously this would be better than what I am doing.

Performance Metrics

I did not collect any performance metrics when I build this project.  How much RAM? Flash?  How long does it take to read and write files?  I don’t know.  Moreover, I put in debugging information into the media driver which was counter productive to good memory usage.  For instance in this snip from the readsector function I define a big ass buffer of 128 bytes on line 134, then I printout a message to the uart each time this function is called.

static int fram_readsector ( F_DRIVER * driver, void * data, unsigned long sector )
{
    char buff[128]; // A scratch buffer for UART Printing
    (void)driver;
    uint16 address;
    uint32_t status;
    
    sprintf(buff,"Read sector %d\n",(int)sector);
    UART_UartPutString(buff);

Error Checking

There are a bunch of places where I could have put in much better error checking, and I didnt.  For instance in this section of the readsector function if the I2C_I2CMasterWriteByte function fails, it probably hangs the I2C bus until the chip is reset… this is bad.  Even when an error occurs, printing a message probably isn’t a good idea (line 146).

    if(status != I2C_I2C_MSTR_NO_ERROR)
    {
        UART_UartPutString("I2C Error\n");
        return MDRIVER_RAM_ERR_SECTOR;
    }
    int i;
    I2C_I2CMasterWriteByte((address>>8)&0xFF);
    I2C_I2CMasterWriteByte(address & 0xFF); // 
    
    
    I2C_I2CMasterSendRestart(calcI2CAddress(sector),I2C_I2C_READ_XFER_MODE);

Wear Leveling

Many nonvolatile memory chip will wear out if you write them too many time.  Even 100K cycles can easily happen on a key sector of the filesystem for instance sector 0.  One convient thing about the FRAM is that it doesnt wear out.  But, when I started this journey I was originally going to use the PSoC6 development kit which uses a NOR Flash.  The NOR Flash will for sure wear out.  To combat this problem, people have developed wear leveling schemes.  But I don’t address this issue at all with my media driver.

Discussion of FAT Filesystems

As I wrote about the FreeRTOS FAT SL Filesystem I was originally planning a tutorial on file systems.  But as I dug a little bit a whole bunch of issues came up which felt a little bit overwhelming to address.  The issues that were left unaddressed are:

  1. Copywrite of the FAT File System
  2. Efficiency of FAT File Systems
  3. The licensing of the FreeRTOS FAT SL
  4. Other FAT implementations

I suppose that at some point I should come back and look at those issues.

FreeRTOS FAT SL – PSoC Example Project (Part 2)

Summary – Examples using FreeRTOS FAT SL

In the previous several articles I have written about the FreeRTOS FAT SL Filesystem.  This included using the Cypress FM24V10 FRAM, creating an FRAM media driver and building an example project.  This article will show you the C-functions in “extestfs.c” that are used to actually test the filesystem.  Notice that I named all of the functions starting with “ex” which I adopted from the FreeRTOS FAT SL examples.  The functions in this article are all called by the command line interpreter that I built in the previous post.  They include

  • exInit – Initializing the Filesystem
  • exCreateFile – Creating a file in the FileSystem
  • exReadFile – Reading the data from a file
  • exFormat – Formatting the disk
  • exDriveInfo – Printing the drive information
  • exDirectory – Print an “ls” or “dir”

exInit

Before the FreeRTOS FAT SL Filesystem can do anything, you must initialize it.  All this function does is call the function that I created to turn on the file system in the media port.  One thing that is interesting is that it returns an error code that tells you if the file system is formatted or  not.   It figured this out by looking at the data in the first sector of the FRAM.

// This function initalize the filesystem
void exInit(void)
{
    unsigned char ucStatus;
    
	/* First create the volume. */
	ucStatus = f_initvolume( fram_initfunc );
    UART_UartPutString("Initialized sucessfully\n");
	/* It is expected that the volume is not formatted. */
	if( ucStatus == F_ERR_NOTFORMATTED )
	{
        UART_UartPutString("Filesystem Unformatted\n");
	}
    
    else
    {
        UART_UartPutString("Filesystem Formatted\n");
    }
}

exCreateFile

This functiom creates a file called “afile.txt” in the FreeRTOS FAT SL filesystem with the ASCII characters for 0-9.  I did something that was probably not helpful in that I made a loop (on line 43) that started a ‘0’ which is also known as 49 (go look at the ASCII table).

This function calls f_open which will create a new file when it is passed the argument “w”.  I also use the function f_putc to output characters to the file.

As I am looking at the code to write this article I realized that I didnt f_close the file (which I have now fixed).

#define FILENAME "afile.txt"
// exCreateFile - this function creates a file called "afile.txt" an
void exCreateFile(void)
{
    F_FILE *pxFile;
    UART_UartPutString("Attempting Create & Write File\n");
    pxFile = f_open(FILENAME, "w" );
  
    if(pxFile)
    {
        for(int i='0' ; i< '9' ; i++)
        {
            f_putc(i,pxFile);
        }
        f_close(pxFile);
    }
    else
    {
        UART_UartPutString("Failed File Create\n");
    }
}

exReadFile

The exReadFile functions reads all of the characters out of the “afile.txt” and prints them to the screen.  It uses the function f_getc which reads one character from the file.  Notice that I open the file in read mode by using the “r” option.

void exReadFile(void)
{
    UART_UartPutString("Attempting Read\n");
    F_FILE *pxFile;
    pxFile = f_open( FILENAME, "r" );
    if(pxFile)
    {
        while(!f_eof(pxFile))
        {
            UART_UartPutChar(f_getc(pxFile));
        }
        f_close(pxFile);
    }
    else
    {
        UART_UartPutString("File not found\n");
    }
}

exFormat

The exFormat function calles f_format with the FAT12 option.  It is impossible to use FAT16 and FAT32 which require a much larger media to use.  FAT12 was originally created for use on smallish floppy disk.

void exFormat(void)
{
    char buff[128];
	/* Format the created volume. */
    unsigned char ucStatus;
	ucStatus = f_format( F_FAT12_MEDIA );
	if( ucStatus == F_NO_ERROR )
	{
        UART_UartPutString("Formatted sucessfully\n");
    }
    else
    {
        sprintf(buff,"Error = %d\n",ucStatus);
        UART_UartPutString(buff);   
        UART_UartPutString("Format Error\n");
    }   
}

exDriveInfo

The exDriveInfo function calls the f_getfreespace function to find out how much space is free for use on the FRAM FreeRTOS FAT SL Filesystem.

void exDriveInfo( void )
{
    char buff[128];
    F_SPACE xSpace;
    unsigned char ucReturned;

    /* Get space information on current embedded FAT file system drive. */
    ucReturned = f_getfreespace( &xSpace );
    if( ucReturned == F_NO_ERROR )
    {
        /* xSpace.total holds the total drive size, xSpace.free holds the
        free space on the drive, xSpace.used holds the size of the used space
        on the drive, xSpace.bad holds the size of unusable space on the
        drive. */
        sprintf(buff,"Free Space = %lu\nUsed Space = %lu\nTotal = %lu\n",xSpace.free,xSpace.used,xSpace.total);
        UART_UartPutString(buff);
    }
    else
    {
        /* xSpace could not be completed.  ucReturned holds the error code. */
        UART_UartPutString("Free space failed\n");
    }
}

exDirectory

The exDirectory function calls the f_findfirst and f_findnext functions to iterate all of the files and directories on the top level of the file system.  The f_findfirst function uses a wildcard regular expression to match filenames. When it finds a file it prints information about that file.

void exDirectory( void )
{
    char buff[128];
    F_FIND xFindStruct;

    /* Print out information on every file in the subdirectory "subdir". */
    if( f_findfirst( "*.*", &xFindStruct ) == F_NO_ERROR )
    {
        do
        {
            sprintf(buff,"filename:%s ", xFindStruct.filename );
            UART_UartPutString(buff);

            if( ( xFindStruct.attr & F_ATTR_DIR ) != 0 )
            {
                UART_UartPutString ( "is a directory directory\n" );
            }
            else
            {
                sprintf ( buff, "is a file of size %lu\n", xFindStruct.filesize );
                UART_UartPutString(buff);
            }

        } while( f_findnext( &xFindStruct ) == F_NO_ERROR );
    }
}

 

Maker Faire Louisville

Summary

On Saturday, as promised, I went to Maker Faire Louisville with my Lab Assistant Nicholas.  I gave out the Cypress CY8CKIT-049 development kit to everyone who asked.  This kit is really cool as it has a PSoC4200 and a Cypress USB Serial UART bridge.

It comes in this flat cardboard mailer.

CY8CKIT-049

CY8CKIT-049

I made a bunch of videos on how to use the kit.  You can find them on youtube or on Cypress.com.

The development kit is cool for a bunch of reason.  First, it is only $4.. which is awesome as I am not aware of anyone else out there was a bad ass kit like this for less.  Second, you can break off the programmer, then solder the development kit directly into your design.  So it is perfect to support your prototyping issues.  Third, you can plug is into your computer directly, without a cable, and boatload new firmware into the PSoC4200.  Finally, after you break off the programmer you are left with a USB to UART bridge to use for other things.

Maker Faire Louisville Pictures

Here are some of the “Where is waldo.? I mean where is the IoT Expert?” pictures that I took for twitter.

Maker Faire Louisville
At my office in Lexington with the twitter teaser picture for Maker Faire Louisville
Maker Faire Louisville
A few beers at Gordon Biersch before Maker Faire Louisville.

Maker Faire Louisville
At the entrance to Maker Faire Louisville

Maker Faire Louisville
At the GE First Build Forget demonstration at Maker Faire Louisville
Maker Faire Louisville
With Bill Cloyd of Newton’s Attic at Maker Faire Louisville

Maker Faire Louisville
With Adam Carlson A.K.A twitter aeroengineer1

This was my first meeting with Adam in person.  He works on giant giant giant engines that are use on the Boeing 777.  The Fan in the engine is like 11 feet tall.

But more interesting,  he is the editor for the EE Times website electroschematics.com

EE Times Electroschematics.com

While we were chatting he asked me to build an example project using PSoC with USB and a bulk endpoint.  I gave him a reference to a video made by Jon Moeller.  But, I thought that it would be a good idea to create a page of reader requests for this website… which I will do.

Here is the link to the Jon Moeller Video on PSoC5 and Bulk USB Endpoints.

https://www.youtube.com/watch?v=dQdCqX84jXQ

 

FreeRTOS FAT SL – PSoC Example Project (Part 1)

Summary

In the previous articles I discussed using the FRAM, and making a FreeRTOS FAT SL media driver.  In this article I will discuss building an example project that uses that work to make a real FreeRTOS FAT SL system example.  I was originally planning on making just one article explaining the example, but my example code turned out to be a little bit sprawling, so I decided to break it into two pieces.  In part 1 (this article) I will

  1. Build the FreeRTOS Template
  2. Import the FreeRTOS FAT SL FileSystem & FRAM Media Driver
  3. Build a command line interpreter
  4. Nuke the data in the FRAM

In the next article I will show you the details of using the FreeRTOS FAT SL filesystem.

Build the FreeRTOS Template & Schematic

I start the project from my FreeRTOS template project.  You can read all about that here.  Then I add in the components required to make things work.  The schematic is simple:

  • A UART component to run the Command Line Interpreter
  • An I2C to control the FRAM

FreeRTOS FAT SL Example Schematic

The I2C is setup as a master at it highest speed setting.

FreeRTOS FAT SL I2C Configuration

On the CY8CKIT-044 the pins need to be configured as so:

FreeRTOS FAT SL - Pin Configuration

Import the FreeRTOS FAT SL FileSystem & FRAM Media Driver

The first step in importing the FreeRTOS FAT SL FileSystem and and media driver is to copy the FreeRTOS-Plus-FAT-SL directory into my project.  Once that is done, my folder structure looks like this:

FreeRTOS FAT SL Code Layout

The next step is to fix the include paths to include the config, api and psp include directories.  This can be done on the build settings menu.

FreeRTOS FAT SL Include Files

Finally I import the .h and .c files into my project so that it looks like this:

FreeRTOS FAT SL Project Directory Structure

Build a Command Line Interpreter (CLI)

I think that it is convenient to have a command line utility (one that connects to the UART port) to send commands to my program to test it.  To build the CLI, I create a task called uartTask which takes keys from the terminal and then processes them in a giant switch statement.  While I was building the FreeRTOS FAT SL system, I noticed that FreeRTOS also has a scheme for CLIs which I will try out in the future.

In the UART configuration I turn on the “RX FIFO not empty” interrupt (meaning that there is data in the fifo that needs to be processed)

FreeRTOS FAT SL UART Configuration

I connect the interrupt to the interrupt service routine on line 64.  In the ISR I use the FreeRTOS notification scheme to send notifications to the uartTask to wakeup and process data (line 50).

My CLI has two different things that it does:

  • It calls functions in the file extestfs.c that start with “ex” , meaning example, to format, initalize etc.
  • It keeps a “currentSector” variable that lets me print out the raw data in a sector.  The currentSector variable is incremented (with the keyboard +) and decremented (with the keyboard -) and set to 0 with the (keyboard 0)

Once all of the keys have been processed (the Rx FIFO buffer is empty – line 71), it turns back on the Rx FIFO interrupt (lines 150-151), then waits for another notification from the ISR (line 69)

TaskHandle_t uartTaskHandle;
void uartISR()
{
    
    BaseType_t xHigherPriorityTaskWoken;
    // disable the interrupt
    UART_SetRxInterruptMode(0);
    vTaskNotifyGiveFromISR(uartTaskHandle,&xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
    
}

// This is the main task which processes commands from the UART and prints the results
// on the screen.
void uartTask(void *arg)
{
    (void)arg;
    UART_Start();
    I2C_Start();
    clearScreen();
    UART_UartPutString("Start Filesystem Demo\n");
    UART_SetCustomInterruptHandler(uartISR);
    
    int currentSector=0;    
    while(1)
    {
        ulTaskNotifyTake(pdTRUE,portMAX_DELAY);
        
        while(UART_SpiUartGetRxBufferSize()) // if there is data then read and process
        {
            char c;
            
            c= UART_UartGetChar();
			switch(c)
			{
				case 'i': // Initialize the RTOS
					exInit();
				break;
				case 'f': // Format the FRAM
					exFormat();
				break;
                    
				case 'q': // Return the drive information
					exDriveInfo();
				break;
			
                case 'w': // Create a file
				    exCreateFile();
				break;
					
				case 'r': // Read the file that was created (if it exists)
				    exReadFile();
				break;
					
				case '0': // Goto to sector 0 and print the data
				    currentSector = 0;
					exPrintSector(0,0,0);
				break;
				
			    case '+': // Print the "current" sector and go to the next
				    exPrintSector(0,0,currentSector);
				    currentSector += 1;
			    break;
					
			    case '-': // print the current sector and go to the previous
				    exPrintSector(0,0,currentSector);
				    currentSector -= 1;
				    if(currentSector<0)
					    currentSector =0;
			    break;
                    
    			case 'd': // Do a directory
	    			exDirectory();
		    	break;
                    
                case 'c':
                    clearScreen();
                break;
                    
                case 'b': // Erase the FRAM (write all 0's)
                    blankFRAM();
                break;
			
                case '?': // Print out the list of commands
                    UART_UartPutString("b - Blank FRAM - write all 0's\n");
                    UART_UartPutString("i - Initalize Filesystem\n");
                    UART_UartPutString("f - Format FRAM\n");
                    UART_UartPutString("q - Print FileSystem Information\n");
                    UART_UartPutString("w - Create a file called \"afile.bin\"\n");
                    UART_UartPutString("r - Read the file called \"afile.bin\" and print contents\n");
                    UART_UartPutString("0 - Goto sector 0 and print contents\n");
                    UART_UartPutString("+ - Goto next sector and print contents\n");
                    UART_UartPutString("- - Goto previous sector and print contents\n");
                    UART_UartPutString("d - Print Directory\n");
                    UART_UartPutString("c - Clear Screen\n");
                    UART_UartPutString("? - Print help\n");        
                    
                break;
                    
			    default:
				    UART_UartPutString("Unknown :");
				    UART_UartPutChar(c);
				    UART_UartPutChar('\n');
			    break;
			}
        }
        // Turn the interrupts back on
        UART_ClearRxInterruptSource(UART_INTR_RX_NOT_EMPTY); 
        UART_SetRxInterruptMode(UART_INTR_RX_NOT_EMPTY);
    }
}

Nuke the FRAM Data

I thought that it would be a good idea to have a function to put 0’s in all of the locations in the FRAM, to prove that I could start with a clean slate.  This function does just that.  Specifically it write 0’s to the 64K locations in I2C address 0x50 (the first bank) and to I2C address 0x51 (the second bank)

// This function erases - write 0's into the FRAM... also known as NUKE the FRAM
void blankFRAM(void)
{
    int i;
    UART_UartPutString("Starting Erase 1st Block\n");
    I2C_I2CMasterSendStart(0x50,I2C_I2C_WRITE_XFER_MODE);
    I2C_I2CMasterWriteByte(0);
    I2C_I2CMasterWriteByte(0);
    for(i=0;i<0xFFFF;i++) // Write 64K of 0's to erase first bank
    {
        I2C_I2CMasterWriteByte(0);
    }
    I2C_I2CMasterSendStop();
    UART_UartPutString("Starting Erase 2nd Block\n");
    I2C_I2CMasterSendStart(0x51,I2C_I2C_WRITE_XFER_MODE);
    I2C_I2CMasterWriteByte(0);
    I2C_I2CMasterWriteByte(0);
    for(i=0;i<0xFFFF;i++) // write 64k of 0's to erase 2nd bank
    {
        I2C_I2CMasterWriteByte(0);
    }
    I2C_I2CMasterSendStop();
    
    UART_UartPutString("Erase Complete\n");

}

As always you can find this project on the IoT Expert GitHub site git@github.com:iotexpert/PSoC-FileSystem.git

FreeRTOS FAT SL FileSystem Porting to PSoC4M

CY8CKIT-044 for FreeRTOS FAT FL FileSystem

Summary of FreeRTOS FAT SL FileSystem Port

In the previous article I discussed the Cypress 24V10 FRAM which I am going to use to store nonvolatile data for the FreeRTOS FAT SL FileSystem.  The “SL” in the name stands for “super light” and was built by HCC Embedded for, get this, embedded applications.

In this article I am going to show you how to build a media driver to make the FreeRTOS FAT SL FileSystem work.  In the next article I will talk about how to actually use the FreeRTOS FAT SL FileSystem on the CY8CKIT-044 using the Cypress FMV24V10 FRAM.

The media driver is pretty simple,  you just need to provide the following functions:

And two structures

  • F_DRIVER – Function pointers to the media driver functions
  • F_PHY – Information about the FRAM

To make all of this work I will start by copying the “ram” driver that was provided as an example (ill call mine framdrv_f.c).  The file that I started with resides in FreeRTOS-Plus/Source/FreeRTOS-Plus-FAT-SL/media-drv/ram/ramdrv_f.c

F_DRIVER Structure

The F_DRIVER structure mostly contains function pointers to the driver functions (which you create).  All throughout the FreeRTOS FAT SL FileSystem code it will do things like :

status = mdrv->getstatus( mdrv );

which calls the function in the media driver structure named “getstatus”.

Here is the exact definition of the F_DRIVER STRUCTURE (found in FreeRTOS-Plus-FAT-SL/api/api_mdriver.h) :

typedef struct F_DRIVER  F_DRIVER;

typedef int           ( *F_WRITESECTOR )( F_DRIVER * driver, void * data, unsigned long sector );
typedef int           ( *F_READSECTOR )( F_DRIVER * driver, void * data, unsigned long sector );
typedef int           ( *F_GETPHY )( F_DRIVER * driver, F_PHY * phy );
typedef long          ( *F_GETSTATUS )( F_DRIVER * driver );
typedef void          ( *F_RELEASE )( F_DRIVER * driver );

typedef struct F_DRIVER
{
  unsigned long  user_data;     /* user defined data */
  void         * user_ptr;      /* user define pointer */

  /* driver functions */
  F_WRITESECTOR          writesector;
  F_READSECTOR           readsector;
  F_GETPHY               getphy;
  F_GETSTATUS            getstatus;
  F_RELEASE              release;
} _F_DRIVER;

typedef F_DRIVER *( *F_DRIVERINIT )( unsigned long driver_param );

The user_data and user_ptr do not appear to be used anywhere in the FreeRTOS FAT SL FileSystem code, so I am not sure what they had in mind for those variables.

The F_PHY Structure

The other structure that is needed (sort of) is F_PHY.  This structure contains parameters that were originally meant for disk drives and are no longer used.  For the FRAM I will divide up the 128k array into “sectors” of “512” bytes.  For some reason which I don’t understand the sector size must be fixed to 512 bytes.  The history of FAT filesystems is incredibly messy, and I started to dig through it so that I understood the number, but I am not sure that there are enough hours in my life.

typedef struct
{
  unsigned short  number_of_cylinders;
  unsigned short  sector_per_track;
  unsigned short  number_of_heads;
  unsigned long   number_of_sectors;
  unsigned char   media_descriptor;

  unsigned short  bytes_per_sector;
} F_PHY;

As I wrote this article I didnt remember setting up the F_PHY structure… but things still worked (ill address this later in the article).

F_DRVERINIT()

This function sets up the function pointers and marks the in_use variable.

/****************************************************************************
 *
 * fram_initfunc
 *
 * this init function has to be passed for highlevel to initiate the
 * driver functions
 *
 * INPUTS
 *
 * driver_param - driver parameter
 *
 * RETURNS
 *
 * driver structure pointer
 *
 ***************************************************************************/
F_DRIVER * fram_initfunc ( unsigned long driver_param )
{
  ( void ) driver_param;

    UART_UartPutString("Calling init\n");

  if( in_use )
    return NULL;

  (void)psp_memset( &t_driver, 0, sizeof( F_DRIVER ) );

  t_driver.readsector = fram_readsector;
  t_driver.writesector = fram_writesector;
  t_driver.getphy = fram_getphy;
  t_driver.release = fram_release;

  in_use = 1;

  return &t_driver;
} /* fram_initfunc */

F_GETPHY()

This function returns information about the FRAM including the size (in sectors) and the size of the sectors (in bytes)

/****************************************************************************
 *
 * ram_getphy
 *
 * determinate ramdrive physicals
 *
 * INPUTS
 *
 * driver - driver structure
 * phy - this structure has to be filled with physical information
 *
 * RETURNS
 *
 * error code or zero if successful
 *
 ***************************************************************************/
static int fram_getphy ( F_DRIVER * driver, F_PHY * phy )
{
  /* Not used. */
  ( void ) driver;

  phy->number_of_sectors = maxsector;
  phy->bytes_per_sector = F_SECTOR_SIZE;

  return MDRIVER_RAM_NO_ERROR;
}

FRAM Helper Functions

In order to map sectors to the correct I2C address (remember the FRAM has two banks of memory in two different I2C addresses) and to the correct bank address, I created two function which map “sector” into address and I2C address.

static const unsigned long maxsector = FDRIVER_VOLUME0_SIZE / F_SECTOR_SIZE;
static const unsigned long halfsector = FDRIVER_VOLUME0_SIZE / F_SECTOR_SIZE / 2;

/****************************************************************************
 *
 * calcAddress
 *
 * This function takes a sector and returns the address in the bank for the
 * start of the secor
 *
 * INPUTS
 *
 * unsigned long sector - which logical sector in the FRAM
 * 
 * RETURNS
 *
 * The FRAM Address of the sector
 *
 ***************************************************************************/
static inline uint32_t calcAddress(unsigned long sector)
{
    if(sector < halfsector)
        return sector * F_SECTOR_SIZE;
    else
        return (sector-halfsector) * F_SECTOR_SIZE;
}

/****************************************************************************
 *
 * calcI2CAddress
 *
 * This function takes a sector from 0 --> maxsector and figures out which bank
 * the address exists.
 *
 * INPUTS
 *
 * unsigned long sector - which logical sector in the FRAM to write to
 * 
 * RETURNS
 *
 * The I2C Address of Bank 0 or Bank 1
 *
 ***************************************************************************/
static inline uint32_t calcI2CAddress(unsigned long sector)
{
    if(sector < halfsector)
        return 0x50; // I2C Bank 0 Address from the datasheet
    else
        return 0x51; // I2C Bank 0 Address - From the datasheet  
}

F_READSECTOR()

This function reads 512 bytes that are located in the sector into the RAM buffer pointed to by data.  Notice on lines 26 & 27 I put in debugging information.  In order to read you need to

  • Send a start (line 30)
  • Send the I2C address and the write bit
  • Set the address you want to read from (line 37-38)
  • Send a restart (line 41)
  • read the 512 bytes (lines 44-54)
  • On the last byte NAK (line 47-50)
/****************************************************************************
 *
 * fram_readsector
 *
 * This function reads 512 bytes into the SRAM at the pointer data
 *
 * INPUTS
 *
 * driver - driver structure
 * void *data - a pointer to the SRAM where the 512 bytes of data will be written
 * unsigned long sector - which logical sector in the FRAM to read from
 * 
 * RETURNS
 *
 * error code or MDRIVER_RAM_NO_ERROR if successful
 *
 ***************************************************************************/

static int fram_readsector ( F_DRIVER * driver, void * data, unsigned long sector )
{
    char buff[128]; // A scratch buffer for UART Printing
    (void)driver;
    uint16 address;
    uint32_t status;
    
    sprintf(buff,"Read sector %d\n",(int)sector);
    UART_UartPutString(buff);
    
    address = calcAddress(sector);
    status = I2C_I2CMasterSendStart( calcI2CAddress(sector),I2C_I2C_WRITE_XFER_MODE);
    if(status != I2C_I2C_MSTR_NO_ERROR)
    {
        UART_UartPutString("I2C Error\n");
        return MDRIVER_RAM_ERR_SECTOR;
    }
    int i;
    I2C_I2CMasterWriteByte((address>>8)&0xFF);
    I2C_I2CMasterWriteByte(address & 0xFF); // 
    
    
    I2C_I2CMasterSendRestart(calcI2CAddress(sector),I2C_I2C_READ_XFER_MODE);
    
    uint8_t d;
    for(i=0;i<F_SECTOR_SIZE;i++)
    {
        
        if(i != F_SECTOR_SIZE - 1)
            d = I2C_I2CMasterReadByte(I2C_I2C_ACK_DATA);
        else
            d = I2C_I2CMasterReadByte(I2C_I2C_NAK_DATA);
         
        *((uint8_t *)data + i) = d;
        
    }
    
    I2C_I2CMasterSendStop();
    
  return MDRIVER_RAM_NO_ERROR;
}

F_WRITESECTOR()

The write sector is very similar to the read.  To write the data you need to

  • Send a start (line 204)
  • Write the address you want to write to (line 205-206)
  • Write the 512 bytes (lines 208-214)
  • Send a stop (line 215)
/****************************************************************************
 *
 * fram_writesector
 *
 * This function takes 512 bytes of user input and writes to the FRAM in the
 *
 * INPUTS
 *
 * driver - driver structure
 * void *data - a pointer to the SRAM where the 512 bytes of data exists
 * unsigned long sector - which logical sector in the FRAM to write to
 * 
 * RETURNS
 *
 * error code or MDRIVER_RAM_NO_ERROR if successful
 *
 ***************************************************************************/

static int fram_writesector ( F_DRIVER * driver, void * data, unsigned long sector )
{
    (void)driver;
    char buff[128]; // A scratch buffer for UART Printing
    uint16 address;
    int i;
        
    sprintf(buff,"Wrote sector %d\n",(int)sector);
    UART_UartPutString(buff);
        
    address = calcAddress(sector);
    I2C_I2CMasterSendStart(calcI2CAddress(sector),I2C_I2C_WRITE_XFER_MODE);
    I2C_I2CMasterWriteByte((address>>8)&0xFF);
    I2C_I2CMasterWriteByte(address & 0xFF); // 
    
    for(i=0;i<F_SECTOR_SIZE;i++)
    {
        uint8_t d = *((uint8_t *)data +i);
       
        I2C_I2CMasterWriteByte(d); 
        
    }
    I2C_I2CMasterSendStop();
    
  return MDRIVER_RAM_NO_ERROR;
}

F_GETSTATUS()

As I wrote the article I noticed in the documentation that I needed to provide the “F_GETSTATUS” function.  The reason that I had not noticed before was that it was not in the media driver provided in the distribution.  That being said, my implementation always returns a 0 indicating OK.

/****************************************************************************
 *
 * fram_getstatus
 *
 * This function must return the status of the drive... F_ST_MISSING, F_ST_CHANGED
 * or F_ST_WRPROECT or 0 (for OK)
 * INPUTS
 *
 * driver_param - driver parameter
 *
 *
 * For the FRAM I dont support any of these other status's
 ***************************************************************************/

static long fram_getstatus(F_DRIVER *driver)
{
    (void) driver;
    // F_ST_MISSING	The media is not present (it has been removed or was never inserted).
    //F_ST_CHANGED	Since F_GETSTATUS() was last called the media has either been removed and re-inserted, or a different media has been inserted.
    //F_ST_WRPROTECT	The media is write protected.
    
    return 0;
}

F_RELEASE()

This function simply set the in_use to 0;

/****************************************************************************
 *
 * fram_release
 *
 * Releases a drive
 *
 * INPUTS
 *
 * driver_param - driver parameter
 *
 ***************************************************************************/
static void fram_release ( F_DRIVER * driver )
{
  /* Not used. */
  ( void ) driver;

  /* Disk no longer in use. */
  in_use = 0;
}

In the next article I will show you the source code for an example project using the FreeRTOS FAT SL Filesystem.

FreeRTOS FAT SL FileSystem – Using the FM24V10 FRAM

Summary

Last week while working on a PSoC FreeRTOS Project, I looked at the CY8CKIT-044 Development kit that I was using and remembered that right under the Ambient Light Sensor there is a Cypress FM24V10 FRAM.  Way back, I started pushing our Development Kit team to put other Cypress parts onto the dev kits…. and because they are awesome, they aggressively started doing that.  One of those chips is the FM24V10 FRAM.  As I looked at the chip, I realized again that I had never really written anything into the FM24V10 FRAM on any of our dev kits, which seems silly after I pushed the dev kit team for them.  I realized that the reason I had never used the FM24V10 FRAM was I didn’t have a nifty way to write files.  But, while working on the other FreeRTOS projects, I noticed the FreeRTOS FAT SL Filesystem is built into FreeRTOS.  The next couple (3?) articles I will talk about making the FreeRTOS FAT SL Filesystem work on a PSoC4200M with a FM24V10 I2C FRAM.

CY8CKIT-044 with FM24V10 FRAM

The Cypress FM24V10 FRAM

The “F” in FRAM stands for ferroelectric.  What that means is each of the memory cells is a little magnet.  So what you say?  Well the “what” is that FRAMs don’t wear out (unlike Flash), you can write individual cells (unlike Flash), and it is super low power, it is plenty fast (I2C = 3.4MBS), and it retains data for a long long time (151 years).

That list sounds great.  Actually really great.  But, what is the but?  There are two answers to that question.  The first answer is there is a density penalty, the biggest I2C FRAM is 1Mb where you can buy a 1Gb NOR Flash or even bigger NAND Flash.  The next issue is price.  The digikey pricing for a 128Kb FRAM is $12.76 or 9.9c/kb and a 1GB NOR Flash is $14.97 or 0.0014c/kb.  That means an FRAM is 6724 x as expensive per bit.

How do I use it?  The FRAM is attached to the I2C pins on the CY8CKIT-044.  That means that I can talk to it with either the Bridge Control Panel, or with the PSoC.  To start with I will show you the Bridge Control Panel.  First, I probe the I2C bus, and I see that there are three I2C devices.

  • 0x0F = The I2C Accelerometer (which I wrote about here)
  • 0x50= The first 64K of FRAM
  • 0x51 = The second 64K of FRAM

The 128K FRAM is divided into two banks which are accessed on separate I2C addresses.  By splitting 128K into two blocks of 64K the chip designers optimized the addressing of the memory.  In order to access 64K you need 16-bits, which means to access 128K you need 17-bits.  This would have required sending a whole extra byte of address when you really only needed 1 of those 8 bits.  They avoid this problem by having two addresses.

The FM24V10 FRAM is easy to use as it implements an EzI2C (like) protocol.  EZI2C keeps an internal address pointer.  The pointer is automatically incremented each time you do an I2C transaction.  When you do a write transaction, the first two bytes you write are placed into the address pointer.  I say “EZI2C like” because the pointer is not retained between transactions.  Some examples:

If I want to write 0x56 into location 0x0123 I would issue

  • I2C Start
  • I2C Write to I2C address 0x50
  • Send 0x01, 0x02 (which write the address pointer)
  • Send 0x56
  • I2C Stop

I can do that sequence with the Bridge Control Panel command “W 50 01 23 56 P;”  The “W” stands for “send a start and send the 7-bit address 0x50 (left shifted 1) and send a ‘0’ for write”.  For some reason the engineers at Philips decided that the I2C protocol would have 7-bit addressing and then 1 bit to represent write or read.  When you talk about I2C there is always confusion about “8-bit address” versus “7-bit address”.  When they talk about 8-bit address they are talking about the 7-bit address shifted left 1 bit and then or-ed with the read or write bit.  Here is a picture from the bridge control panel:

And the same thing from the logic analyzer.

Once I have written 0x56 into address 0x0123, I can read it back by a “w 50 01 23 r 50 x p;” which sends:

  • I2C Start
  • I2C Write to I2C address 0x50
  • Send 0x01, 0x02 (which write the address pointer)
  • I2C Restart
  • Sends 0x50 (shifted left) or-ed with “read”
  • Reads the byte
  • I2C Stop

In the transaction output window below, you can see that the “x” is replaced with “56” meaning that it read the previously written value back.

The only other interesting thing about the protocol is that once you have sent and address, you can keep reading, or writing without sending the address again.  For instance to write 01, 02, 03, 04 to address 23, 23,25 and 26 you can send “W 50 00 23 01 02 03 04 p”, then you can read it back with “W 50 00 23 r 50 x x x x p;”

In the next Article I will start the process of using the Free RTOS File System to write and read from the I2C FRAM.

WICED HTTP Client

WICED HTTP & 943907 & CY3280 CapSense

Summary

In the previous articles I talked about the GE Hackathon, using WICED and CapSense, and finally creating a Particle Photon configuration.  In this article I will show you the WICED HTTP Client firmware which will read the button state and send it via WICED HTTP to the Particle Cloud.  To build this project I will start from the I2C Read firmware that I talked about in this article.

There are two parts of this application

  • The “main” application which reads the buttons and sends a message
  • The “sendMessage” function which builds a WICED HTTP message and sends it to the Particle cloud.

Main Application

I took the code from the previous example (CY3280 –> I2C –> WICED) and only made a few modifications (though I rearranged things a bit to make it easier to look at)

  • I joined the network (line 126)
  • I look up the IP address of the Particle Cloud (line 128)
  • Then I send a HIGH or LOW via the sendMessage function based on the state of the buttons (all the buttons do the same thing)
#include "wiced.h" 
#include <stdlib.h> 

#define I2C_ADDRESS (0x37) 
#define BUTTON_REG (0xAA) 
wiced_semaphore_t buttonPress; // used to signal in ISR to signal main
void application_start( )
{
    wiced_init();                                 // Initialize the WICED device
    wiced_rtos_init_semaphore(&requestSemaphore); // Initialize
    wiced_result_t result;

    wiced_network_up(WICED_STA_INTERFACE, WICED_USE_EXTERNAL_DHCP_SERVER, NULL);

    wiced_hostname_lookup( SERVER_HOST, &ip_address, DNS_TIMEOUT_MS, WICED_STA_INTERFACE );
    wiced_rtos_init_semaphore(&buttonPress);

    // WICED_GPIO_9 is the MBR3 Interrupt Pin
    wiced_gpio_init(WICED_GPIO_9,INPUT_PULL_UP);
    wiced_gpio_input_irq_enable(WICED_GPIO_9, IRQ_TRIGGER_FALLING_EDGE, button_isr, NULL); /* Setup interrupt */

    /* Setup I2C master */
    const wiced_i2c_device_t i2cDevice = {
            .port = WICED_I2C_2,
            .address = I2C_ADDRESS,
            .address_width = I2C_ADDRESS_WIDTH_7BIT,
            .speed_mode = I2C_STANDARD_SPEED_MODE
    };

    wiced_i2c_init(&i2cDevice);

    /* Tx buffer is used to set the offset */
    uint8_t tx_buffer[] = {BUTTON_REG};
    uint8_t buttonStatus;
    while ( 1 )
    {
        wiced_rtos_get_semaphore(&buttonPress,WICED_WAIT_FOREVER);

        // Do this until the MBR3 is alive.  It goes into deep sleep and wakes when you
        // send the first command.
        do {
            result = wiced_i2c_write(&i2cDevice, WICED_I2C_START_FLAG | WICED_I2C_STOP_FLAG, tx_buffer, sizeof(tx_buffer));
        }
        while(result != WICED_SUCCESS);

        result=wiced_i2c_read(&i2cDevice, WICED_I2C_START_FLAG | WICED_I2C_STOP_FLAG, &buttonStatus, sizeof(buttonStatus));
        if(buttonStatus > 0)
        {
            WPRINT_APP_INFO(("Sending On\n"));
            sendMessage("HIGH");
        }
        else
        {
            WPRINT_APP_INFO(("Sending Off\n"));
            sendMessage("LOW");
        }

    }
}

Send Message via WICED HTTP

The WICED HTTP sendMessage function simply

  • Creates a http_client (which is just a mechanism to keep track of an HTTP connection
  • Sets up a connection (lines 77-80)
  • Makes the connection (line 82)
  • Creates the message (line 88) in “application/x-www-form-urlencoded” format
  • Builds the HTTP headers for a HTTP “POST” (lines 90-105)
  • Write the Request (lines 108 –> 112)
  • Waits for the response using semaphore (line 114)
  • Destroys the connection (line 115 –> 116)
#include "wiced_tls.h" 
#include "http_client.h" 
#define SERVER_PORT ( 443 ) 
#define SERVER_HOST "api.particle.io" 
#define SERVER_RESOURCE "/v1/devices/2a001b000347353137323334/digitalwrite" 
#define PARTICLE_ACCESS_TOKEN "1311f9217a60" 
#define DNS_TIMEOUT_MS ( 10000 ) 
#define CONNECT_TIMEOUT_MS ( 3000 ) 
wiced_semaphore_t requestSemaphore; // used to signal request is done static http_client_t client; 
static http_request_t request; 
static http_client_configuration_info_t client_configuration; 
static wiced_ip_address_t ip_address; 

/* void sendMessage - Send HTTP request to turn on or off the LED
 */
void sendMessage( char *state )
{

    http_client_init( &client, WICED_STA_INTERFACE, event_handler, NULL );

    /* configure HTTP client parameters */
    client_configuration.flag = (http_client_configuration_flags_t)(HTTP_CLIENT_CONFIG_FLAG_SERVER_NAME | HTTP_CLIENT_CONFIG_FLAG_MAX_FRAGMENT_LEN);
    client_configuration.server_name = (uint8_t*)SERVER_HOST;
    client_configuration.max_fragment_length = TLS_FRAGMENT_LENGTH_1024;
    http_client_configure(&client, &client_configuration);

    http_client_connect( &client, (const wiced_ip_address_t*)&ip_address, SERVER_PORT, HTTP_USE_TLS, CONNECT_TIMEOUT_MS );

    http_header_field_t header[3]; // Three headers
    char messageBody[128];        // Enough to hold the message body
    char messageLengthBuffer[10]; // Enough to hold the characters for the Content-Length: header

    sprintf(messageBody,"access_token=%s&params=D7%%2C%s",PARTICLE_ACCESS_TOKEN,state);

    header[0].field        = HTTP_HEADER_HOST;
    header[0].field_length = sizeof( HTTP_HEADER_HOST ) - 1;
    header[0].value        = SERVER_HOST;
    header[0].value_length = sizeof( SERVER_HOST ) - 1;

#define MIME_FORM_URL "application/x-www-form-urlencoded"
    header[1].field        = HTTP_HEADER_CONTENT_TYPE;
    header[1].field_length = sizeof( HTTP_HEADER_CONTENT_TYPE ) - 1;
    header[1].value        =  MIME_FORM_URL;
    header[1].value_length = sizeof(  MIME_FORM_URL ) - 1;

    sprintf(messageLengthBuffer," %d",strlen(messageBody)); // Put the message body into the buffer so that you can strlen it
    header[2].field        = HTTP_HEADER_CONTENT_LENGTH;
    header[2].field_length = sizeof( HTTP_HEADER_CONTENT_LENGTH ) - 1;
    header[2].value        =  messageLengthBuffer;
    header[2].value_length = strlen(messageLengthBuffer);

    // Build the HTTP Message
    http_request_init( &request, &client, HTTP_POST, SERVER_RESOURCE, HTTP_1_1 );
    http_request_write_header( &request, &header[0], 3 ); // 3 headers
    http_request_write_end_header( &request );
    http_request_write(&request,(uint8_t*)messageBody,strlen(messageBody));
    http_request_flush( &request );

    wiced_rtos_get_semaphore(&requestSemaphore,10000); // wait up to 10 seconds to close the request and the client
    http_request_deinit(&request);
    http_client_deinit(&client);
}

WICED HTTP Event Handler

The way that the WICED HTTP  executes is that it has a worker thread waiting on the TCP socket.  When it gets a response it runs your callback function and tells you what happened.  In this case I just tell my thread to close the connection and move on.

/*
 * void event_handler() is called by the http_client function when
 *  Data is received from the server
 *  a connection is made
 *  a disconnect occurs
 *
 *  When data is received I assume that the response is good and I reset the semaphore so that another request can happen
 */

static void event_handler( http_client_t* client, http_event_t event, http_response_t* response )
{
    switch( event )
    {
        case HTTP_CONNECTED: // Dont do anything
        break;

        case HTTP_DISCONNECTED: // Disconnect if you get this event
            wiced_rtos_set_semaphore(&requestSemaphore);
        break;

        case HTTP_DATA_RECEIVED: // Disconnect if you get this event
            wiced_rtos_set_semaphore(&requestSemaphore);
        break;

        default:
        break;
    }
}

 

Particle Photon Configuration with Tinker Firmware

Summary

In the last article I wrote about using a CY3280 MBR3 Shield on a WICED WiFI 943907AEVAL1F development kit at the GE MegaHackathon.  In the next article I will show you the WICED HTTP firmware that I wrote to connect to the Particle Photon which they were using (I have written about Particle Photon before).  Obviously, I like Particle Photon because it is a WICED 43362 WiFi Radio.  In this article, I am going to show you how to get a Particle Photon going with the Tinker firmware.  Then test it with the iOS app, the web console and finally using CURL.  The CURL is just a mechanism to send HTTP Posts to the Tinker firmware, exactly what I will do in the next article on the WICED development kit.

Configure the Particle Photon

When you get a fresh Particle Photon out of the box you need to get it introduced to your WiFi network, and attached to your console.  To do this, start by going to setup.particle.io and following the process.

Particle Photon Configuration

 

Particle Photon Configuration

Particle Photon Configuration

Particle Photon Configuration

Particle Photon Configuration

Particle Photon Configuration

 

 

Particle Photon Configuration

 

 

Particle Photon Configuration

Testing with iPhone App

One you have “claimed” your Particle Photon and it is connected to the network, then you can talk to it with the Particle iOS app.  Here is what it looked like when I started the App on my phone.  You can see the device called “iotexpert-example” (remember that is what I named it from above).  The “Elkhorn_creek” Photon is the one that I wrote about in this article.

Particle Photon iOS App

Although the console says that I have the Tinker Firmware on the app, I wanted to make sure, so I use the iOS App to re-flash the Tinker Firmware.  You can do this by clicking the new device, then press the little “…” at the top right of the screen.  Finally click “Reflash Tinker”. It is awesome how fast that happens.

Particle Photon iOS Flash Firmware

Once I am sure about the version of the Tinker firmware, I test to make sure that things are working correctly.  First I click on “D7”

Particle Photon iOS Tinker App

Which brings up this screen where you can select digitalRead and digitalWrite.

Particle Photon iOS Tinker App

Then when you press the button it will switch from high to low and vice versa.

Particle Photon iOS Tinker App Particle Photon iOS Tinker App

You can also call the API directly by pressing “inspect” then “Data”

Particle Photon iOS digitalwrite Data Function

Particle Photon Console

In addition to using the iOS App, you can also interact with the Photon using the console.

Particle Photon Console

When I click on the “iotexpert-example” it brings up this screen where I can run the Tinker firmware functions.  In this case I ran “digitialwrite” with “D7,HIGH” which turns on the LED on the Photon.

Particle Photon Console

Testing the Particle Photon with CURL

The Particle Cloud exposes an API which lets you send Restful API requests to specific devices.  The Unix tool CURL lets me type command line requests (which I will mimic in the next Article using WICED).  The first command that I send is and HTTP GET which will return a JSON document that describes the configuration on my Photon.

curl https://api.particle.io/v1/devices/iotexpert-example?access_token=1311f67269d6

You can see the device name etc in the JSON below.  It also shows that the Tinker firmware has four function built into it.

{  
   "id":"2a001b000347353137323334",
   "name":"iotexpert-example",
   "last_app":null,
   "last_ip_address":"69.23.226.142",
   "last_heard":"2017-09-17T15:38:56.406Z",
   "product_id":6,
   "connected":true,
   "platform_id":6,
   "cellular":false,
   "notes":null,
   "status":"normal",
   "current_build_target":"0.5.3",
   "variables":{  

   },
   "functions":[  
      "digitalread",
      "digitalwrite",
      "analogread",
      "analogwrite"
   ]
}

Then I can send a HTTP POST using Curl to turn on the D7 LED.

 curl https://api.spark.io/v1/devices/2a001b000347354/digitalwrite -d access_token=1311f67269d66b -d params=D7,HIGH

You can see the Blue LED right next to D7 turns on.

Particle Photon

Particle Photon Tinker App

I wondered where the Tinker App API was documented?  It turns out that the App is available in Particle library.  You can search by typing “tinker”

The section of code that matters is here.  The function takes a “String” and parses it.  It demands that the 2nd character be a PIN number between 0 and 7.  The first character be a capital “D”.  Then you need to have a “HIGH” (in caps) or a “LOW” (in caps)

/*******************************************************************************
 * Function Name  : tinkerDigitalWrite
 * Description    : Sets the specified pin HIGH or LOW
 * Input          : Pin and value
 * Output         : None.
 * Return         : 1 on success and a negative number on failure
 *******************************************************************************/
int tinkerDigitalWrite(String command)
{
	bool value = 0;
	//convert ascii to integer
	int pinNumber = command.charAt(1) - '0';
	//Sanity check to see if the pin numbers are within limits
	if (pinNumber< 0 || pinNumber >7) return -1;

	if(command.substring(3,7) == "HIGH") value = 1;
	else if(command.substring(3,6) == "LOW") value = 0;
	else return -2;

	if(command.startsWith("D"))
	{
		pinMode(pinNumber, OUTPUT);
		digitalWrite(pinNumber, value);
		return 1;
	}
	else if(command.startsWith("A"))
	{
		pinMode(pinNumber+10, OUTPUT);
		digitalWrite(pinNumber+10, value);
		return 1;
	}
	else return -3;
}

In order to access the digitialwrite function via the network, they publish it (and some others).

/***
 * All the based tinker functions are registered. You can add you own code.
 ***/

// This #include statement was automatically added by the Spark IDE.
#include "Tinker.h"

void setup() {
	//Register all the Tinker functions
	Spark.function("digitalread", tinkerDigitalRead);
	Spark.function("digitalwrite", tinkerDigitalWrite);
	Spark.function("analogread", tinkerAnalogRead);
	Spark.function("analogwrite", tinkerAnalogWrite);
}

void loop() {
}

When I first thought about the Tinker firmware I thought that it must be reasonably complex.  But it is not because it takes advantage of the Particle cloud functionality.  All in all what they did is very elegant and simple..

Now that it looks like my Particle Photon is working, in the next article I will show you WICED firmware to read the CapSense buttons and then Turn On/Off the LED on the Photon.

CY3280 MBR3 & WICED CYW943907

Summary

In the last Article I talked about the GE Megahackathon.  One of the groups at the event got interested in using a CY3280 MBR3 to send signals via a WICED CYW943907 to the Particle IO server which was connected to a Particle Photon.  I helped them with the implementation and thought that it would be useful to show here.

CYW3280 & WICED CYW943907

Cypress CY3280 MBR3

The CY3280 MBR development kit is a CapSense demonstration kit that shows the Mechanical Button Replacement 3 chip.  It features 4 CapSense buttons with LEDs, a proximity sensor, and a buzzer.  It is connected to another MCU via the Arduino pins. of the WICED CYW943907.  The device sits on the I2C bus and acts as an I2C Slave.  You configure it using EZ Click.

When you run EZ Click you can setup the configure the internal registers of the MBR3 to make the board act like a bunch of different things.  In this case I turned on

  • The MBR buttons 1-4 (you can see them in the picture above)
  • The Flanking Sensor rejection which makes it so that you can only press one button at a time.
  • All of the automatic tuning features.

EZ-Click CY3280

Once the main CapSense is configured, I moved to the other part of the configuration where I setup

  • The 4 LEDs to toggle and be full brightness when on
  • The buzzer to buzz for 100ms at 4kHz when something happens
  • The host interrupt pin as CS15/SH/HI.  This made the Arduino pin D2 be an interrupt when something happened so that WICED would poll the MBR3

EZ-Click CY3280

Once these settings were all done, I downloaded the firmware configuration via the KitProg USB connector.  Then I tested it using the bridge control panel which I have shown you a bunch of different times in the past.  The MBR3 acts as an I2C slave.  To find out what the state of the buttons are you need to read register 0xAA.  The only little trick is that the chip goes to sleep to save power.  In order to wake it up you need to send an I2C transaction, which ends up getting NAK’d.  But the next transaction you send will be ACKd.  In the screenshot below you can see that I tried two of the buttons (0x08 and 0x20)

Bridge Control Panel

One problem that I had is that the power system of this board is setup to take 5V from the Arduino base board but the WICED development kit gives only 3.3v.  Here is a picture of the power system from the MBR3 schematic.

CY3280 Power Supply

The MBR3 can run on 3.3Vs.  In fact it can run all the way down to 1.7v and up to 5.5v, but for some reason (which I can’t remember) we made the board only work with 5.0v.  To fix this problem I removed J12 and then wired a wire from the 3.3V Arduino pin.  The wire is soldered onto the 3.3v pin, but has a female connector on the other side so that it can be plugged into J12.  Here is a picture:

CY3280

The last thing that I needed to do was move the jumpers to position “A” which made the host interrupt pin be connected to D2, and move the I2C jumpers so that the MBR3 was connected to the Arduino instead of the P5LP kitprog.  You can see that in the J3_scl and J3_sda in the picture above.

WICED CYW943907

The CYW934907AEVAL1F is an development kit for the Cypress 43907 MCU+WiFi module.  The WICED CYW943907 board can do dual band (2.4 and 5Ghz), 802.11 a/b/g/n,  Ethernet and a whole bunch of other stuff.

WICED CYW943907

The first firmware that I wrote in WICED Studio:

  • Sets up an ISR to unlock a semaphore when the interrupt occurs
  • Initialized WICED_GPIO_9 to be an input and connected to an ISR … this is also known as Arduino D2
  • Setup the I2C Master Hardware in the 43907
  • Wait for a semaphore (from the ISR)
  • Read the I2C register 0xAA from the MBR

The only trick in the firmware is that I read the I2C with a “do” loop until I get a valid result, meaning that the MBR3 has woken up.

#include "wiced.h"

#define I2C_ADDRESS (0x37)
#define BUTTON_REG (0xAA)

wiced_semaphore_t buttonPress;

/* Interrupt service routine for the button */
void button_isr(void* arg)
{
    wiced_rtos_set_semaphore(&buttonPress);
}

/* Main application */
void application_start( )
{
    wiced_init();	/* Initialize the WICED device */
    WPRINT_APP_INFO(("Started\n"));

    wiced_result_t result;
    wiced_rtos_init_semaphore(&buttonPress);

    // WICED_GPIO_9 is the MBR3 Interrupt Pin
    wiced_gpio_init(WICED_GPIO_9,INPUT_PULL_UP);
    wiced_gpio_input_irq_enable(WICED_GPIO_9, IRQ_TRIGGER_FALLING_EDGE, button_isr, NULL); /* Setup interrupt */

    /* Setup I2C master */
    const wiced_i2c_device_t i2cDevice = {
            .port = WICED_I2C_2,
            .address = I2C_ADDRESS,
            .address_width = I2C_ADDRESS_WIDTH_7BIT,
            .speed_mode = I2C_STANDARD_SPEED_MODE
    };

    wiced_i2c_init(&i2cDevice);

    /* Tx buffer is used to set the offset */
    uint8_t tx_buffer[] = {BUTTON_REG};
    uint8_t buttonStatus;

    while ( 1 )
    {

        wiced_rtos_get_semaphore(&buttonPress,WICED_WAIT_FOREVER);

        // Do this until the MBR3 is alive.  It goes into deep sleep and wakes when you
        // send the first command.
        do {
            result = wiced_i2c_write(&i2cDevice, WICED_I2C_START_FLAG | WICED_I2C_STOP_FLAG, tx_buffer, sizeof(tx_buffer));
        }
        while(result != WICED_SUCCESS);

        result=wiced_i2c_read(&i2cDevice, WICED_I2C_START_FLAG | WICED_I2C_STOP_FLAG, &buttonStatus, sizeof(buttonStatus));
        WPRINT_APP_INFO(("Button State = %X\n", buttonStatus)); /* Print data to terminal */
    }
}

Once that is programmed I program and test the firmware.

Testing WICED CYW943907

In the next article I will modify all of this firmware and make the WICED CYW943907 send data via HTTP to the Cloud.

Cypress Development Kits & the GE Mega Hackthon

Summary

I spent this weekend attending the GE Mega Hackathon at GE FirstBuild.  First Build is a Maker Space-ish place in Louisville that is sponsored by GE and Louisville Speed School.  The Hackathon was called “Hack the Home” and was a two day thing where teams of makers built stuff for the house… generally by modifying GE white goods. Nicholas, my lab assistant, and I brought a bunch of Cypress Development Kits for people to use… then we helped them modify the kits to put them in their hacking projects.

Nicholas with the pile of Cypress Development Kits Cypress Development Kits

At the table next to us were two guys from OnShape which is a cloud based 3-d drawing application.  It is super cool and free to use for non-comercial applications.  Nicholas is totally into 3-D printing and has been using Tinker CAD, which is cool… and free… but is still mostly a toy.  OnShape on the other hand is a fully featured pro package.  Philip, one of their applications engineers, helped Nicholas get going.

Nicholas & OnShape

I brought a bunch of different Cypress Development Kits, but what got people really interested was CapSense.  I had three different Capsense kits which fired peoples imagination…. first, the CY8CKIT-145 (which I have written extensively about) has three buttons and a slider… plus LEDs and a Bluetooth module on the back.

CY8CKIT-145
The CY8CKIT-024 Proximity shield which works with most any of the Pioneer kits.

CY8CKIT-024

And finally the CY3280 MBR3 development kit.  This has 4 capsene buttons, a buzzer and a proximity loop… in an Arduino shield format factor.  To talk to the shield you use I2C.

CY3280 Cypress Development Kits

What is really cool is that you don’t have to write firmware as you just configure it with EZ-Click.

EZ Click

Several people used it, including this guy who was talking to it with a Raspberry Pi.

CY3280

One of the team used a CYW943907AEVAL1F talking to a CY3280 Capsense talking through cloud to a Particle Photon.  I helped them with the firmware, which I will go through in detail in the next article.

FreeRTOS PSoC Template Project

Summary

In the last article I showed you clever FreeRTOS PSoC Component… and the talked about some of the issues that I had with it.  In this article I will talk about a self-contained FreeRTOS PSoC Template project that includes everything for FreeRTOS and Tracealyzer all in one project.  My idea was that when I start a new project I will just make a copy of the template project, rename it, then move on.

My FreeRTOS PSoC Template has

  • FreeRTOS with the files in in the same directory (i.e. not referenced externally)
  • Tracealyzer with the files in the same directory & all of the streamports including RTT and the UART DMA
  • All of the files organized into PSoC Creator folders
  • A template main.c
  • All of the build settings configured

This project is checked into GitHub and you can find it git@github.com:iotexpert/PSoC-FreeRTOS-Template.git

Building the FreeRTOS PSoC Template

I started the process by creating a blank PSoC project called “FreeRTOS_Template”.  I then went into the Windows Explorer and copied the entire FreeRTOS source directory into the FreeRTOS PSoC Template Project directory.  Then I copied the Percepio TraceRecorder library into the FreeRTOS PSoC Template project.

FreeRTOS PSoC Template Directory Structure

By having both of the source directories in my project it isolated this project from changes in the FreeRTOS or the TraceRecorder.  Obviously that is a double edged sword.  The next thing that I did was use the Windows Explorer to copy FreeRTOSConfig.h, trcConfig.h, trcSnapshotConfig.h and trcStreamingConfig.h into the project.   Once all of the files were in my project directory is was time to fix up the PSoC Creator Project.

To do this I created a folder called “FreeRTOS_Source” in the “Header Files” and “Source Files” folders in my template project.  You can do this by right clicking and selecting “Add->New Folder”.  Then I added all of the appropriate .h and .c files from FreeRTOS source directory.  This gives me the following project view:

FreeRTOS PSoC Template PSoC Creator Header Files

And Source Files (notice that I also added heap_4.c which I generally use for memory management)

FreeRTOS PSoC Template PSoC Creator Source Files

Then I add the configuration files FreeRTOSConfig.h, trcConfig.h, trcSnapshotConfig.h, trcStreamingConfig.h and trcStreamingport.h.  Next I do the same thing for the TraceRecorder library which makes my project look like this:

Then I modify the build settings to add the include directories:

FreeRTOS PSoC Template Build Settings

FreeRTOS PSoC Template PSoC Creator Include Path

Now you can modify the FreeRTOSConfig.h to include all of the Tracealyzer stuff:

/* A header file that defines trace macro can be included here. */
#if ( configUSE_TRACE_FACILITY == 1 )
#include "trcRecorder.h"
#endif

#endif /* FREERTOS_CONFIG_H */

Then I setup a new tab in the schematic to contain the DMA UART Streamport.  You can read all about the UART DMA Streamport in this article.

FreeRTOS PSoC Template PSoC Creator Streamport Schematic

By putting that part of the stream port on a separate schematic page I can now do a right click and disable the page when I am not using the Tracealyzer streamport.  Disabling a page of the schematic completely removes everything from the build.

PSoC Creator Schematic Disable Settings

Next I create files called FreeRTOS_Start.h/.c to put in the startup code:

#include <project.h>
#include "FreeRTOS.h"

extern void xPortPendSVHandler(void);
extern void xPortSysTickHandler(void);
extern void vPortSVCHandler(void);

#define CORTEX_INTERRUPT_BASE          (16)
void FreeRTOS_Start()
{
    /* Handler for Cortex Supervisor Call (SVC, formerly SWI) - address 11 */
    CyIntSetSysVector( CORTEX_INTERRUPT_BASE + SVCall_IRQn,
        (cyisraddress)vPortSVCHandler );
    
    /* Handler for Cortex PendSV Call - address 14 */
	CyIntSetSysVector( CORTEX_INTERRUPT_BASE + PendSV_IRQn,
        (cyisraddress)xPortPendSVHandler );    
    
    /* Handler for Cortex SYSTICK - address 15 */
	CyIntSetSysVector( CORTEX_INTERRUPT_BASE + SysTick_IRQn,
        (cyisraddress)xPortSysTickHandler );
}

Finally I make a template main.c that starts everything and has a simple ledTask and instructions for changing Memory Management scheme and the TraceRecorder.

// This template has heap_4.c included in the project.  If you want a 
// different heap scheme then remove heap_4 from the project and add 
// the other scheme from FreeRTOS/Source/portable/memmag

// TraceRecorder
// There are methods
// 1. Snapshot mode
// 2. Streaming UART/DMA
// 3. Streaming JLINK RTT
//
// To use method 1: 
// - in FreeRTOSConfig.h make this line be 1 (currently line 45)
//#define configUSE_TRACE_FACILITY                1
// - in trcConfig.h configure the TRC_CFG_RECORDER 
// #define TRC_CFG_RECORDER_MODE TRC_RECORDER_MODE_SNAPSHOT
//
// To use method 2:
// - in FreeRTOSConfig.h make this line be 1 (currently line 45)
//#define configUSE_TRACE_FACILITY                1
// - in trcConfig.h configure the TRC_CFG_RECORDER
//#define TRC_CFG_RECORDER_MODE TRC_RECORDER_MODE_STREAMING
//
// This project currently has the PSoC UART Streaming Port
// add the TraceRecorder/streamports/PSoC_Serial/trcStreamingPort.c to the project
// add the TraceRecorder/streamports/PSoC_Serial/include/trcStreamingPort.h
// add the TraceRecorder/streamports/PSoC_Serial/include to the compiler include directories
// Enable the Trace_DMA schematic sheet and make sure UART pins are assigned correctly
// This port depends on the UART being named UART and the DMA being named "DMA"
//
// To use method 3: JLINK RTT
// Remove the previous streamport files from the project
// Remove the Streamport include path
// add the TraceRecorder/streamports/JLink_RTT/Segger_RTT.c to the project
// add the TraceRecorder/streamports/JLink_RTT/Segger_RTT_Printf.c to the project
// add the TraceRecorder/streamports/JLink_RTT/include/trcStreamingPort.h
// add the TraceRecorder/streamports/JLink_RTT/include/Segger_RTT.h
// add the TraceRecorder/streamports/JLink_RTT/include/Segger_RTT_Conf.h
// add the TraceRecorder/streamports/JLink_RTT/include to the compiler include directories


#include "project.h"
#include "FreeRTOS.h"
#include "timers.h"

// An example Task
void ledTask(void *arg)
{
    (void)arg;
    while(1)
    {
        RED_Write(~RED_Read());
        vTaskDelay(500);  
    }
}

int main(void)
{
    CyGlobalIntEnable;
    FreeRTOS_Start();
    
    #if ( configUSE_TRACE_FACILITY == 1 )
    vTraceEnable(TRC_START);
    #endif
    
    xTaskCreate(ledTask,"LED Task",configMINIMAL_STACK_SIZE,0,1,0);
    vTaskStartScheduler();  // Will never return
    while(1);               // Eliminate compiler warning
}

 

Topic Description
FreeRTOS: A PSoC4 FreeRTOS Port An introduction to making FreeRTOS work on PSoC 4
FreeRTOS PSoC Examples Using multiple tasks in FreeRTOS
FreeRTOS Queue Example Using a queue to communicate between tasks
PSoC 6 FreeRTOS - The First Example Booting FreeRTOS on PSoC 6
FreeRTOS Binary Semaphore An first example of a binary semaphore
FreeRTOS Binary Semaphore (Part 2) Removing polling in the UART Task
FreeRTOS Counting Semaphore An example using a counting semaphore
PSoC FreeRTOS Reading I2C Sensors with a shared I2C Bus
PSoC FreeRTOS Task Notify A light weight scheme to replace Semaphores
PSoC FreeRTOS Task Notification Values A very light weight method to transfer one word of information into a task

FreeRTOS PSoC Component

Summary

This weekend I found myself down a rabbit hole, beating my head on the wall trying to make a USB driver work properly inside of Parallels & Windows 10 on my Mac (which I still don’t have quite right).  While going through that excruciating process I ended up creating 3-4-5 different FreeRTOS PSoC projects, which although not difficult, is still a bit of a pain as it requires 1/2 dozen step.  After reflecting on it a while I decided that I needed something easier.  The obvious thing to do was to build a FreeRTOS PSoC Component, which I did, but eventually abandoned (Ill talk about that process in the next section).  After the component idea was abandoned I decided to just make a template project that could be used to start a FreeRTOS PSoC Project (the next Article).

In this article I will show you:

  • An example project using a clever FreeRTOS PSoC Component that I found on GitHub built by E2ForLife
  • A discussion of the implementation details of that FreeRTOS PSoC Component
  • A discussion of problems with that implementation which lead me to build a template project.

FreeRTOS PSoC Component Example Project

When I first started looking at FreeRTOS I wasn’t totally sure where to start.  When I googled FreeRTOS PSoC, one of the first hits was this repo which contains a PSoC Component that was built by “E2ForLife”.  I really liked the idea of a component based FreeRTOS implementation, as all you would need to do is place the components… and then away you go.  The more that I looked at the component the more that I liked what E2ForLife had done.  When I cloned his repo, there was “nothing” in it, but it turns out there is another branch called “Implement-PSoC5” which makes me think that he was partially done (he hasn’t been changed since August 2015)

First, his example project.  When you look at the schematic you see a nice looking FreeRTOS PSoC Symbol (obviously E2ForLife draws way better than me).

FreeRTOS PSoC Component

When you double click the component you see all of the stuff that is normally in FreeRTOSConfig.h which you can set using the GUI instead of the FreeRTOSConfig.h

FreeRTOS PSoC Component Configuration

When you “Generate Application” you can see that he setup all of the FreeRTOS files to come into the Generated Source automatically (though with different names)

FreeRTOS PSoC Component API

And his FreeRTOS PSoC Component example project is straight forward

#include <project.h>

xTaskHandle redTask;
xTaskHandle blueTask;
xTaskHandle greenTask;

void vRedTask( void* pvParameters);
void vGreenTask( void* pvParameters);
void vBlueTask( void* pvParameters);

int main()
{
    CyGlobalIntEnable; /* Enable global interrupts. */

	xTaskCreate(vRedTask,"red",80,NULL,3,&redTask);
	xTaskCreate(vGreenTask,"green",80,NULL,3,&greenTask);

	FreeRTOS_Start();
	
    for(;;);
}

void vRedTask( void* pvParameters)
{
	for(;;) {
		vTaskDelay( 125/portTICK_RATE_MS );
		RED_Write( ~RED_Read() );
	}
}

void vGreenTask( void* pvParameters)
{
	for(;;) {
		vTaskDelay( 219/portTICK_RATE_MS );
		GREEN_Write( ~GREEN_Read() );
	}
}

He built a function called “FreeRTOS_Start()” which installs the interrupt vectors then starts up the scheduler.

uint8 FreeRTOS_initVar = 0;

/* ------------------------------------------------------------------------ */
void FreeRTOS_Init( void )
{
    /* Handler for Cortex Supervisor Call (SVC, formerly SWI) - address 11 */
    CyIntSetSysVector( CORTEX_INTERRUPT_BASE + SVCall_IRQn,
        (cyisraddress)vPortSVCHandler );
    
    /* Handler for Cortex PendSV Call - address 14 */
	CyIntSetSysVector( CORTEX_INTERRUPT_BASE + PendSV_IRQn,
        (cyisraddress)xPortPendSVHandler );    
    
    /* Handler for Cortex SYSTICK - address 15 */
	CyIntSetSysVector( CORTEX_INTERRUPT_BASE + SysTick_IRQn,
        (cyisraddress)xPortSysTickHandler );
	
	FreeRTOS_initVar = 1;
}
/* ------------------------------------------------------------------------ */
void FreeRTOS_Enable( void )
{
	/* start the scheduler so the tasks will start executing */
	vTaskStartScheduler();	
}
/* ------------------------------------------------------------------------ */
void FreeRTOS_Start( void )
{
	if (FreeRTOS_initVar == 0) {
		FreeRTOS_Init();
	}
	FreeRTOS_Enable();
	
	/*
	 * After the scheduler starts in Enable(), the code should never get to
	 * this location.
	 */
	for (;;);
}

And when you run the FreeRTOS PSoC Component project you get the nice blinking LED (Red and Green)

CY8CKIT-042

FreeRTOS PSoC Component

After downloading the project, then opening it I first wanted to look at the components.  You can do this by clicking the “Components” tab in the workspace explorer.  It looks like he created (or was planning to create) several other components in addition to the “FreeRTOS”.

FreeRTOS PSoC Component

When you double click on the “FreeRTOS_v8_2.cysym” you will get an editable view of the symbol.

FreeRTOS PSoC Component Symbol

When you right click on the blank part of the canvas, PSoC Creator will bring up this menu.

PSoC Creator Configuration

On the properties menu you can configure which tab the component belongs to in the Component Catalog.  In this case he created a tab called “Community” which looks like this in the actual Component Catalog.

PSoC Creator Component Catalog

To make that happen he setup the “Doc.CatalogPlacement” to be “Community/Operating System/FreeRTOS” (on the properties menu)

FreeRTOS PSoC Component Parameter Configuration

The next thing that he did was add a whole bunch of Symbol Parameters which will let the user change the setup of FreeRTOS. Each  of these parameters show up as an editable field on the component customers (in the schematic).

FreeRTOS PSoC Parameter

In the picture above you can see that he created two new “enumerated” datatypes called “FreeRTOS_CheckStackOverFlowType” “FreeRTOS_MemMangType”.  In the picture below you can see the legal values for that type.  This lets him restrict the things that the user of the component can select when he places it in his schematic.

FreeRTOS PSoC Component Configuration

Here is what the component looks like when the user actually uses it.  You can see the legal fields (from above) and the legal values for those fields (from above)

FreeRTOS PSoC Component Configuration

The next thing that he did was copy all of the FreeRTOS files into component API.

FreeRTOS PSoC Component API

If you remember each FreeRTOS project needs to have a file called “FreeRTOSConfig.h”.  But, that file doesn’t appear to exist in the list above.  How is that?  Remember that when PSoC Creator builds a project it copies the API into your generated source directory, but it renames each of the files to be INSTANCE_NAME_filename.  In this example, “Config.h” will become “FreeRTOS_Config.h” (FreeRTOS is the instance name in the schematic)

In FreeRTOS each of the features of the RTOS turn into a #define that is 0 or 1.  When the component was created he modified “Config.h” so that each of the parameters on the component set values for the #defines in the “Config.h” file.  And there is a bunch of them so that must have taken a good bit of work.  Here is an example of a section of his “Config.h”.  Each place you see the back-tick $parameter back-tick PSoC Creator will substitute the value of the parameter (I am typing back-tick because WordPress interprets the actual symbol to mean something special and I don’t know how to get it into the text)

#if CY_PSOC4
    
    /* Port-dependent settings - not user-editable */
    #define configCPU_CLOCK_HZ          ( ( unsigned long ) CYDEV_BCLK__SYSCLK__HZ )
        
    /* Application settings - user editable */
    #define configMAX_PRIORITIES		( `$MAX_PRIORITIES` )
    #define configTOTAL_HEAP_SIZE		( `$TOTAL_HEAP_SIZE` )
    
#elif CY_PSOC5
    
    /* Device settings - not user-editable */
    #define configCPU_CLOCK_HZ			( ( unsigned long ) BCLK__BUS_CLK__HZ )
        
    /* Application settings - user editable */
    #define configMAX_PRIORITIES        ( `$MAX_PRIORITIES` )
    #define configTOTAL_HEAP_SIZE		( `$TOTAL_HEAP_SIZE` ) 
    
#else
    
    #error "This FreeRTOSConfig.h file is for PSoC 4 and PSoC 5LP devices only"
    
#endif

#define configUSE_PREEMPTION			`$USE_PREEMPTION`
#define configUSE_IDLE_HOOK				`$USE_IDLE_HOOK`
#define configUSE_TICK_HOOK				`$USE_TICK_HOOK`
#define configTICK_RATE_HZ				( ( portTickType ) `$TICK_RATE_HZ` )

Because each filename changes name, he had to go fix all of the #includes to look like this example from croutine.c (this was a bunch of work)

/* PSoC Component Customizations */

#include "`$INSTANCE_NAME`.h"
#include "`$INSTANCE_NAME`_task.h"
#include "`$INSTANCE_NAME`_croutine.h"

He also wanted to be able to have all of the FreeRTOS memory management schemes included in the project at one time.  To solve this problem he put an #if around all of the code in heap_1, heap_2 … that adds and removes the appropriate memory manager.

#if (`$MemManager` == 2)

.
.
.
.
.

#endif

A FreeRTOS PSoC Template Project

When I started working on FreeRTOS I knew that I wanted to use V9.0.  But the component was setup for V8.2.  So I launched into the process of converting the component.  This turned out to be a colossal pain in the ass because of the massive number of “small” changes.  In addition I didn’t really like having to change the names of key files (even the stupidly named semphr.h).  Moreover, the source code as a component debate was raging wildly inside of Cypress and in general is on the way out.  So I decided to implement this as a template project instead of a component.

All that being said, what E2ForLife did I continue to think was really clever.

Topic Description
FreeRTOS: A PSoC4 FreeRTOS Port An introduction to making FreeRTOS work on PSoC 4
FreeRTOS PSoC Examples Using multiple tasks in FreeRTOS
FreeRTOS Queue Example Using a queue to communicate between tasks
PSoC 6 FreeRTOS - The First Example Booting FreeRTOS on PSoC 6
FreeRTOS Binary Semaphore An first example of a binary semaphore
FreeRTOS Binary Semaphore (Part 2) Removing polling in the UART Task
FreeRTOS Counting Semaphore An example using a counting semaphore
PSoC FreeRTOS Reading I2C Sensors with a shared I2C Bus
PSoC FreeRTOS Task Notify A light weight scheme to replace Semaphores
PSoC FreeRTOS Task Notification Values A very light weight method to transfer one word of information into a task

PSoC FreeRTOS Task Notification Value

Summary

In the previous article I showed you how to use the FreeRTOS task notification mechanism to replace a binary semaphore.  In this article I will build PSoC FreeRTOS Task Notification Value firmware.  Every FreeRTOS task has one built-in “uint32_t” which you can use to pass information between the task that sends the notification and the task that receives the notification.  In this article, instead of using the task notification as a binary semaphore, I will use it as a Queue of depth 1 that can hold one 32-bit word.  I will also show you a lesson that I learned about the interrupt registers in the SCB UART.

PSoC FreeRTOS Task Notification Value

I start by copying the project 9-TaskNotify and calling it 10-TaskNotifyValue.  I thought that it would be interesting to pass the cause of the UART interrupt to the UART Task, so that it could be told to the user.  To do this I call “xTaskNotifyFromISR” instead of “vTaskGiveFromISR”.   This function lets me set the value of the FreeRTOS Task notification value, is case to the bit mask of the cause of the UART interrupt.  The function also lets you specific if you want to

  • eNoAction – don’t do anything (this is what the xTaskNotifyFromISR does)
  • eSetBits – or the current notification value with the value you send
  • eIncrement – increment the notification value by 1 (in which case it ignore the value you send)
  • eSetValueWithOverwrite – replace the current notification value with the value passed in this function
  • eSetValueWithoutOverwrite – if there is no pending write, then write the value from this function into the notification value

In the UART_Task I take the value and then clear all of the bit (aka set it to 0) when I exit.

CY_ISR(uartHandler)
{
    uint32_t intrBits = UART_GetRxInterruptSourceMasked();
    UART_SetRxInterruptMode(0); // Turn off the Rx interrupt
    BaseType_t xHigherPriorityTaskWoken;
    xTaskNotifyFromISR( uartTaskHandle,intrBits,eSetValueWithOverwrite,&xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
void UART_Task( void *arg)
{
    (void)arg;
    char c;
    UART_Start();
    UART_SetCustomInterruptHandler(uartHandler);
    while(1)
    {
        uint32_t intrBits;
              
        xTaskNotifyWait( 0x00,         /* Don't clear any bits on entry. */
                         ULONG_MAX,          /* Clear all bits on exit. */
                         &intrBits, 
                         portMAX_DELAY );    /* Block indefinitely. */
      
        switch(intrBits)
        {
            case UART_INTR_RX_NOT_EMPTY:
                UART_UartPutString("Interrupt: FIFO Not Empty\n");
            break;
            
            case UART_INTR_RX_ERR:
                UART_UartPutString("Interrupt: Error\n");
            break;
                
            case UART_INTR_RX_FULL:
                UART_UartPutString("Interrupt: FIFO Full\n");
            break;
            
            default:
                UART_UartPutString("Interrupt: Unknown\n");
            break;
        }
        
        while(UART_SpiUartGetRxBufferSize())
        {
            c = UART_UartGetChar();
            UART_UartPutString("Char = ");
            UART_UartPutChar(c);
            UART_UartPutString("\n");
        }
        // re-enable the interrupt
        UART_ClearRxInterruptSource(UART_INTR_RX_NOT_EMPTY);
        UART_SetRxInterruptMode(UART_INTR_RX_NOT_EMPTY);
    }
}

New Learning

When I first wrote the program I had something “weird” happening.  Specifically it looked like I was getting the interrupt service routine called twice:

I originally wrote the code like this:

CY_ISR(uartHandler)
{
    uint32_t intrBits = UART_GetRxInterruptSourceMasked();
    UART_SetRxInterruptMode(0); // Turn off the Rx interrupt
    UART_ClearRxInterruptSource(UART_INTR_RX_NOT_EMPTY);
    BaseType_t xHigherPriorityTaskWoken;
    xTaskNotifyFromISR( uartTaskHandle,intrBits,eSetValueWithOverwrite,&xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}

But, what happens is:

  1. Turn off interrupts
  2. Clear the interrupt source (meaning turn off the flag in the SCB that says there is a character in the Rx Buffer)
  3. One or so UART clock cycles later the flag is reset (because there is still something in the UART Rx Buffer)
  4. Send the notification to the UART Task
  5. The UART Task wakes up and processes the UART Rx Buffer
  6. The UART Task turns back on the interrupts
  7. The interrupt is called because the RX_NOT_EMPTY flag is still set (it is set until it is clear)
  8. The interrupt handler clears the flag (which isn’t reset this time because there is nothing in the Rx buffer)
  9. The interrupt handler sends the notification
  10. The UART Task wakes up again… prints out the Flag..
  11. The UART Task tries to read out of the Rx Buffer… but there isn’t anything in it.

Each time I start thinking that I know what I am doing, I find something else to learn.  I suppose that is what makes this whole thing fun though.

Topic Description
FreeRTOS: A PSoC4 FreeRTOS Port An introduction to making FreeRTOS work on PSoC 4
FreeRTOS PSoC Examples Using multiple tasks in FreeRTOS
FreeRTOS Queue Example Using a queue to communicate between tasks
PSoC 6 FreeRTOS - The First Example Booting FreeRTOS on PSoC 6
FreeRTOS Binary Semaphore An first example of a binary semaphore
FreeRTOS Binary Semaphore (Part 2) Removing polling in the UART Task
FreeRTOS Counting Semaphore An example using a counting semaphore
PSoC FreeRTOS Reading I2C Sensors with a shared I2C Bus
PSoC FreeRTOS Task Notify A light weight scheme to replace Semaphores
PSoC FreeRTOS Task Notification Values A very light weight method to transfer one word of information into a task

PSoC FreeRTOS Task Notify

Summary

I have been writing a bunch of articles about implementing PSoC FreeRTOS so, this morning I was reading the FreeRTOS manual (yes I am one of those…) and I noticed a section in the API guide that I hadn’t see before… Task Notifications.  Every task in the FreeRTOS has a built in 32-bit integer notification value.  This value is super light weight and can be used like a task specific counting semaphore, or a signaling bit mask, or binary semaphore.  The API includes:

It seems like this API is good for the situations when your Semaphore has a specific task target in mind.  I thought that this would be a perfect scheme to have a PSoC FreeRTOS UART ISR signal the UART Handling task that there is data available to do something with.

Setup the PSoC FreeRTOS Project

I start this process by making a copy of “1-BlinkingLED” (which already has all of the FreeRTOS stuff in it) and naming it “9-TaskNotify”.  Then I add a UART to the schematic and name it “UART”

PSoC FreeRTOS Schematic

I attach the UART to the right pins on the CY8CKIT-044 kit.

PSoC Creator Pin Assignment
Next I turn on the interrupt which will be called when there is data in the receive FIFO.

PSoC UART Configuration

PSoC FreeRTOS UART Code

Now that the schematic is all configured I update my firmware.  The function “uartHandler” is called when there is data in the UART RX FIFO.  It turns of the interrupts for the UART (which I will turn back on after I have cleared the data in the input buffer), clears the interrupt  (so that it will stop pending) and then sends the notification to the UART_Task.

The UART Task just registers the handler… then while(1)’s until the end of time.  It waits for a notification, then reads data out of the RX fifo and puts out,  then re-enables the interrupts.

CY_ISR(uartHandler)
{
    BaseType_t xHigherPriorityTaskWoken;

    // disable the interrupt
    UART_SetRxInterruptMode(0);
    vTaskNotifyGiveFromISR(uartTaskHandle,&xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}

void UART_Task( void *arg)
{
    (void)arg;
    char c;
    UART_Start();
    UART_SetCustomInterruptHandler(uartHandler);
    while(1)
    {
        ulTaskNotifyTake(pdTRUE,portMAX_DELAY);
        while(UART_SpiUartGetRxBufferSize())
        {
            c = UART_UartGetChar();
            UART_UartPutChar(c);
        }
        // clear & re-enable the interrupt
        UART_ClearRxInterruptSource(UART_INTR_RX_NOT_EMPTY);
        UART_SetRxInterruptMode(UART_INTR_RX_NOT_EMPTY);
    }
}

Topic Description
FreeRTOS: A PSoC4 FreeRTOS Port An introduction to making FreeRTOS work on PSoC 4
FreeRTOS PSoC Examples Using multiple tasks in FreeRTOS
FreeRTOS Queue Example Using a queue to communicate between tasks
PSoC 6 FreeRTOS - The First Example Booting FreeRTOS on PSoC 6
FreeRTOS Binary Semaphore An first example of a binary semaphore
FreeRTOS Binary Semaphore (Part 2) Removing polling in the UART Task
FreeRTOS Counting Semaphore An example using a counting semaphore
PSoC FreeRTOS Reading I2C Sensors with a shared I2C Bus
PSoC FreeRTOS Task Notify A light weight scheme to replace Semaphores
PSoC FreeRTOS Task Notification Values A very light weight method to transfer one word of information into a task