Matrix Orbital GTT43A: PSoC 4 Interface


In the last several articles I have written about how to use and talk to the Matrix Orbital GTT43A.  Now it is time to write some code.  The PSoC4 program that I am going to show you has evolved over time as I added stuff to it.  For instance, while I was working on this program I ran into a problem where the I2C Bus would hang (the subject of the next article).  As such, some of the code that is in this program was written to help me debug that problem.  With that said, I wanted a program that:

  1. Is command line driven i.e. I can interact with my program via serial commands through the PC COM Port
  2. Can read 1 byte at a time (like I do on the bridge control panel)
  3. Can test the “read whole packet” code
  4. Can selectively send commands via a I2C or the UART
  5. Send test commands to the display e.g. reset, clear
  6. Test the display generated messages (like button presses)

All of this code was built to run on the CY8CKIT-044 which has a PSoC 4200M MCU

Schematic & Pin Assignment

All PSoC 4 projects start with a schematic.  In my schematic I have a UART setup to talk to the KitProg (called UART) and serve as the command processor, an I2C which directly attaches to the I2C bus that drives the display, and a UART that is also attached to the display which I called SCRUART.

The I2CFAIL pin in the schematic I used to help me debug the I2C problem (the subject of the next article)

PSoC 4200m Schematic

The pin assignment has the UART attached to the KitProg UART, the I2C attached to KitProg and the Display.  The SCRUART is attached to UART on the Display.

PSoC 4200M Pin Assignment


Main Event Loop

The main event loop has the following parts

  1. Read a character from the keyboard
  2. Process the keyboard command character
  3. Read data from the screen
    1. If you are in packet mode read a whole packet
    2. If you are in streaming mode read one byte

There are three system modes.

  1. IDLE = Dont read from the screen
  2. PACKET = Read whole packets (poll for complete packets)
  3. STREAMING = read bytes (polling)

I also have setup the program to read/write bytes to the UART and I2C.  This is called the “comInterface”.

The enumerated type systemMode is used to setup the polling mode (each time through the main loop, what does it do?).

The actual main section of the code

  1. Starts by initializing the UART, SCRUART and I2C.
  2. On line 299 it reads a character, then switches on the character to figure out which command the user has type.

You can see that ‘u’ and ‘U’ change the communication interface from UART to I2C and back.

The end of the loop handles the “?” case… in other words print out all of the commands.  Then based on the system mode, it either reads a whole message packet from the display or it reads only byte.

I created three keys (0,1,2) to change the system mode, from IDLE, to reading whole packets to reading bytes.

While I was trying to figure out how things worked I wanted to be able to do one thing at a time. So I create ‘r’ to read one byte (like Bridge Control Panel) and ‘p’ to read a whole packet.  Notice that you really really only want to do this why you are not polling the display.

The last section of commands send various GTT2.0 commands to the display.  Notice that the writePacket function knows which system interface to use (either I2C or UART).

First, I declare some commands, just an array of bytes.

Then I use them:

Read Byte

In order to read one byte from the display I first determine which mode Im in, then call the appropriate sub-function.

The first sub function to read bytes via I2C.  To read a byte with no error checking you have to

  1. Send a Start
  2. Send the address
  3. Send the Read bit
  4. Clock it 8 times (this is exactly what the I2CMasterReadByte function does)
  5. Send an NAK
  6. Send a Stop

I ran into an I2C issue which I will talk about in the next article, however, if I see an error from any of these commands Ill put the system into MODE_IDLE and throw an error.  In addition I write a 1 to the I2CFAIL pin, which I am using to trigger the Oscilliscope (so I can see what is happening)

Read Packet

For the packet read code I did the same thing as the byte read code.  Specifically I wrote an overall get packet, then called the correct read packet based on the

If you read the source code that Matrix Orbital gives you for drivers, you will find that it reads one byte at a time.  The problem with doing this is that you

  1. Send a start
  2. Send an I2C address
  3. Send a read bit
  4. Read the ACK
  5. Read a byte
  6. Send a NAK
  7. Send a stop

The problem with this approach is that it uses 11 bit-times extra per byte of overhead (steps 1-4) which kinda sucks.  So I wanted to write a complete packet reader.  My packet reader will

  1. Send a start
  2. Send an I2C address
  3. Send a read bit
  4. Read the ACK
  5. Read a byte  [This is the 254 that marks the start of the packet]
  6. ACK
  7. Read a byte [This is the command which identifies the packet]
  8. ACK
  9. Read a byte [The MSB of the Length]
  10. ACK
  11. Read a byte [The LSB of the Length]
  12. NAK
  13. If there is a length then:
  14. Send the start
  15. Send an I2C address
  16. Send a read bit
  17. Read the ACK
  18. read length -1 bytes
  19. ACK
  20. Read the last byte
  21. Send a NAK
  22. Send a stop

By spec you are supposed to NAK your last read byte to indicate that your read transaction is over… that means you have to NAK the last Length byte because there could be 0 bytes to read, in which case you would need to stop.  It would have been nice if the protocol let you send only one start, but Im pretty sure it was designed for UART, which doesn’t suffer from this problem.  Also as a side note, Im pretty sure that the MCU they are using doesn’t really care, but Im not willing to implement it incorrectly.

Here is the code:

You can "git" these projects from

And the driver library from

Matrix Orbital GTT43: A Cool Display
Matrix Orbital GTT43A: Serial Interface
Matrix Orbital GTT43A: GTT Scripts
Matrix Orbital GTT43A: A PSoC 4 Interface
Matrix Orbital GTT43A: Debugging the I2C
Matrix Orbital GTT43A: GTT Driver Library - Part 1
Matrix Orbital GTT43A: GTT Driver Library - Part 1
Matrix Orbital GTT43A: PSoC 6 using RTOS and the GTT Driver Library

The Lost Art of Assembly Language Programming

