Posts Tagged ‘printf’


23/12/2015 18 comments

Previously I created a blog post on Printf to UART using Processor Expert, this is a great way to output debug info at runtime to a console using the OpenSDA USB debugger port as found for example on the FRDM K64F board. What if you don’t want to use this USB port or can’t because you don’t have one, for instance on a custom board perhaps. Well if your board provides a USB port that connects direct to the mpu’s USB pins this blog will help you configure all the Processor Expert components and code needed to output to that type of USB port. In this blog I will again use the FRDM K64F board but it has a second USB port that is directly connected to the USB pins of the of the MK64FN1M0VLL12 MCU. I am using KSDK 1.3.0 and Eclipse Neon but I will also try provide notes on how to do this in KSDK 1.2.0, if you want to know how to set up Eclipse you can follow the directions on my blog Toolchain: KSDK 1.2.0 with Eclipse 4.4 (Luna) and GNU ARM Plugin, although that blog covers an older version of Eclipse and KSDK, the steps work perfectly still as long as you download all the latest pieces of software mentioned in that blog.

PLEASE NOTE: I am not an expert with USB on Kinetis devices so I cannot provide any help on any other USB related projects such as Mass storage devices or HID devices. Please do not post comments/questions asking how to perform other types of USB projects.




  1. Ok to start, create a new Kinetis project.CreateProject_Name
  2. Select the board type. In my case I select the FRDM-K64F board.CreateProject_Board
  3. Select KSDK_1.3.0, Processor Expert and standalone.CreateProject_SDK
  4. Select “GNU C Compiler” and click Finish.CreateProject_Compiler
  5. Switch to Processor Expert perspective and add the component “fsl_usb_framework”. Note this will also automatically add the referenced components “Init_FMC” and “fsl_debug_console”.
    Note: In KSDK 1.2.0 the “Init_FMC” is not automatically added for you but you still add it manually then afterwards.PE_fsl_usb_framework
  6. If you get prompted on how you want to add the “Init_FMC” component, select “New component [KSDK 1.3.0/Init_FMC_VAR1]…”PE_fsl_usb_framework_sharedComp
  7. On the Components window select “usbFmw1:usb_framework” and set the properties as below. Its important that the USB clock is set to 48 MHz. Its also very important that MPU is disabled as the MPU protects the Bus from USB read/writes. Make sure the Mode is set to “DEVICE” then Enable “USBCFG_DEV_CDC” under the Device class driver section.
    Note: In KSDK 1.2.0 the option to disable the MPU is not available on this component, you will need to manually add the component “Init_MPU” and disable it from there.fsl_usb_framework_Properties
  8. Now select the component “FMC:Init_FMC”, this should be already set correctly for us but just note that the important bit here is that the access protection on Master 4 which protects USB memory access areas must be set to “Read only”.
    Note: in KSDK 1.2.0 this is not set for you, you must manually set Master 4 to Read only.Init_FMC_Properties
  9. Next select the “DbgCs1:fsl_debug_console” component, make sure the “Baud rate” is set to 115,200. It’s not important what Pins the Receiver and Transmitter are set to as this will get overridden in code when we initialise this component manually. VERY IMPORTANT, make sure the “Auto initialization” is disabled, as said, we will manually do this in code.fsl_debug_console_Properties
  10. Ok one last configuration then, select the “Cpu:MK64FN1MOVLL12” component (or whatever MPU you are using). Switch to the “Build Options” tab and make sure you set a Heap size because usb stack uses malloc which uses a function called _sbrk(). This function checks if there is heap memory available to allocate to the malloc. The FRDM K64F board has enough memory available for me to set the Heap size to its max on this screen of 0xFFFF, Also make sure you have at least 0x400 allocated to the Stack.
    Note: KSDK 1.2.0 has a bug and does not implement a _sbrk() function, you will need to create your own _sbrk() function to get this to work. See the end of this Blog on how to do this.Cpu_HeapSize
  11. Now generate code from Processor Expert.Components
  12. On the Project Explorer window, expand the folder \SDK\usb\usb_core\device\sources. Create a folder under the sources folder called “classes”.Import the following 3 folders into the classes folder from the path “C:\Freescale\KSDK_1.3.0\usb\usb_core\device\sources\classes”
    • cdc
    • common
    • include



  13. We need to add these new folders into the includes. Open up the project properties and add the following 4 folders under “C/C++ Build >> Settings >> Cross ARM C Compiler >> Includes”.Project_Settings_includesOn the Project Explorer window again, Open up the file “\SDK\platform\utilities\fsl_debug_console.c”.  Note around line 49 the following #if block:
#if (defined(USB_INSTANCE_COUNT) &&  (defined(BOARD_USE_VIRTUALCOM)))
  #include "usb_device_config.h"
  #include "usb.h"
  #include "usb_device_stack_interface.h"
  #include "usb_descriptor.h"
  #include "virtual_com.h"

based on this section of code I can see that the code actually supports using USB and the use of the “VIRTUALCOM”. What is this “VIRTUALCOM”, well if you were to look at the code in the example KSDK project “C:\Freescale\KSDK_1.3.0\examples\twrk64f120m\demo_apps\usb\device\cdc\virtual_com\bm\kds” which is a project for demonstrating how to use USB CDC communication but without the use of the” fsl_debug” component or using Processor expert at all, then you will see that the “VIRTUALCOM” is the main piece of code written for sending and receiving messages over the USB CDC. Great, that means then that we can enable the “fsl_debug_console” to make use of it. So looking at this section of code in “fsl_debug_console.c”, it looks like all we need do is define a symbol for “BOARD_USE_VIRTUALCOM”.

  1. Open up the Properties of the project and under “C/C++ Build >> Settings >> Cross ARM C Compiler >> Preprocessor” add the symbol “BOARD_USE_VIRTUALCOM”. make sure to include the double quotes around the symbol.Project_Settings_Preprocessor
  2. Ok but now the code will complain that it can’t find the included files “usb_descriptor.h” and “virtual_com.h”, so where can this be found. Well actually you can find these files in the same directory where the “fsl_debug_console” files get imported from. So to fix this perform the following imports:import_virtual_com_headersimport_virtual_com_code


  3. One last thing to do is make sure we initialise the Debug Console component telling it to use the USB CDC. If you remember we intentionally disabled auto initialising the “fsl_debug_console” in processor expert. This was done for the purpose of providing us the ability to change the device used by the console. So at the start of your main function just after the call to “PE_low_level_init()”, make the call “DbgConsole_Init(BOARD_DEBUG_UART_INSTANCE, DEBUG_UART_BAUD, kDebugConsoleUSBCDC);”.


/* ###################################################################
**     Filename    : main.c
**     Project     : K64F_USB_CDC
**     Processor   : MK64FN1M0VLL12
**     Version     : Driver 01.01
**     Compiler    : GNU C Compiler
**     Date/Time   : 2015-12-12, 23:04, # CodeGen: 0
**     Abstract    :
**         Main module.
**         This module contains user's application code.
**     Settings    :
**     Contents    :
**         No public methods
** ###################################################################*/
** @file main.c
** @version 01.01
** @brief
**         Main module.
**         This module contains user's application code.
**  @addtogroup main_module main module documentation
**  @{
/* MODULE main */

/* Including needed modules to compile this module/procedure */
#include "Cpu.h"
#include "Events.h"
#include "clockMan1.h"
#include "pin_init.h"
#include "osa1.h"
#include "usbFmw1.h"
#include "DbgCs1.h"
  #include "Init_Config.h"
/* User includes (#include below this line is not maintained by Processor Expert) */

/*lint -save  -e970 Disable MISRA rule (6.3) checking. */
int main(void)
/*lint -restore Enable MISRA rule (6.3) checking. */
  /* Write your local variable definition here */

  /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/
  /*** End of Processor Expert internal initialization.                    ***/


  PRINTF("Hello CDC!");

  /*** Don't write any code pass this line, or it will be deleted during code generation. ***/
  /*** RTOS startup code. Macro PEX_RTOS_START is defined by the RTOS component. DON'T MODIFY THIS CODE!!! ***/
    PEX_RTOS_START();                  /* Startup of the selected RTOS. Macro is defined by the RTOS component. */
  /*** End of RTOS startup code.  ***/
  /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/
  /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/
} /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/