Cypress introduced it’s first mass market microcontroller in 2001. It used a Cypress designed 8 bit CISC processor running at 24 MHz, with as little as 4 KB Flash and 256 bytes RAM. Wrapped around that was a neat array of programmable analog and digital blocks. This may not sound like much, but with a creative mindset you could get these parts to do amazing things. For instance, I once implemented a complete ultrasonic ranging sensor with full wave analog demodulation in a single PSOC1 as shown below.

PSOC1 Ultrasonic Ranging

With CPU resources at a premium, you had to write tight, efficient code to get the most out of PSOC1. A single C library could consume the entire Flash. Consequently, I wrote a lot of assembly code. That’s not so bad, since I actually enjoy it more than C. There’s a certain elegance to well written, fully commented machine code. In the case of PSOC1, here’s what you had to work with: 5 registers, some RAM and Flash. That’s it. Real Men Write In Assembly.

M8C Architecture


We’ll start with simple machine code instruction to make the CPU do something. You can reference the M8C assembly language user guide here for more details. To get the M8C to execute 2+3=5 we write:

mov A,2       ;Load A with 2
add A,3       ;Add 3 to A. Result=5 is in A

We can get fancy by using variables. Let’s add R=P+Q. Assume P is at RAM location 0x20 and Q is at location 0x21, and R is at 0x22

;Initialize variables
mov [0x20],2  ;Load P with 2
mov [0x21],3  ;Load Q with 3

;Add variables
mov X,[0x20]  ;X <- P
mov A,[0x21]  ;A <- Q
adc [X],A     ;X <- P + Q
mov [0x22],X  ;R <- X

The fun thing about assembly is you can always dream up cool ways of doing things in less operations based on the machine’s instruction set. For example, we can simplify the above code as follows:

;Add variables
mov [0x20],[0x22]   ;R <- P
adc [0x22],[0x21]   ;R <- P + Q

In my experience, a good programmer with expert knowledge of the instruction set and CPU resources can always write better code than a compiler. There’s a certain human creativity that algorithms can’t match.

All that being said, I had not seen a good “machine code 101” tutorial for writing assembly in PSOC Creator on modern ARM M0 processors. So let’s walk through one now. We’ll use a CY8CKIT-145 and blink the LED. It’s just what happens to be laying around on the lab bench. Any PSOC4 kit will do.


We’ll start by creating a standard project in PSOC Creator, drop a Digital Output pin on the schematic and call it “LED”

Then open the .CYDWR file and drag pin LED to P2[5], since that’s where it is on the LED board. Yours may be in a different place on whatever board you are using.

Now under “Source Files” in the workspace directory you will delete main.c and replace with main.s

Now right clock on “Source Files”, select “Add New File” and select “GNU ARM Assembly File” in the dialog. Rename the file from GNUArmAssembly01.s to main.s

Your workspace ends up looking like this:

So far, so good. Now open main.s, delete everything if it’s not empty and add the following code. This sets up the IDE for M0 assembly architecture

// ==============================================
// ARM M0 Assembly Tutorial
// 01 – Blink LED
// ==============================================
.syntax unified

Next we need to include register definitions for the chip we are using. These are all from the PSOC4 Technical Reference Manual (TRM)

// ==============================================
// Includes
// ==============================================
.include “”

Then we are going to do some .equ statements, same as #define in C. This identifies the Port 2 GPIO data register plus bits for the LED pin in on and off state

// ==============================================
// Defines
// ==============================================
.equ LED_DR,CYREG_GPIO_PRT2_DR          // LED data reg address
.equ LED_PIN,5                          // P2.5
.equ LED_OFF,1<<led_pin                 // 0010 0000
.equ LED_ON,~LED_OFF                    // 1101 1111

Now you add the right syntax to set up main()

// ==============================================
// main
// ==============================================
.global main
.func main, main
.type main, %function

Finally we add the code for main, which is pretty simple:

ldr r5,=LED_DR      // Load GPIO port addr to r5

ldr r6,=LED_ON      // Move led data to r6
str r6,[r5]         // Write r6 data to r5 addr

ldr r0,=0xFFFFFF    // Argument passed in r0
bl CyDelayCycles    // Delay for N cycles

ldr r6,=LED_OFF     // Move led data to r6
str r6,[r5]         // Write r6 data to r5 addr

ldr r0,=0xFFFFFF    // Argument passed in r0
bl CyDelayCycles    // Delay for N cycles

b loop0             // Branch loop0

.endfunc            // End of main
.end                // End of code

One thing to note: The function CyDelayCycles is defined CyBootAsmGnu.s. Any function in assembly gets its arguments passed by the first 4 registers r0,r1,r2 and r3. Before calling the function you simply load r0 with the argument then do a bl (branch with link). This is also why I avoided the first 4 registers when messing with LED data. If you’re interested in doing more with ARM assembly, definitely read the Cortex M0+ Technical Reference Manual. It’s a great primer for the M0+ instruction set.

That’s it. End result is a blinking LED. Cool thing is you can use PSOC Creator with all it’s nice features, but sill access the power of machine code.

You can get the project ZIP file here.

Darrin Vallis

PSoC 4200M Low Power with WDTs


The last few weeks of my technical life have been frustrating.  Nothing and I mean nothing has been easy.  A few weeks ago I replied to a comment about cascading the watch dog timers in the PSoC 4200M to extend the sleep time – the article was called “PSoC 4200M WDT Long Deep Sleep“.  I wanted to measure power to see what exactly was happening.  But the great technical gods were conspiring against me and I had tons of problems.  Well I have things sorted out.  In this article I will build a project using the PSoC 4200M Watch Dog Timers and show the power measurements on the CY8CKIT-043 and CY8CKIT-044.  I will include PSoC 4200M low power measurements at 5V and 3.3V as well as with both the ILO and the WCO as the source of the WDT.  To do this I:

  1. Created a PSoC 4200M low power project
  2. Modified the CY8CKIT-043M
  3. Reject the Fluke 175
  4. Read the Keysite 34465A Multimeter Manual
  5. PSoC 4200M Low Power Current Measurement

PSoC 4 Low Power Firmware