/* END main */
** @}
** ###################################################################
**     This file was created by Processor Expert 10.5 [05.21]
**     for the Freescale Kinetis series of microcontrollers.
** ###################################################################


  1. If you try to compile the code now you will get an error saying the Symbol ‘usb_device_board_init’ could not be resolved within the file “virtual_com.c”. If you navigate to the line where this error is caused all that need to be done is to set the value to NULL instead:


cdc_config.board_init_callback.callback = NULL;


That’s it then, after that you can make “PRINTF”, “SCANF” or “GETCHAR” calls in your code and it will output to the OTG usb port on your board. Please note, you must capitalise the calls to the functions “PRINTF”, “SCANF” or “GETCHAR” as these are specialised versions of the functions that reside inside the “fsl_debug_console.c” file.


You can get a copy of this project on my Github repo at


Good luck, hope this works well for you all.


KSDK 1.2.0 _sbrk() function


To implement a _sbrk() function simply add the following block of code to your project:


void *_sbrk ( uint32_t incr )
	extern char   end __asm ("end");
	extern char   heap_limit __asm ("__HeapLimit");
	static char * heap_end;
	char *        prev_heap_end;

	if (heap_end == NULL)
		heap_end = & end;

	prev_heap_end = heap_end;

	heap_end += incr;

  return (void *) prev_heap_end;

FRDM K64F Printf to UART using Processor Expert

05/06/2015 4 comments

If you are using the OpenSDAv2 USB for debugging with Segger J-Link on the FRDM K64F development board within Eclipse then you may want to route Printf functions to the Segger virtual com port. This blog will cover how to set this up on Windows using Processor Expert on KSDK 1.2.0 and Eclipse Luna.


  1. Prerequisites
  2. Create New Project
  3. Configure Processor Expert
  4. Hello World Test Code
  5. View output using COM port terminal application
  6. Clock Configuration


Before you begin please make sure your development environment is setup and you can already compile and debug code using KSDK 1.2.0 on Eclipse Luna. If not please refer to my blog: Toolchain: KSDK 1.2.0 with Eclipse 4.4 (Luna) and GNU ARM Plugin

Create New Project

  1. Within Eclipse, on the top menu point your mouse over “File” menu item, this should expand out with an option to select “Kinetis Project”.NewKinetisProject
  2. Name your project, I tend to name my project starting with the type of development board or processor followed by an underscore and then purpose of the project, this allows me to create projects of the same purpose for other boards/processors. Set location of project, I use the default location under the workspace area. Click Next.NameProject
  3. Select the development board used, and click Next.DevelopmentBoard
  4. Select “KSDK 1.2.0”.
    Set location to KSDK path, I use an absolute path but you can select Environment variable if you have set up a path under Windows operating system environment variables with a name called “KSDK_PATH” that points to the location of the KSDK folder. The location of my KSDK is in the default location where KSDK would install to.
    Ensure “Processor Expert” checkbox is checked. The perspective radio button you select does not matter nor does the Project mode for this project.
    Click the Next button.SDKandPESelect
  5. Select “GNU C Compiler” and Click the “Finish” button.SelectGNUCompilerN.B. Wait a while for Processor Expert to finish generating the initial source for the project. Keep an eye on the progress when it reaches 100% by looking at the bottom right hand corner of Eclipse.GeneratingCode

Configure Processor Expert

Before you proceed make sure you can build the project now without errors. If not then make sure you have followed the instructions and understood how to setup your Eclipse environment as specified in the blog Toolchain: KSDK 1.2.0 with Eclipse 4.4 (Luna) and GNU ARM Plugin, especially the “Setting Eclipse workspace preferences” section.

  1. Open the Processor Expert perspective, this should be a button on the top right hand side of Eclipse.OpenPEPerspectiveIf it’s not there, try clicking on the “Open Perspective” button and then selecting “Processor Expert” in the form that appears.OpenPerspective


  2. Click on the “Components Library” tab, search for the component “fsl_debug_console” and double click on it.addcomponent_debugConsole
  3. Select the “DbgCs1:fsl_debug_console” in the Components windowComponent_DbgCs1
  4. Click on the “Component Inspector” tab. Then click on the three ellipses “…” button next to the Baud rate.Component_DbgCs1_BaudRate_ElipsesButton
  5. Double click on the baud rate “115200” on the right hand form and click the “OK” button.SetBaudRateNote: Note that “Clock cfg. 4” is Enabled above. We will review these settings further down in “Clock Configuration”.
  6. On the Pin Settings tab, the FRDM K64F board uses Port B 16 (PTB16) for RxD and Port B 17 (PTB17) for TxD. Make sure these are set correctly.  You can refer to the FRDM-K64F Freedom Module User’s Guide at section “11 Serial port” for these pin settings.PinSetting
  7. Make sure all component settings are saved and click on the “Generate Processor Expert Code” button within the Components window.GenerateCode