First I create a schematic.  This includes 4 digital output pins.  The GREEN, RED and BLUE are attached to the tri-color LED.  A UART to print the status of the startup.  And an interrupt connected to the WDT Interrupt.

PSoC 4200M Low Power Schematic

The next thing to do is to make sure that the WDT is being driven by the ILO.  I also turn off the three WDTs because I will configure them in the firmware.

PSoC 4200M Low Power Clock Configuration

In order to get low power you need to switch the debugging pins off i.e. make them GPIOs.  You can do this on the DWR System Screen.

Finally write some firmware.  The firmware simply

  1. Blinks the LED 10 times
  2. Prints “Started” to the UART, waits until the buffer is flushed, then turns off the UART to make sure the power is low.
  3. Configure the Watch Dog Timers.  This could have been done on the Low Frequency Clock Screen (except for the cascading of timers which had to be done with firmware)
  4. Turn off the Pin, Deep Sleep the chip… and wait.  When an interrupt from the WDT occurs, it calls the ISR (next section)

The ISR first turns on the trigger pin (which I will use in the next article to trigger the oscilloscope).  Then it determines which timer caused the interrupt.  Originally I was blinking different color LEDs when I was trying to figure out what was happening.  With the current configuration WDT0 and WDT1 will never trigger an interrupt.  Finally it clears the interrupt and returns.  When it returns the main loop will turn off the trigger pin and then deep sleep.

Modified the CY8CKIT-043

In order to measure current with the. CY8CKIT-043 you need to remove the 0 ohm resistor R22 and install a jumper (J4) so that you can measure the current into the board.

CY8CKIT-043 Schematic

R22 is on the back of the development kit.  You can see that I circled it.

CY8CKIT-042 modification for PSoC 4200M Low Power Measurement

Then install a jumper into J4. I  just use a two pin break away header.

CY8CKIT-042 modification for PSoC 4200M Low Power Measurement

Fluke 175

According to the AN 86233 PSoC® 4 and PSoC Analog Coprocessor Low-Power Modes and Power Reduction Techniques I should be able to get 1.3uA in deep sleep 1.3mA in active.

PSoC 4200M Low Power Specs

I started with my trusty Fluke 175… but quickly realized that uA are not in the cards.  It appears that the lowest it can measure is 10’s of microamps.

PSoC 4200M Low Power Measurement with Fluke

It does fine with the active mode.

PSoC 4200M Low Power Measurement with Fluke

Keysight 34465A 6 1/2 Digit Multimeter

The good news is that I also have a Keysight 34465A 6/12 digit multimeter.  In the 1uA range it can measure +- 0.055% of 1uA or about 5nA (is that right?)

Keysight 34655A Specs

Keysight 34665A Current Measurement Ranges

It also doesnt change the input power supply very much.  In fact only 0.0011v in 3.3v is negligible.

Keysight 34465A Drop Out Voltage

PSoC 4200M Low Power Current Measurement

I wanted to measure Active, Sleep, Deep Sleep on the CY8CKIT-043 and CY8CKIT-44 with the WCO on and off.  In the two pictures below you can see that the system is taking between 3.6uA and 4.2uA in Deep Sleep.

PSoC 4200M Low Power Measurement

PSoC 4200M Low Power Measurement

Here are tables with all of the measurements.

5V – CY8CKIT-044

Mode WCO On WCO Off
Active 12..860mA 12.859mA
Sleep 5.339mA 5.335mA
Deep Sleep 4.206uA 1.078uA

3.3V – CY8CKIT-044

Mode WCO On WCO Off
Active 12.84mA 12.84mA
Sleep 5.328mA 5.327mA
Deep Sleep 4.096uA 0.940uA

5V – CY8CKIT-043

Mode WCO Off
Active 12.711mA
Sleep 5.352mA
Deep Sleep 3.632uA

The other thing that is pretty cool with the KeySite is that you can put it into “Trend” mode and it can display the current readings over a long period.  In the picture below I am flashing the LED which takes around 3.5mA @ 3.3v on this development kit.

PSoC 4200M WDT Long Deep Sleep


Earlier this year I wrote an article about using the PSoC 4200M WDT Watch Dog Timers.  In it I described a bunch of things that you could do with the PSoC 4200M WDT to help you time events, reset the part etc.  Recently a user named JAGIR asked if I could generate interrupts slower than 2 seconds and have the PSoC 4200M in deep sleep.  The answer to both of those questions is yes.

In order to make this work you need to “cascade” two WDTs together, something you can only do with firmware.  I have updated my previous workspace with a new project called “LongDeepSleep” which you can “Git” on my GitHub website or you can “”

Configure the PSoC 4200M WDT Design

First add a digital output pin called “RED” to the schematic

PSoC 4200M WDT Schematic

Then assign it to P0[6]

PSoC 4200M WDT - DWR Pin Assignment

Go to the clocks tab of the design wide resources.  Then click on “Edit Clock”.

PSoC 4200M WDT Clocks

On the Low Frequency Clocks configuration page of the design wide resources turn on the two WDTs and setup the dividers.

PSoC 4200M WDT

System Reference Guide – PSoC 4200M WDT

All of the documentation for the PSoC 4200M WDT is in the “Low Frequency Clock aka cy_lfclk” of the system resources documentations.

PSoC 4200M WDT System Reference Guide

When you read a little bit down in the PSoC 4 Low Frequency clock documentation you will find “Note The EDT cascade options are not configurable using these panels but the APIs can be used to perform cascading of WDTs”

PSoC 4200M WDT

Then you search a little bit further down in the document and you will find the API CySysWDTSetCascade which will allow you to hook multiple 16-bit counters together to get 32 or more bits.

PSoC 4200M WDT - CySysWdtSetCascade

Write the PSoC 4200M WDT Firmware

The first example will blink the LED every 4 seconds.  Remember from the configuration above it has a 32KHz input clock with a divider of 1024 on WDT0 and a divider of 128 on WDT1.  That means you will get 32KHz / (1024 *128) = 0.25 Hz aka every 4 seconds.

You can also get different delays by changing the dividers using firmware.  In the example below it is 1Hz output.