Hello World Test Code

Make sure your project can still build without errors at this point. Then open the “main.c” file, search for the text that says “/* Write your code here */” and “/* For example: for(;;) { } */” and just below it write the following code:

PRINTF(“Hello World”);


Note: PRINTF should intentionally be uppercase. This will use a printf function supplied with the KSDK.
That’s all there is to it Smile
Build your project again, it should compile without Errors.

View output using COM port terminal application

To be able to view the output of the PRINTF statement you will need a serial port terminal application. There are several good ones available for Windows but one I like to use which has other useful features available is an application called “PuTTY”. You can download the latest copy at:


You are going to need the COM Port used by your device. You can find out what yours is by opening the Windows “Device Manager” and expanding the “Ports (COM & LPT)” section. Look for the device named “JLink CDC UART Port” and in brackets you can see the COM port used.


After downloading the PuTTY file, simply run the downloaded file. Select the “Serial” radio button, in the “Serial line” text box type the COM port used by your JLink CDC UART Port, in my case its “COM3”.


One set, click the Open button. You should see a blank terminal window.


Now go back to Eclipse and run the application, you should now see the following in the PuTTY terminal window:


Clock Configuration

Congratulations if all is working well for you now. I wanted to point out what the clock configuration is that gets used. This is helpful to know if for some reason you do not have or are using the default clock settings.

If you refer to section “52.4.3 Baud rate generation” within the K64 reference manual K64P144M120SF5RM, we can see the Baud rate is a calculation of the following:

UART baud rate = UART module clock / (16 × (SBR[12:0] + BRFD))

  • UART module clock: is one of 5 clock configuration sources we can choose from set on the clock manager.
  • SBR: is a module clock divisor we use that can be a number between 1 and 8191.
  • BRFD: is a fractional fine-adjust counter that adds fractional delays to the baud rate clock to allow fine trimming of the baud rate to match the system baud rate. Basically any fraction by 32 bits (n/32).

Lets take a look at the clock manager to see what the settings are in this example. Go into the Processor Expert perspective. Select the “clockMan1:fsl_clock_manager” component in the Components window.


In the Component Inspector window, select the “Clock settings tab” then the “Clock sources” tab. Take note of the clock frequency  under the System oscillator 0 section.


Now click on the “Clock configuration” tab then select the “MCG settings” tab. Now select the “clockMan1_InitConfig4” configuration which is the one we used for the “DbgCs1:fsl_debug_console” configuration. Note we are using System oscillator 0 here and the MCG mode is “PEE” which uses PLL settings, so looking at the PLL settings we can see 48 MHz is entered as the desired output clock.


Now select the tab “System clocks” tab. If we refer to section “5.7.10 UART clocking” within the K64 reference manual K64P144M120SF5RM, we can see that UART0 uses the core/system clock which should be set to 48 MHz.


Ok, so coming back to the baud rate formula:

UART baud rate = UART module clock / (16 × (SBR[12:0] + BRFD))

    115,200 Hz = 48 MHz (or 48,000,000 Hz) / (16 × (SBR[12:0] + BRFD))

16 × (SBR[12:0] + BRFD) = 48,000,000 Hz / 115,200 Hz

16 × (SBR[12:0] + BRFD) = 416.6666666666667

(SBR[12:0] + BRFD) = 416.6666666666667 / 16

(SBR[12:0] + BRFD) = 26.04166666666667

So therefore SBR can equal 26

BRFD can be calculated as 0.04166666666667 * 32 = 1.333333333333333 but must be rounded to a whole number thus = 1.


Ok so maybe that’s a lot of detail on the calculation but I hope this helps when you are trying to use different clock settings.