Serial Wire View with PSOC4

I use PSOC4 to invent all kinds of unique solutions for customers. Usually, they want them field upgradeable to deploy new features or fix bugs. Fortunately Cypress has a great I2C boot loader to meet this need, so I use the heck out of it.

Cypress has a great debugger built into PSOC Creator which fully supports all the ARM Serial Wire Debug protocols such as breakpoints, single step, memory, register viewing etc. However, when you are running a boot loader the debugger does not work! Why not? Because with a boot loader there are two applications resident in PSOC4: The boot loader and application. This is not supported by Cypress implementation of SWD.

Where does this leave you, the intrepid code developer, when debugging a boot loader project? Personally, I have used all kinds of methods: debug UART interface, debug I2C interface, bang out states on pins, debug Bluetooth interface … and on and on. You get the idea. All these methods burn a communications interface and require extra pins on the chip. Sometimes that’s not possible.

The issue recently came to a head when a customer very nearly in production experienced a boot loader failure. One system out of a few thousand was “bricked” when they tried to field  update in the lab. Their pinout is frozen, they can’t add new hardware so how do we look inside PSOC4 and see what’s going on?

I woke up at 2 AM and thought “Ah Ha! SWV!” (Yes, I Am A Geek) Serial Wire View is an ARM native debug protocol that let’s you XRAY the insides of any ARM MCU with the right interface. SWV is a protocol which runs on the SWD pins (clock and data) but also needs the Serial Wire Output (SWO) pin. Cypress left the SWO pin and associated IP off of PSOC4 to save die cost, foiling my great idea. Brief interlude to drink and bang head on desk.

Fortunately, I don’t give up easily. At least my subconscious does not. Woke up the next night thinking “Ah Ha!” again. Wife was mildly annoyed, but tolerates my idiosyncrasies.

Cypress has a nice software UART transmitter implementation. I shamelessly stole it, modified for my purposes and created a custom component. (It’s pretty easy to do this by the way) Baud rate was modified to 230 KBps and the output pin forced to a specific pin with a control file.

Once the component is in place, you can use its _DView_Printf( ) API call to display any debug data. Here is an example:

More about that output pin. Cypress sells a tool for programming and debugging PSOC called CY8CKIT-002, aka MiniProg3. The programming connector consists of VDD, GND, reset, SWD clock and SWD data as shown below.

Since we can’t use SWD protocol for debugging anyway, we can change the pins from SWD to normal GPIO. The pins still function for programming. By default they are in SWD mode as shown.

Going to the system tab of the .CYDWR file, we can change them to GPIO.

Once we do that, the pins look like this. Here’s the trick. We now assign the TX output of our DTView component to pin 3[2], which is available  on the SWD programming header, pin 5.

Can you see where we are going with this? Printf( ) data is now coming out of PSOC4 on pin 3[2], easily accessible on our debug header. This is where MiniProg3 comes in. It can actually receive data as a 230 KBps RX UART on its XRES pin. Weird, right? By building a simple interface cable we can get the data from your debug header into MiniProg3.

MiniProg3 XRES —— SWD HEADER pin 5

MiniProg3   GND —— SWD HEADER pin 2

However, MiniProg3 does not show up as a COM port on your PC, so how do we the data? It needs to be accessed by a host application running the PP_COM API. This is documented under PSOC Programmer Component Object Model COM Interface Guide, Cypress specification 001-45209. If you installed PSOC Creator or Programmer, this document is actually on your PC under C:\Program Files (x86)\Cypress\Programmer\Documents. Engineers don’t like to read instructions. Amazing what you can find when you do.

I wrote a simple  console application which opens MiniProg3 using PP_COM, retrieves data from the serial RX pin via USB and displays it like a simple terminal program. Voila! You now have a serial debugger that works for any PSOC4 project using MiniProg3 as your USB to serial dongle.

Customer was really happy with this. We were able to immediately see his problem and fixed it in about 5 minutes.

Finally, here are all the source files

DTView Firmware : PSOC Creator example project and DTView component

DTViewer Binary : Installer for DTViewer console

ViewerSource : Complete source code for DTViewer console (Requires Visual Studio 2015)

That’s all. Have fun with the new debugging tool.


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 :

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) :

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.

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).


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


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

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.


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)


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)


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.


This function simply set the in_use to 0;

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

FreeRTOS PSoC Template Project


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

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:

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:

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.


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


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

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

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


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)

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)

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.

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


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.

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:

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


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


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.

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

Percepio Tracealyzer: A PSoC DMA Streamport


In the last Article I analyzed the performance problems of my firmware based PSoC Tracealyzer Streamport … which was terrible.  Although it has been a long time since I used the PSoC4M DMA engine, I knew that it would solve my problem.  In this article Ill show how to use the PSoC DMA, then Ill build and analyze a PSoC DMA Streamport for Tracealyzer.


The DMA block that shows up in the PSoC4200M, PSoC 4200L and PSoC4BLE is pretty amazing.  It can do a bunch of stuff.  Here is a snapshot that I took out of the TRM.  This block sits on the main AHB bus inside of the PSoC.  It can act as a master (see the block that says Master I/F) and read and write any of things in the ARM address space including the Flash, SRAM, and all of the peripherals.  It has an incoming trigger which can get the transfers going and when it is done it can trigger an interrupt or another DMA channel.  The Slave I/F allows the CPU to program the block.  The device has 8-channels with each channel having 2 descriptors (so it can ping pong).


Before I tried to make the PSoC DMA Streamport I started by looking at the example projects by pressing “File->Code Example”

PSoC Creator Example

Then filtering for DMA

PSoC Creator Example Project - DMA

Finally creating project.  This project uses two DMA channels, one for the UART receive and one for the UART Transfer.  It lets you type characters into the UART, it saves them in one of the RAM buffers, then when you have typed 8, it DMAs them back into the Transmit channel of the UART.  This example ping-pings back and forth between two RAM buffers.

PSoC Creator DMA Example

I decided that it would be best to build a bare metal DMA project called “test-uart” to prove that I understood.  This project will DMA transfer an array of characters to the UART when the user presses the switch on the board or a “s” on the keyboard.  The first thing to do is build the schematic with a UART, a DMA block,  two output pins, and input pin and an interrupt.

PSoC DMA Streamport

Place an SCB UART. then configure it (change the name, but accept all of the defaults)

PSoC Creator UART

Then click on the advanced tab.  Turn on the DMA for Transfer (TX Output) and set the “FIFO Level” to 7.  This will cause the UART to assert DMA signal anytime the transmit FIFO has less than 7 bytes.  In  other words … FEED ME!!!

After configuring the UART, Set the PINs

PSoC DMA Streamport Pin Assignment

Next configure the DMA.  The memory array that I have will be “uint8_t” aka “char”.  So the input needs to be “bytes”.  The UART FIFO hold Words… aka 4 bytes.  So I need to configure the transfers to do “Byte to Word”.  After the DMA transfer is done, I setup the DMA to create an interrupt (so that I can reset everything in the CPU) and to invalidate the descriptor.

PSoC DMA Streamport

In the firmware works by

  • Turning on the UART
  • Enabling the DMA
  • Setting up the channel with the address of the buffer that I am going to write to (aka the TX FIFO) and asking for an interrupt

Then looping:

  • When the User presses “s” or the switch, I set myFlag to be 1.
  • If it is 1 and the channel is inactive, then initialize the “source” address, setup the number of transfer elements to be the number in my array, validate the descriptor, and turn on the channel.

When the channel turns on, the Tx fifo will be empty so it will assert the Tx Out, which will make the DMA keep triggering and copying 1 byte at a time into the FIFO.  While this is happening, the UART will try to empty the fifo by sending the bytes.  Finally when the DMA reaches the end of the RAM buffer, it will stop, and at some point the TX FIFO will finish emptying.  The DMA will trigger the interrupt to toggle the BLUE LED.  And the whole process can start again.

PSoC DMA Streamport

Now that I understand how to use the DMA, I can create the PSoC DMA Streamport by copying the project “1-BlionkingLED_UART_TRACE” project and calling it “1-BlinkingLED_UART_TRCE_DMA”.  Next, add the DMA and modify the UART.

PSoC DMA Streamport

Configure the UART

PSoC DMA Streamport - UART Configuration

Turn on the UART DMA and set the level to 7

Configure the DMA Block

PSoC DMA Streamport Configuration

Make byte transfers and byte –> word.

PSoC DMA Streamport - DMA Configuration

Finally modify the trcStreamingPort.c – AKA the PSoC DMA Streamport file.  Specifically you need to fix up the PSoC_Transmit to send out the data when the TraceRecorder buffer is full.

  • If the DMA is busy… then wait until the previous transaction is done.
  • Then setup the DMA and let it rip.

The only other thing that needs to happen is configure the DMA in main.c

Testing the PSoC DMA Streamport

Now when I startup the Tracealyzer, here is what I get:

PSoC DMA Streamport - New CPU Load

It looks like I solved my problem because that is way way better than:

PSoC DMA Streamport - Terrible Performance

As always you can find all of these projects on the IotExpert GitHub site or

Article Description
Percepio Tracealyzer & PSoC An Introduction to Percepio Tracealyzer on the Cypress PSoC
Percepio Tracealyzer RTT Streamport - PSoC4200M Make the JLINK RTT Library work with Tracealyzer
Percepio Tracealyzer PSoC UART Streamport Creating a UART Streamport
Percepio Tracealyzer - Analyzing the PSoC Tracealyzer Streamport Figure out what is broken in the UART Streamport
Percepio Tracealyzer - Using PSoC DMA to Fix the UART Streamport Implementing PSoC DMA to improve the CPU Utilization
Percepio Tracealyzer - Running on PSoC6 Porting the Percepio Tracealyzer to PSoC6

Percepio Tracealyzer & PSoC 4200M


As you have probably noticed, I have spent a significant amount of time in the last few months doing FreeRTOS projects.  One thing that I have been continuously frustrated about is a lack of analysis tools.  How much memory am I using?  How much stack and heap are free?  How long are tasks taking?  How do you get the priorities set right?  And on and on.  A couple of weeks ago I got an email from the guys at Percepio asking me if I wanted to try out the Percepio Tracealyzer.  I said yes… but that I was really busy and it was going to take a while for me to get to it.  So now I have… and this is the first article about the Percepio Tracealyzer.  Unfortunately the story involves me burning myself with a soldering iron but I suppose that isn’t their fault.

In this series of article’s I will instrument the FreeRTOS projects that I have been showing you with the Percepio Tracealyzer Recorder Library, then run the tool to see what is going on.  In this specific Article I will show you how to get the most basic Tracealyzer functionality going on a PSoC4200M.

Percepio Tracealyzer

The way that Percepio Tracelzer works is that you install a bit of code into your project called the Tracealyzer Recorder Library.   In streaming mode, the code creates a new task in FreeRTOS called “TzCtrl” which interacts with the FreeRTOS kernel to record all of the running task information into a communication link (e.g UART, SPI, JLINK RTT, etc.)  In snapshot mode, the kernel information is just written to an SRAM buffer inside of the PSoC.

This is the architecture picture from the Percepio website:

Percepio Tracelyzer Architecture

Updating CY8CKIT-044 PSoC4200M Development Kit

To make the Percepio Tracealyzer work you need to turn the “Snapshot or streaming” line from the picture above into a real connection.  In snapshot mode there are two ways (I think) that you can do it.

  1. You can stop the processor with the debugger, then write the region of memory with the trace buffer into an “.hex” or a “.bin” file.  Then read that file into Percepio Tracealyzer.  Unfortunately the debugger in PSoC Creator cannot create binary output files of regions of memory like that… so plan 1 is out the window
  2. You can attach a Segger JLINK to the PSoC via SWD.  Then, Tracealyzer knows how to talk to the JLink to read the memory.  This is what I am going to do for this Article.

One feature that is very cool about the Snapshot methodology is that Tracealyzer can search the output file and find the trace buffer.  The trace buffer data structure is marked by something that Tracealyzer can find.

When our very good devkit team team in India built the CY8CKIT-044 (which I have used and written about quite a bit), they installed a built in debugger/programmer called “KitProg“.  But they also understood that someone might want to connect some third part debugger like the JLINK.  So… they put the footprint for a 10-pin ARM debugging port onto the board. (see it in the lower left).  Actually if you look at the board, you can see two 10-pin footprints, the one at the top is connected to the PSoC5 (which serves as the KitProg).

CY8CKIT-044 PSoC 4200M Development Kit

Before I can use a JLINK I needed to do this … which unfortunately ended with me burning myself with the soldering iron… bad Alan.

CY8CKIT-044 PSoC 4200M Development Kit

Tracealyzer Snapshot Mode on Blinking LED Project

In a previous article I talked about the organization of PSoC Creator projects, specifically how to handle the situation where you want to include .h/.c files into your project but you don’t want to modify them.  This is exactly what I will do with the Percepio Tracealyzer Recorder Library.  The library has some files which I will want to leave intact and I will just make references to them in my project including trcKernelPort.h, trcPortDefines.h etc.  And there are some files which I will want to modify, which I will copy out of the Trace Recorder Library into my project for editing trcConfig.h, trcSnapShotConfig.h and trcStreamingConfig.h

To start the first Percepio Tracealyzer example I will use the basic “Snapshot Mode”.  There is good documentation on the Percepio Tracealyzer documentation website.  I will start by copying the PSoC Creator Workspace from the FreeRTOS articles from GitHub.  It has 9 projects in it, starting with the blinking led, going to a more complicated multi-thread project.  The next step is to download the FreeRTOS Tracealyzer library from the Perceio website into a parallel directory called “TraceRecorder”.

Make a new folder for the non-changing include files called “TraceRecorder” (for the files that I don’t want to change)

PSoC Creator Project Configuration

Next I will add the files that I don’t want to change to the project so that I can see them (meaning they are just referenced by PSoC Creator)

PSoC Creator Project Configuration - Add External Files

They reside in the directory TraceRecorder/include

PSoC Creator Project Configuration - Add External Files

Once I have the unchanging .h’s into my project, I need to add their directory to the include path.  To do this right-click on the project and select “Build Settings …”

PSoC Creator Project Configuration - Add External Files

Then click “Compiler” and then the “…” on the “Additional Include Directories” line

PSoC Creator Project Configuration - Compiler Options

Navigate until you get to TraceRecoder/include then press “Select Folder”

PSoC Creator Project Configuration - Update include path

Now your include path should look like this:

PSoC Creator Project Configuration - Include Path

Next, I want to copy the configuration files in the Windows Explorer to my project directory so that they become a changeable part of they project.  They reside in TraceRecorder/config (I just did a Ctrl-C to copy)

PSoC Creator Project Configuration - Add Trace Recorder Library

You want to paste them into your project directory

PSoC Creator Project Configuration - Add External Files

Then you need to add them to the project so that you can easily edit them by right clicking on the “Header Files” folder and selecting “Add–>Existing Item”

PSoC Creator Project Configuration - Add External Files

Then selecting them out of your project directory.

PSoC Creator Project Configuration - Add External Files

Now we need to add references to all of the .c files.  Start by making a new folder for the c-files called “TraceRecorder”

PSoC Creator Project Configuration - Add TraceRecorder

Then “Add–>Existing Item…”

PSoC Creator Project Configuration - Add External Files

Select the files from the TraceRecorder directory

PSoC Creator Project Configuration - Add TraceRecorder Files

Now your project should look like this

PSoC Creator Project Configuration - Project Configuration

Your project now has all of the necessary body parts so you next will modify the source files.  Start with modifying FreeRTOSConfig.h to include the TraceRecorder Library stuff.

Then modify the trcConfig.h so that it has access to all of the CMSIS header files.

Then tell the TraceRecorder that we are using an ARM Cortex-M

Now, you need to modify the project’s stack and heap size setup

PSoC Creator Project Configuration - Design Wide Resources

The default snapshot buffer is to big to fit into PSoC SRAM, so I change the size to 400 records

Finally modify main to start the Trace Recorder (vTraceEnable on line 40)

Testing the Output

After all of the setup is done you can build and program the development kit.

PSoC Creator Program Project

Plug in the Segger J-Link


Start Tracealyzer then setup the J-Link (click on J-Link Settings…)

Percepio Tracelyzer

Select “Select Device…”

Percepio Tracelyzer - JLINK Settings

Filter the list to “cypress” then choose the “CY8C4247xxx” (which is the chip that is on the C8CKIT-044)

Percepio Tracelyzer - JLINK Settings Select Device

Then Select “Jink->Read Trace”

Percepio Tracelyzer - Read Trace

Accept the defaults (this window only is only brought up the first time)

Percepio Tracelyzer - JLINK Memory Region

Then you will end up with a screen like this.  Each stripe of white/gray is 1 second in time.  The yellow line is where the startup occurred.  The red lines are where the “LED Blink” task was running.  This seems to make sense as you get a tiny red line 2x/second (remember in the source code we have a 500ms delay so that makes sense).

Percepio Tracelyzer - Console

Next I press the reset button on the devkit and re-run the trace.  Then I click on the second red line and the window on the right gives me information about that task.  You can see that the task ran for 53uS and took 23uS to start (time taken up in the FreeRTOS scheduler and Percepio Tracealyzer Recorder Library)

Percepio Tracelyzer - Console


Obviously the snapshot mode is limited by the size of the RAM buffer that you allocate but it saves you the hardware resources and timing constraints that are required to stream FreeRTOS data.  In the next several articles I will show you how to:

  • Use Segger JLINK RTT streaming
  • Make a streaming port
  • Use some of the other screens in the Percepio Tracealyzer

As always you can find all of these projects on the IotExpert GitHub site or

Article Description
Percepio Tracealyzer & PSoC An Introduction to Percepio Tracealyzer on the Cypress PSoC
Percepio Tracealyzer RTT Streamport - PSoC4200M Make the JLINK RTT Library work with Tracealyzer
Percepio Tracealyzer PSoC UART Streamport Creating a UART Streamport
Percepio Tracealyzer - Analyzing the PSoC Tracealyzer Streamport Figure out what is broken in the UART Streamport
Percepio Tracealyzer - Using PSoC DMA to Fix the UART Streamport Implementing PSoC DMA to improve the CPU Utilization
Percepio Tracealyzer - Running on PSoC6 Porting the Percepio Tracealyzer to PSoC6

PSoC FreeRTOS Counting Semaphore


The FreeRTOS Counting Semaphore is a simple extension of the binary semaphore that I talked about in the last two articles (PSoC Binary Semaphore, PSOC Binary Semaphore Part Two).  Simply put, the semaphore counts up when “set” and counts down when “get”.  When it is 0, the task that tried to “get” it is paused until some other task “set”s it.  There are a number of uses of the the counting semaphore including:

  • One or more producers tasks create events and one or more consumers tasks consume those events.  The semaphore counts the events
  • The semaphore represents one or more identical resources.  When you need that resource you take the flag, use the resource, then give the flag back. (e.g. identical blocks of scratch memory)

As I worked on this article I was looking around the internet for good examples, that would visibly demonstrate the counting semaphore.  There are a number of examples out there including, the dining philosophers, the line of bathrooms, the librarian but they all feel somewhat contrived.  The other thing that I realized as I looked around is that there are a bunch of different names for exactly the same thing, that is getting and setting the semaphore.  Those names include at least:

  • Signal/Wait
  • P/V
  • Give/Take
  • Set/Get

FreeRTOS Counting Semaphore Danger

There are a number of scenarios that can cause you much pain with threaded RTOS programming and semaphores.  Two of those cases are circular deadlocks and priority inversion.

The circular deadlock occurs when A depends on B who depends on C who depends on A.  If your program finds itself in this state, you will have a deadlock, which is almost certainly a highly-not-good thing.  A variation of the circular deadlock occurs when you have multiple threads that are dependent on a pool of shared resources and you end up with the scenario where each threads only has one of the resource that its needs (e.g. it requires 2 of the resources to get a job done).  Each thread is then stopped, and waiting for one of the other threads to release the resource.

The other problem that can occur (and be difficult to debug) is called priority inversion.  This can occur when a lower priority thread gets access to a scarce shared resource.  And, a higher priority thread ends up waiting for that shared resource.  This scenario effectively gives the lower priority task a higher priority.

PSoC FreeRTOS Counting Semaphore Example

My example is simply to have one task (called countingSemaphore)  which is consuming events and multiple places that are creating events.  When there are events available, the countingSemaphore task will just printout the number of events, decrement a.k.a. take the semaphore, then loop back.  I start by copying the project “4-Binary-Semaphore” and creating a new project called “5-Counting-Semaphore”.

To make this work, I first declare a global variable to hold the counting semaphore.

Then I initialize it in main

Create the counting semaphore task

I make the task that will take the semaphore, then print the semaphore count, then start again.

Lastly I add the ability to “create events” by making the 1,2,3 keyboard keys create 1,2,3 events (a.k.a. set the semaphore 1,2,3 times)

To test the program, I start up a terminal and:

  • press ‘3’, which gives the semaphore 3 times in a row.  Then the countingSemaphore task consumes the “gives” with “takes” and prints out “2,1,0”
  • press ‘2+’, which gives the semaphore 2 times in a row.  Then the countingSemaphore task consumes the “gives” with “takes” and prints out “1,0”
  • press ‘1’, which gives the semaphore 1 time.  Then the countingSemaphore task consumes the “give” with “take” and prints out “0”

FreeRTOS Counting Semaphore Example

You can find this example on the IoT Expert GitHub website or

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 Binary Semaphore (Part 2)

FreeRTOS Binary Semaphore – Update

Last week I taught a class on WICED WiFi programming, which also uses and RTOS.  During that class I yelled at a number of people for not using the RTOS mechanisms that I was showing them.  Which got me thinking, that in all of the versions of the FreeRTOS example program that I have shown you, I have used a polling loop for handling the UART.  This was kind of bugging me (at very least it was inconsistent).  In order to fix this I decided use the FreeRTOS Binary Semaphore to fix the problems by:

  • Modifying the FreeRTOS Binary Semaphore schematic and adding the UART ISR
  • Add a FreeRTOS Binary Semaphore called “uartSemaphore” that I will set in the UART ISR
  • Turn on interrupt handling for the UART when there is one or more characters in the buffer
  • In the ISR turn off interrupts and set the “uartSemaphore”
  • In the UART task, wait for the “uartSemaphore”, then handle all of the characters, then turn the UART interrupt back on

First I copied the “4-BinarySemaphore” project and called it “4a-BinarySemaphore”.  Then I modified the schematic to support the UART ISR.

FreeRTOS Binary Semaphore UART Schematic

Then I create a new global variable called uartSemaphore.

In main I initialize the semaphore and install the ISR Handler.

In the ISR Handler, I clear the interrupt from the UART.  Originally I thought that I could just clear the pending interrupt, set the semaphore and return.  However, when I returned from the ISR, there were still characters in the receive FIFO, which made the UART immediately pend the interrupt.  This kept me from ever leaving the ISR.  To fix this I turn off all interrupt sources.  In the UART Task I will turn the interrupts back on when the FIFO is empty again.

Finally I modify the UART Task to

  • Line 77 Wait for  the semaphore (which is set in the ISR)
  • Line 78 Loop until there is nothing left in the FIFO (UARTGetChar() will return 0 when there is nothing left)
  • Line 124: Turn the UART Interrupts back on

This is a fairly simple modification to my program which will save power (potentially), will save CPU cycles (for sure) and is generally much better inline with the RTOS philosophy.

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 4 Flash Write


Last week I got a question from a customer about how to write into the PSoC 4 Flash.  I sent him a fairly straight forward email message explaining the process in English… but after reflecting a little bit, I decided to write an example project as “C’ is often much clearer.  And yes I know that this article it doesn’t have much to do with IoT, but hopefully it is helpful to someone.  In this article I will explain:

  • The organization of the PSoC 4 Flash
  • The risks and issues of writing to the PSoC 4 Flash
  • A program that demonstrates reading and writing the PSoC 4 Flash
  • How to protect rows of the PSoC 4 Flash

Organization of the PSoC 4 Flash

The PSoC 4 Flash is organized into an array that starts at memory address 0x00 and has 128 byte rows.  Different versions of the chip will have different numbers of rows and possibly two arrays (in the case of PSoC 4 BLE II).  The exact configuration of your part is knowable in the firmware by a set of #defines that are built for you by PSoC Creator.  Here is a snapshot from the PSoC 4 System Reference Guide Chapter 8.

PSoC 4 Flash System Reference Guide

You can use that information along with the System call CySysFlashWriteRow() to write into the flash of your device.

PSoC 4 Flash Write API

Risks and Issues Writing the PSoC 4 Flash

There are several risks that you must take into account when performing a PSoC 4 Flash write (or for that matter writing Flash in any other MCU).

  • You must write a complete row at a time.  In PSoC 4 that is 128 bytes.  So, even if you want to write only 1 byte, you will need to read in all of the data surrounding that byte in the row and make sure you don’t overwrite something important.
  • You can easily write someplace bad and brick your part (e.g. if you overwrite your program, or exception vectors, or …).  You need to be very careful that you are writing in the correct place
  • It takes 20ms, which is a long time in the context of MCU speed, to write a row of flash and the MCU comes to a standstill while that is happening (all of the interrupts are off etc.)
  • The Flash will eventually wear out.  If you look at the data sheet for PSoC 4 you will find that the endurance of the Flash is 100K writes. If you are continually updating a place in the memory, you will eventually wear it out

PSoC 4 Datasheet

A PSoC 4 Flash Write Demo Project

To demonstrate the process of a PSoC 4 Flash write I created a project that:

  • Initializes a 128 byte array in the Flash (aligned to a complete row) with 0’s
  • Lets you read the Flash array into a RAM array by pressing a key on the keyboard
  • Lets you printout the values of the Flash array
  • Lets you printout the values of the RAM array
  • Lets you increment the values of the RAM array
  • Lets you write the RAM array into the Flash

Normally when you declare a variable in C it will be assigned to the RAM somewhere (either on the Stack or in the Data or BSS section of the RAM).  In order to have my array be assigned to the Flash, I declare the array to be “const”.  The first time I did this I did not include the “={0}” in the declaration, and the compiler decided to put the array in the RAM, but when I initialized one of the elements it assigned it to the Flash.  The CY_ALIGN() macro tells the linker to put the start of the “row” array on a 128 byte boundary.  In other words completely aligning to a Flash row.

At the start of main, I declare array called “data” which will reside in the RAM.  I will use this array as a buffer to read Flash data into, then change it, then write it back to the Flash.

We know that the Flash is arranged in rows of 128 bytes (well, actually rows of size CY_FLASH_SIZEOF_ROW).  To calculate the row number of the my array “row”, I use the Address of the row divided by the row size. (the CY_FLASH_BASE is 0x00 because the Flash starts at Address 0x00)

To make things a bit easier I create a function called “dump” which just prints the values of a “size “of memory in hex format.  The function just takes an address that you want to start dumping to the screen.

In order to test this whole thing I use a UART to read from the keyboard and display to the screen.  The main function is just a loop that reads keys and then does a big “switch”.

When you press ‘f’ it dumps the Flash “row”

When you press ‘r’ it copies the Flash “row” into the array “data” (which resides in the RAM)

When you press ‘i’ it increments the values in the “data” array

When you press “R” it dumps out the values in the “data” array

When you press ‘q’ it prints out information about the rowNumber, row size etc.

When you press ‘w’, it writes the “data” array into the “row” array in the Flash using the “CySysFlashWriteRow()” system call

Testing the Program

After I program the device, I first press “q” to find out the information about the PSoC 4 Flash array.  You can see that my “row” is the 46th row in the Flash and resides at address 0x1700 (as I type this I wish that I hadn’t mixed decimal and hex … and that I had called my “row” variable something other than “row”).  You can also see that the rows are 128 bytes and that the Flash array starts at address 0x0.  All that is good.

PSoC 4 Flash Write Demo

When I press ‘f’ to dump out the Flash array, you can see that my row has all 0’s in it.  Then I press ‘R’ to dump out my RAM array and you can see that it has garbly-gook in it (which makes sense as I didn’t initialize the array)

PSoC 4 Flash Write Demo

Next, I press ‘r’ to copy the PSoC 4 Flash array into the RAM buffer.  Then I press “i” to increment the values in the RAM array, then I dump it out.  Lastly, I press ‘w’ to write it to the PSoC 4 Flash.

PSoC 4 Flash Write Demo

Then I hit reset on the board and press ‘f’ to printout the PSoC 4 Flash array.  And I see success, the values were retained in the PSoC 4 Flash even after resetting the device. (or for that matter power cycling it)

PSoC 4 Flash Write Demo

Protecting Rows of the PSoC 4 Flash

One cool feature of the PSoC 4 Flash is that you can write protect it on a row by row basis.  Meaning that you can make it so that the PSoC 4 Flash writing hardware will not overwrite rows.  You do this by going to the “Flash Security” tab of the Design Wide Resources.  Then you have 1 box for each row in the flash where you can pick “W” for Full Protection and “U” for Writable.  In the screen show below you can see me changing the row “ox1700” to Write protection.  This is the row where my Flash array resides.

PSoC 4 Flash Security

After reprogramming my device I try to press ‘w’ and you can see that the Write fails.

PSoC 4 Flash Write Fail

As always my projects are available on the IoT Expert GitHub site