Question: What to do on a rainy Sunday?
Answer: Having fun with USB and the KL25Z Freedom board! :-).
In “A shell for the Freedom board” I used the UART-to-USB OpenSDA capability of the KL25Z Freedom board: The KL25Z processor uses the OpenSDA K20 microprocessor as Serial-to-USB converter. But this only works because of the P&E OpenSDA USB CDC (Communication Device Class) implementation. If I create my board without OpenSDA, I need a different approach: I want to do USB CDC with the KL25Z :twisted:.
For several months I’m using successfully my Processor Expert FSL_USB_CDC component since early this year, in several projects and with different boards. What is missing is support for the Kinetis KL25Z. So this is what this tutorial is about. It takes you maybe around 30 minutes, and you will have USB support with your Freedom board :-). As for myself, after learning all the knowledge needed, it takes me less than 10 minutes :grin:.
I’m using CodeWarrior for MCU10.3 with my Processor Expert components. If you followed my earlier Freedom Board tutorials, then I hope you are familiar with loading more user components. Otherwise, have a look at the section “Additional Processor Expert Component Installation” in this post. In this tutorial I’m using following components:
- FSL_USB_Stack: Freescale USB Stack as Processor Expert component.
- Wait: Universal realtime waiting functions.
- Optional: LED: Universal LED driver.
❗ The FSL_USB_Stack Processor Expert component has been updated to version V1.008 to support the KL25Z
Step 1: Creating the Project (or reuse an existing one)
In this tutorial I start from a clean sheet and create a new project. Of course it is possible to add USB CDC support to any of the other tutorials I have published for the Freedom KL25Z board, e.g. Tutorial: Enlightening the Freedom KL25Z Board. In that case, you can skip this step.
To create a new project, I select the menu File > New > Bareboard Project and give it a project name:
Next is to select the device:
I’m going to debug the board with OpenSDA only, so I deselect the default P&E Multilink, and select Open Source SDA:
The next dialog is about the language and build tools options: I go with the defaults:
In the next dialog I make sure I select Processor Expert:
Pressing Finish will create the project:
💡 Hint: In case the extra Processor Expert views are not already open: I use the menu ‘Processor Expert > Show Views’.
Step 2: Adding the Components
The next step is to add my other component(s): I select the component(s) in the Components Library view and add it to my project. If I already have the Wait component in my project, of course no need to add it again.
This will add the components to my project. And the USB component shows a red (x) telling me that it needs to be configured:
I need to component Inspector to configure the properties.
💡 The context menu ‘Inspector’ on a component opens the Component Inspector View.
If I inspect the properties of the USB component, it shows me that I need to set up the CPU and the USBInit property:
So I select the CPU for my KL25Z board, and select Init_USB_OTG_VAR0 to initialize the USB peripheral for it:
❓ No idea why Freescale has decided to name that Kinetis component as ‘Init_USB_OTG_VAR0’. A name like ‘Init_USB_OTG_Kinetis’ would have been *much* easier to use and remember.
The USB CDC stack is using two ring buffers:
Make sure that the buffers (Rx and Tx) has enough buffers specified. Recommended is a minimum size of 32 bytes:
The next thing is to inspect the USBInit component. And it is good to pay close attention to the warnings:
Enabling the Clock gate ensures that the USB module is clocked. And as I have no external clock pin, I select to use the PLL/FLL clock source:
The inspector informs me about a very important thing: the USB module requires a 48 MHz clock. So I need to make sure that this is configured properly.
❗ Warning: Failing to configure the USB clock properly is probably the most common source of failure. For myself I can count endless hours debugging and inspecting my projects, and in many cases I made a mistake in the clock configuration. Unlike many other USB enabled devices, the Freescale ones need an external crystal, and that crystal has to be used to generate a very stable and accurate clock signal. Otherwise it will *not* work.
Step 3: Configuring the Clock
According to the FRDM-KL25Z Schematics (SPF-27556_D).pdf have a 8 MHz crystal on the board:
❗ IMPORTANT: I’m using in this post the ‘white’ pre-production Freedom Board. The black production board board has several differences (see Completing the FRDM-KL25Z Board). An important difference is that the black board has the 1.0MOhm resistor R25 nearby the 8 MHz: with that resistor *not* populated, the clock will *not* run in high gain mode. So for the black Freedom board with that resistor *not* populated, the clock mode has to be in ‘low power’ mode.
The configuration of the clock is in the CPU component. For this I select the CPU to configure the properties:
I can have multiple oscillator settings, but here I just need one. So I enable the ‘System oscillator 0’ setting, and configure it to use an 8 MHz external crystal in High gain mode (for the white pre-production board which has the R25 (see above) populated, but in Low Power mode for the black production board:
As the black Freedom board has no R25 populated, the Oscillator operating mode has to be ‘Low power’ instead:
Next is to select the PEE (PLL Engaged External) clock mode: in this mode, the PLL is using the external reference clock. Remember that the USB block needs an 48 MHz PLL signal? So I need to configure it to 96 MHz as it will be divided by a factor of 2 until it reaches the USB block:
With my clock changes, the core clock is not set correctly:
With my base clock of 8 MHz, I can set the CPU core clock to 48 MHz and a Bus clock of 24 MHz:
Now I could think that everything is just fine. But there is one possible glitch, and maybe this is even a silicon problem (?): I need to *disable* the Internal and External reference clock, otherwise my board will crash during clock configuration. So I need to *disable* the reference clocks:
Checking my USB module again, it shows that it is now properly clocked with 48 MHz:
😕 Processor Expert still warns about the need for 48 MHz clock, even I have it set up with 48 MHz? Anyway, the important thing is that it *is* clocked with 48 MHz.
Step 4: Adding Application Code
I keep things very simple here: no RTOS. All what I add in Processor Expert is a simple loop-back which does an echo of what I type into the terminal window.
To show the current enumeration status, I’m using my code from my earlier Tutorial: Enlightening the Freedom KL25Z Board.
❗ Hint: An easy way to copy Processor Expert components from one project to another is using copy-paste. If you do not want to use the LEDs, then simply remove the code for the LEDs in the code below.
I’m adding the function CDC_Run()
to the ProcessorExpert.c
as below and call it from main()
:
Note: Later version of the component is using CDC1_ Prefix for functions, as the methods have been moved to a separate CDC submodule.
/** ################################################################### ** Filename : ProcessorExpert.c ** Project : ProcessorExpert ** Processor: MKL25Z128VLK4 ** Version : Driver 01.01 ** Compiler : GNU C Compiler ** Date/Time: 2012-10-07, 12:33, # CodeGen: 0 ** Abstract : ** Main module. ** This module contains user's application code. ** Settings : ** Contents : ** No public methods ** ** ###################################################################*/ /* MODULE ProcessorExpert */ /* Including needed modules to compile this module/procedure */ #include "Cpu.h" #include "Events.h" #include "WAIT1.h" #include "USB1.h" #include "USBInit1.h" #include "Tx1.h" #include "Rx1.h" #include "LED1.h" #include "LED2.h" #include "LED3.h" #include "GPIO1.h" #include "GPIO2.h" /* Including shared modules, which are used for whole project */ #include "PE_Types.h" #include "PE_Error.h" #include "PE_Const.h" #include "IO_Map.h" /* User includes (#include below this line is not maintained by Processor Expert) */ static uint8_t cdc_buffer[USB1_DATA_BUFF_SIZE]; static uint8_t in_buffer[USB1_DATA_BUFF_SIZE]; static void CDC_Run(void) { int i; for(;;) { while(CDC1_App_Task(cdc_buffer, sizeof(cdc_buffer))==ERR_BUSOFF) { /* device not enumerated */ LED1_Neg(); LED2_Off(); WAIT1_Waitms(10); } LED1_Off(); LED2_Neg(); if (CDC1_GetCharsInRxBuf()!=0) { i = 0; while( i<sizeof(in_buffer)-1 && CDC1_GetChar(&in_buffer[i])==ERR_OK ) { i++; } in_buffer[i] = '\0'; (void)CDC1_SendString((unsigned char*)"echo: "); (void)CDC1_SendString(in_buffer); (void)CDC1_SendString((unsigned char*)"\r\n"); } else { WAIT1_Waitms(10); } } } /*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!!! ***/ PE_low_level_init(); /*** End of Processor Expert internal initialization. ***/ CDC_Run(); /*** 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!!! ***/ #ifdef PEX_RTOS_START PEX_RTOS_START(); /* Startup of the selected RTOS. Macro is defined by the RTOS component. */ #endif /*** End of RTOS startup code. ***/ /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/ for(;;){} /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/ } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/ /* END ProcessorExpert */ /* ** ################################################################### ** ** This file was created by Processor Expert 10.0 [05.03] ** for the Freescale Kinetis series of microcontrollers. ** ** ################################################################### */
❗ It is important that the application calls App_Task() frequently, because with this routine data is sent and received.
Step 5: Running the Application
Now I can generate code for my drivers, e.g right click on the ProcessorExpert.pe file and selecting ‘Generate Processor Expert Code‘:
followed by building the sources (menu Project > Build Project). And then download/debug it.
With the USB plug disconnected, the red LED is on:
With connecting the USB cable to the KL25Z, it enumerates the device and the green LED is on:
Additionally it has been enumerated as device on my host machine:
In case it is the first time you use such a CDC device: the driver .inf file is generated in the ‘Documentation’ folder (for details see USB CDC, reloaded):
I connect to the virtual CDC COM port with a terminal program. And the application will echo what I send to it:
Summary
Setting up and using a USB stack is definitely not a trivial task, as a lot of settings needs to work correctly. I hope that with the above information it should be much easier to do this now for the Freescale FRDM-KL25Z board. Using Processor Expert makes things definitely a lot easier. While the above project is bare-metal (no RTOS), it is easy to add an RTOS to it. That’s actually how I use it like in the Freedom Shell project.
The above project can be downloaded here or from the link on http://www.steinerberg.com/EmbeddedComponents/Examples/Examples.htm
Happy USB Freedom 🙂
Hi Erich,
Would you happen to know if CDC1_App_Task() attempts to re-enumerate the microcontroller as a USB device if the first attempt at enumeration fails?
I know for a fact that it is always the USB host (the computer) that initiates enumeration when an electric change is detected on the USB wires. But is it possible for CDC1_App_Task() to trigger successive attempts at enumeration if the first one fails?
I have eight KL46-based boards that fail to enumerate in about 1 out of 40 times that I plug each board straight to the computer. They tend to fail right after I reset the test computers (Dell and HP laptops running Windows 7). I have run this test many times with several of the boards.
At the start of my firmware I check how many times CDC1_App_Task() returns ERR_BUSOFF. If enumeration is not detected after X number of attempts then the boards will conclude that they have been plugged in to a USB power supply, like a mobile phone charger, instead of a USB host.
I used TotalPhase’s Beagle USB 12 hardware analyzer to check the situation and I managed to capture several of the failed enumeration attempts. In each of the failed attempts the analyzer says that the first device descriptor sent from the KL46 to the computer has an invalid length.
Currently the boards wait 2.5 seconds before they give up on the enumeration. I still get 1 failed enumeration out of 40. I can keep increasing the timeout counter but I’d like to know if further increasing this timeout count has any hope of solving the problem. These reliability tests are very time consuming.
If CDC1_App_Task() doesn’t re-attempt enumeration then it won’t matter how long I have the boards wait for enumeration. Even more, this would mean that there’s some bugs in Freescale’s USB stack. If that’s the case then I need to report this so the good folks at Freescale can look into it 😉
Thanks in advance!
LikeLike
Hi Erich,
Apparently Windows 7’s USB host controller attempts to enumerate a USB 1.0+ and USB 2.0 device three times before it reports it as an Unknown Device in the Device Manager.
Here’s the related paragraph from a post by Windows’ USB developer team:
http://blogs.msdn.com/b/usbcoreblog/archive/2009/10/31/how-does-usb-stack-enumerate-a-device.aspx
Timeout of Port Reset:
In the case of a timeout of the first reset request, the hub driver will attempt to retry enumeration up to 3 times by returning to the beginning of the “First Port Reset” state. A delay of 500ms occurs between each retry to allow the device to settle. If the port reset times out on the 3rd retry, enumeration will be cancelled and an “Unknown Device” will be reported to PnP.
I’m going to increase my KL46’s enumeration timeout period from 2.5 to 5 seconds and see if I can still catch a failed enumeration with the USB analyzer. If I still experience failed enumerations then I’ll know there’s something fishy going on with the USB stack on the KL46. Or maybe an interrupt on the KL46 side is messing up the enumeration?
I’ll let you know what happens.
Thanks again!
LikeLike
Hi Erich,
Have you or your students had any luck communicating independently with two Freescale USB CDC devices simultaneously connected to the same host computer without each device causing communications problems to each other?
Both of my KL46 devices are using the default vendor, product and serial numbers (0x2504, 0x0300, 0x00) that come with Freescale’s USB stack. In the USB protocol, a serial number of 0x00 means that the device doesn’t have a serial number.
The problem I’m experiencing is that both devices see each other’s communications with the host computer. Each device is only supposed to communicate with the host computer and never among each other. Currently, device A sees the communications intended for device B and considers them as corrupt packets because the USB packets contain “invalid PID” sequences (PID = USB packet ID). The contents of the corrupted packets are either the enumeration sequence for device B or other commands that my software is trying to send to device B. I figured this out by monitoring one of the device’s USB traffic using a USB analyzer.
Both devices show up as separate COM ports on Windows 7’s Device Manager. But I noticed that Freescale’s USB stack doesn’t populate the “iSerialNumber” property for the device’s USB descriptor. Furthermore, I don’t see a way to set the iSerialNumber property using Processor Expert.
Jan Axelson’s USB Complete book states that:
“Devices with the same Vendor ID, Product ID, and device release number should not share a serial number.”
It also states that:
“Serial numbers are useful if users may have more than one identical device on the bus and the host needs to remember which device is which even after rebooting.”
Have you or your students experienced this problem? Would assigning separate serial numbers to each device solve the problem? Is it possible to set the iSerialNumber property with Freescale’s USB stack?
Thanks in advance!
P.S. I’m still trying to figure out the occasional enumeration problems but this problem with the corrupt packets is more serious than that.
LikeLike
Hi Carlos,
no, I have not seen problems with multiple identical devices/serial numbers attached so far. But very likely, it could be a spurious problem. I’m thinking that maybe best the CPU UUID could be used as serial number, so I have to look into this.
LikeLike
Hi Erich, look i successed in connecting Freedom board with PC, via USB.. And manage a LCD Display through it.
But this worked fine in Windows, not in linux, when i plug it in a PC with Ubuntu, this message appears http://www.subirimagenes.net/i/140819085609430571.png . Its a deal with driver but i dont know how to make it work.
Thanks in advice
LikeLike
Hi Javier,
unfortunately, I don’t have such a Linux machine available, and I’m not experienced enough with these Linux drivers :-(. So I believe it must be something going wring with your USB drivers installation for USB CDC?
LikeLike
Hello again Erich,
Maybe this could save you some work in answering my question about configuring the USB descriptor’s iSerialString. I see that the Processor Expert component for Freescale’s USB stack generates a file called “usb_descriptor.c”. This file contains the vendor and product IDs as well as a “Serial number string index”. It seems like this string index is the memory address location where the serial number should be stored. But it also looks like this is hard coded to zero and I’m not sure how to override this or the actual value for the serial number.
Thanks again! Hope this helps!
LikeLike
Hello again,
I tried giving my second board a different USB product ID and this didn’t solve the “crosstalk”. Furthermore, I noticed that the only communications that cause “crosstalk” are the communications in the direction from the computer towards the devices. But not from the devices towards the computer.
So, regardless of whether both devices are using the same VID/PID or not, device A always sees packets that the computer tries to send to device B as corrupt packets. These packets can be USB enumeration control transfers, opening/closing of a COM port, commands I send, etc. However, device A never sees the packets that device B sends to the computer (which is good). This tells me there’s still some problem that the computer is having with being able to uniquely address each Freescale USB CDC device. It’s strange that plugging and unplugging mice and keyboards doesn’t affect the USB CDC devices. Only Freescale devices affect other Freescale devices.
This is definitely a problem for anybody using Freescale’s USB stack when developing systems that require multiple USB CDC devices.
Maybe this is something that I should report to Freescale? Unless, of course, there’s some piece of knowledge that I haven’t learned about to get multiple Freescale USB CDC devices to work in harmony 😉
Thanks one more time!
LikeLike
Hi Carlos,
I think that might be more of a question for the Freescale forum, as this goes beyond my knowledge. About the serial number: do you still need me to look into that?
LikeLike
Hi Erich,
Thanks for your reply! I learned that it is normal for all USB devices attached to the same host controller chip to see all the “downstream” traffic. For example, its ok for both KL46Z boards to see the traffic send from the computer to either of the boards. Each board knows to discard the requests that are not meant for them. This is done by looking at the bus ID number in the packets. Each device receives a unique bus ID number when the USB enumeration completes. This is also why the USB analyzer reports “error” packets. Its because these packets are not meant for the device that is being monitored.
Some USB hubs have more than one USB controller chip. My Belkin hub has two USB chips inside it. So plugging each board to USB ports that I know to be connected to different USB chips allows me to avoid seeing the packets that the computer sent to the other board.
In conclusion, this behavior has nothing to do with any of the other issues I have with my firmware.
Thank you again for responding to my posts!
LikeLike
Questions about the Timeout feature:
I’ve read on several posts that you have mentioned using the timeout feature to prevent the firmware apps from hanging.
-How does this feature work?
-Does it also work for receiving data from the computer or only for sending data to the computer?
-What are your recommended settings for the TMOUT1 component that the timeout feature generates?
-Do I need to add additional code to my firmware to allow this feature to work as intended?
Sometimes I notice that my boards don’t reply with the USB ACK byte (0xD2) to the computer when the computer tries to write to the boards. Because of this, Windows tries to continually send the same packet to the board. I see this with C# programs I’ve written and also on other third party terminal programs like RealTerm. The only way for me to prevent my C# programs from hanging is to use a software timeout such as Microsoft’s .NET SerialPort class’ WriteTimeout property. This way if the boards don’t acknowledge the request then the software throws a timeout exception and the write request gets cancelled. Otherwise I had to use the task manager to force close my app and reset the computer to cancel the low level write request to the board. The reset was also necessary because the COM port would have been left open.
The USB analyzer shows me that if the board replies to the computer’s write request with the ACK byte, then I only see my command packet once on the USB wires. But if the board doesn’t send the acknowledge byte then the computer will keep trying to write to the board until I cancel the transaction. The problem usually goes away if I power cycle my boards. But after a couple of minutes I see the problem again.
I’m hoping that I can solve the problem if I can understand your timeout property. Otherwise, I know I have to debug somewhere else 🙂
Thanks again!
LikeLike
The Timeout component is what I use in several projects and places. What it does is it uses an array of ‘tick’ counters (or array of timeout handlers). The tick counters get decremented by each ‘tick’, e.g. every 10 ms. That decrement of tick is with the AddTick() method you have to call say every 10 ms. When the tick counter reaches zero, a timeout happened. The application gets a timeout handle, then checks if the timeout (or timer) expired, and handles accordingly. Does this make sense? Maybe I should write an article about it?
LikeLike
Hi Erich,
Thank you for your reply! I understand the general idea of using a timeout (regardless of the implementation) to prevent the stack from hanging. Is there an example on GitHub were you use this feature with the USB CDC component? If so, then a tutorial might be unnecessary 🙂 Otherwise, I’ll look into it a little bit more and come back with questions 😉
Speaking of the USB CDC component, I noticed that version 01.033 is available. I’m using FSL_USB_CDC_Device version 01.020 along with all the component versions from your commit from 24 Sep 2013.
Is there a change log for every component? I’m trying to decide whether we should update or not. Most of our firmware is working, but major changes in the components might set our development team back if we have to call different methods or interact with the components in a different way. However, if your update to the FSL_USB_CDC solves our current USB issue then we would gladly spend a day or two updating the rest of our firmware around any other major component changes you have made. The intermittent lack of the KL46’s USB acknowledge byte to the computer’s serial write requests seems like a low level problem. So updating to your new version is very tempting. But it could also be that we’re causing our problems with our use of interrupts.
We’re using the following components: AD1, BitIO, GenericI2C, Init_GPIO, LED LDD timers, LDD SPIMaster, Utility and Wait. Maybe you have a log of the specific changes you’ve made since 24 Sep 2014?
Thanks again!
LikeLike
About using a timeout: the USB_CDC_Device component has a setting to enable timeouts. If enabled for a 100 ms timeout, this then is used in CDC1_SendDataBlock() like this:
byte CDC1_SendDataBlock(byte *data, word dataSize)
{
TMOUT1_CounterHandle timeout;
uint8_t res = ERR_OK;
transactionOngoing = TRUE;
if (USB_Class_CDC_Interface_DIC_Send_Data(CONTROLLER_ID, data, dataSize)!=USB_OK) {
transactionOngoing = FALSE;
return ERR_FAULT;
}
/* wait for transaction finish */
timeout = TMOUT1_GetCounter(100/TMOUT1_TICK_PERIOD_MS); /* set up timeout counter */
while(transactionOngoing) { /* wait until transaction is finished */
CDC1_RunUsbEngine();
if (TMOUT1_CounterExpired(timeout)) {
res = ERR_FAILED;
break;
}
}
TMOUT1_LeaveCounter(timeout); /* return timeout counter */
return res;
}
LikeLike
About log for every component: I don’t maintain a specific log file or similar, but every change with a commit message is available on GitHub. Unfortunately *not* for the USB stack sources, as Freescale did not allow me to share the sources (I still would debate that I’m allowed to share them according to the license agreement, but Freescale insisted on their position). But the components AD1, BitIO, Init_GPIO, LDD timers, LDD SPIMaster are Freescale owned components, and I do not maintain or provide them. But mine are for example Utility and Wait. You can see all the commits here:
https://github.com/ErichStyger/mcuoneclipse/commits/master
I hope this helps.
LikeLike
Thank you Erich! This points me in the right direction!
LikeLike
Hi.
I’d like to add a Rx1_OnItemAdded event to the RingBuffer in order to get a pseudo interrupt-driven CDC setup. Does this seems like a reasonable / expedient way to get this functionality?
I am new to PE and the format of the drv, etc. files, so if you could point me to any tutorials on that I’d appreciate it.
Thanks,
Greg
LikeLike
Hi Greg,
yes, there is a tutorial on CDE here: https://mcuoneclipse.com/2013/03/31/tutorial-creating-a-processor-expert-component-for-an-accelerometer/
What you are asking for is not a big deal, and actually I should have it implemented it at the beginning. I should be able to commit something to GitHub tonight. Then you can see the changes made.
LikeLike
I was able to edit the files by hand to add this. Works great!
I can do a pull request if you want it.
LikeLike
oh! I was travelling by train and have now already committed this:
https://github.com/ErichStyger/mcuoneclipse/commit/d9d0fdd14cfc717384d352db8adda866acacdb1c
Would that work too?
LikeLike
+1 Thank you for your site and this article. I’ve been testing your example code on my Freedom board successfully. (I also walked through manually creating a bare-bone project that works too.)
I now have a custom board with a K22FN1M0VLH12 (64-pin) processor. I walked through the steps to create a bare-board project, but I’m getting compile errors from the generated USB1.c output in regard to NVIC_ICER, NVIC_ICPR, NVIC_ISER being undeclared. If I select one of these USB interrupt definitions and press F3 to drill down to the declaration, the IDE correctly finds it under IO_Map.h. Is there something simple I’m not doing correctly for this to find these definitions? I have CW10.5. Thanks!
LikeLike
That file under IO_Map links to the library files, provided with the Processor Expert libraries. They should be ini MCU\ProcessorExpert\lib\Kinetis\iofiles. If the compiler does not find it, then probably you do not have this path present in your compiler include paths. Check your project settings (compiler options) if it contains “${ProcessorExpertPath}/lib/Kinetis/iofiles”
LikeLike
I checked there and everything was setup. A passed my co-worker my project, and after he installed your latest .PEupd files it compiled. I should have updated first as I was using something from June. It now compiles. Thanks!
LikeLike
Sorry for that! I update the sources/project about once a month to make sure things are up-to-date. Unfortunately there is no easier way to get notified about updated except you are using git.
LikeLike
Hello Erich,
Two questions:
#1:
Do you think it’s possible for the Multilink FX debugging probe to alter the KL46 firmware’s behavior when using in-circuit debugging? I’m still trying to figure out why sometimes the KL46 units will fail to respond to USB messages. That is, they fail to generate the USB acknowledge byte (0xD2). By that I mean that I’ll use a serial terminal software or my PC software to write messages to the KL46 (running as a USB CDC device) and all goes well for a couple of minutes but eventually the KL46 will stop acknowledging incoming USB messages. I’ve verified this with a USB analyzer.
I ask about in-circuit debugging because I’m running two KL46 boards to debug this problem. One board is using in-circuit debugging via a Multilink FX with a watchpoint on the USBx_ERRSTAT register. The other board is my “control subject” and runs without being connected to any debugger. Both boards use the same firmware. All of my boards (I have about 10 of them running three slight variations of the same firmware) show this USB problem. But whenever I use in-circuit debugging, the problem seems to disappear for the unit that’s being debugged. The “control” units always show the problem after a couple of minutes.
Maybe the debugger alters some time sensitive behavior in the USB module and this prevents the problem from occurring? I find that hard to believe because that would mean that I can’t trust the debugger. In any case, I can’t catch USB error interrupts if the debugger prevents these interrupts from being generated.
I know for a fact that it is the KL46’s USB module’s job to generate USB acknowledge bytes (0xD2) when the computer tries to send USB CDC messages to the KL46. This is shown in page 632 of the KL46’s reference manual. Therefore, the USB stack has nothing to do with USB ACK byte generation. Page 632 also states that “token done” interrupts are generated by the USB module when the USB module generates or receives USB ACK bytes. To deal with USB RX transaction issues, the USB module can generate two types of DMA overrun error interrupts: the bus timeout interrupt and the generic “DMA error” interrupt. I was expecting to catch USB error interrupt flags on the USBx_ERRSTAT register. But I can’t if the debugger is interfering with the KL46’s USB behavior.
Question #2:
How can I cause the PEx USB stack component to call a specific method when the USBx_ISTAT and USB_ERRSTAT registers reflect a USB error? I noticed that the FSL_USB_CDC_Device component offers an “OnError()” event. But this event doesn’t report the low level errors defined by the USBx_ERRSTAT register.
However, I did notice that the USB stack’s USB_ISR() seems to include a mechanism for calling custom methods when the USBx_ISTAT register detects a USB error. This is done within the USB_ISR() by calling the USB_Device_Call_Service() method. This method checks if a callback function has been registered for the particular USB error and then it calls that function. Unfortunately I don’t understand how to register my methods as a USB error callback function within the USB stack. I think I could call “_usb_device_register_service()” in “usb_driver.c” to register a custom callback function. But when I open the “_usb_device_register_service()” method’s declaration I see that this method is compiled as an empty method since the “MULTIPLE_DEVICES” parameter is undefined.
Any suggestions would be appreciated. By the way, the KL46 boards always acknowledge control transfers (i.e. when the computer opens the corresponding COM port and tries to set a baud rate, etc) even after the boards stop acknowledging CDC serial messages.
This USB error has been haunting us for several months since the product users would be forced to power cycle the product every couple of minutes 😦
Thanks again Erich!
LikeLike
Hi Carlos,
on question #1: what comes to my mind is that if you attach a debug probe, you alter the device for sure on the electrical side. Not sure if this is your problem, but the debug probe has ground and Vcc connection to the target, and that might have an influence. I’m not sure, but if you have a custom KL46Z board this might cause problems. I had cases where without the debug probe attached, the device did silent resets, while with the debug probe the power supply and reset line were stable.
And if you are using a watchpoint, then I’m I believe that might be intrusive: means it alters slightly the timing of the processor. So does it happen with and without watchpoints too? You might verify the electrical behaviour with just hooking up the debug probe, but not debugging.
LikeLike
Thanks Erich! That’s a good suggestion, I’ll check if the debug probe affects the behavior even without running the debugging connection. I will also check the behavior by removing the watchpoint with the debug probe attached but without debugging.
Any comments regarding question #2? 🙂
LikeLike
Hi Carlos,
I appologize for my late answer (trying to catch up on my huge backlog 😦 ). I checked about your question #2, and honestly I do not understand why this code is guarded by MULTIPLE_DEVICES. That macro seems to indicate that it is for dealing with multiple devices, but should not be required if you want to have custom hooks.
You might give a try and enable that define in your compiler/projects settings, to see if that works? Of course I could provide a custom hook with Processor Expert, but if possible do not want to divert from the original USB stack.
LikeLike
Hi Erich,
I am reading values from an accelerometer and sending to the computer via usb cdc with FRDM kl25z. Now, I want the firmware only proceed when all bytes are sent to the pc! For this I am using the following statement
while(CDC1_GetCharsInTxBuf() != 0){}
However, the program gets stucked in this loop! The program on the computer receives the bytes if I dont put that loop! But I want control the bytes arriving!
What do you think might be happening?
Thanks,
Matheus
LikeLike
Hi Matheus,
Are you still serving the USB with CDC1_App_Task()? Without this, the USB input/output buffers do not get processed.
Erich
LikeLike
Hi Erich,
We have a problem with using the FSL_USB_CDC on a custom board with a MKL25Z MCU: after some time, sending data to the board stops working, while receiving data continues to work. The time until this happens can be everything from a couple of minutes to several hours (the amount of data that is sent/received is constant over time). I have tried increasing buffersizes, how often CDC1_App_Task() is called etc. to no avail.
So, for reference, I went back to the freedom board and the example code in this post, and I can still see the same problem. Just by typing characters in fast succession (ok, sometimes I need the help of an Autoit script). I have added a periodic printout in the else clause in the program, so I can verify that sending from the freedom board continues to works. And, if I remove the 10 ms wait in the else clause, it’s really easy to trigger this.
Any idea what might be the problem here?
Thanks,
Anders
LikeLike
Hi Anders,
I have some ideas for you. I’ve been dealing with a similar problem. Do you happen to have a USB analyzer? If so, could you check if your board is forgetting to send the USB acknowledge byte (0xD2) to the computer?
Also, could you check what happens to your USB ERRSTAT register when the problem occurs? (particularly bits 4 and 5, but any of the other bits might give you a clue to what kind of error you’re experiencing).
Lastly, are you using the most recent Processor Expert components? The last update to the FSL_USB_CDC_Device component seems promising for our problem. It was updated 5 days ago. See this post:
https://github.com/ErichStyger/mcuoneclipse/pull/18
If you’ve been using the PEupd packages to update your components then you probably have to manually download the update for the USB CDC component from Erich’s Github account.
Moreover, in February Erich started using the CriticalSection component to fix a problem with Freescale’s EnterCritical() and ExitCritical() macros. These macros are used to make the Processor Expert components more robust against problems with interrupts and global variables. Specifically, the ring buffer component (which is used by many other components) was getting corrupted every once and a while. But Erich’s CriticalSection component fixes this.
Here are the reasons why I’m asking the above questions:
In USB 2.0 full speed communications there are three steps to a successful USB write transaction:
1) The computer sends an “OUT” token (a write request) to the USB device.
2) The computer transmits the data that your custom software or terminal is outputting. This can be any ASCII message like “hello”, etc.
3) The USB device acknowledges the write request by replying with an acknowledge (ACK) byte. This is simply the “0xD2” character. This character tells the computer that the transfer was successful. Note that this doesn’t tell the computer that your device has agreed to respond to the message by blinking a light, sending some data, etc. That depends on your firmware.
It is also important to note that the ACK byte is produced by the KL25’s USB silicon module instead of the USB stack, the CDC or your firmware. But still, finding out what kind of error you’re experiencing will help you program the proper response for your KL25.
According to Rev. 3 of the KL25Z’s reference manual (pgs. 619-620), USB transactions can fail because of a DMA overrun error and this could be reflected on either bit 4 (BTOERR) or bit 5 (DMAERR) of the USB ERRSTAT register. So it’s a good idea to regularly check what happens to this register. You are lucky that your board can still send out messages even though it cannot receive messages. This would allow you to send out the contents of the USB ERRSTAT register without having to use a debugger probe. I suspect that in my case, the debugger probe is affecting the USB behavior of my board.
I hope this helps.
Carlos
LikeLike
Hi Carlos,
That last update to the FSL_USB_CDC_Device component seems to have done the trick!
I haven’t done any checking of the ERRSTAT register, and I don’t have a USB analyzer. But it seems logical that the fact that the original FSL_USB_CDC_Device component only was made for sequential TX/RX communication was the problem, as our application uses asynchronous TX/RX. It also explains why it was so easy to hang the test program once you remove the 10 ms wait.
Interesting thing that about critical section. We have had problems to communicate reliably with a radio chip on the SPI bus, if larger blocks than 2 bytes are sent and a USB device is present (no problems with a KL15 MCU). And the SPIMaster component seems to not be using the CriticalSection component.
Thanks for the help!
Anders
LikeLike
Hi Erich,
Thanks for your reply. I’m testing your most recent upgrades to the USB CDC device component to see if this has a positive impact on my USB issue. Other than that, yes I can try to define the MULTIPLE_DEVICES variable and also I figured out a way to report the low level USB errors from the USB ERRSTAT register through the USB CDC device component. Using this idea the application layer could be notified with the contents of USB ERRSTAT via the CDC component’s OnError() event. All that’s needed is to modify the code for the CDC component so the CDC App_Callback() method calls the OnError() event when App_Callback() receives the USB_APP_ERROR parameter. This edit needs to be performed on “FSL_USB_CDC_Device.drv” between lines 598 and 601. I’m hoping to try this in the next two days. If it works then I’ll send you a pull request.
Carlos
LikeLike
Hello,
I get the processor expert module to work easily following the tutorial but the problem comes when I try to communicate with the board from a VS application. I managed to make a scan of all the usb devices connected on the PC and simply display the list but the Freedom board is not seen (I display the vid and the pid of each device). When I tried to communicate with the board using Termite, everything was ok, so I don’t understand what I missed as the installation of the CDC driver was done easily. The freedom board is installed and seen as COM8 in the peripheral manager so a question is is it really an usb device?
Thanks for the support in advance
LikeLike
Stupid I am
The value of pid and vid is hexa in provessor expert and I was working with decimal values in Visual Studio… so everything is ok.
Anyway, thanks for the modules and for the tutorials wich are very helpful.
Sébastien
LikeLike
finding out the problem myself is what happens to me many times too. The good thing is that we all should feel good about it: it is solved 🙂
LikeLike
Hi Erich and Anders,
I’m happy to report that Kevin’s commit to the PEx CDC device component also fixed my problem with USB data reception on the KL46Z. I have ran about 50 trials since yesterday without experiencing the problem. Before I was experiencing the problem within 5 to 10 trials and the only solution was to reset the custom KL46 board.
I’m very thankful for the update to the PEx component and I hope it soon gets included in the SourceForge PEupd release so others can avoid this issue.
@Erich: How does Kevin’s fix work? I’m still confused about why commenting out and adding in “USB_Class_CDC_Interface_DIC_Recv_Data(CONTROLLER_ID, NULL, 0);” can have this effect with data reception.
LikeLike
Carlos,
I admit, I’m surprised too that this change has such an effect. I should get an USB analyzer very soon, so hopefully this will give me some insights what is going on. Otherwise maybe Kevin can comment.
Erich
LikeLike
Hello,
I’m experiencing problem to initiate the communicate with the KL 25Z board running the soft coming from that tutorial. In fact, scanning the device works good, I can get some general informations from the device, but when I try to open the usb port, I get a NOT_SUPPORTED error. I’m trying to communicate with the board running an application using the libusb library. As I’m a newbie with usb communication, I don’t know what can be wrong. Maybe a compatibility issue? Does anyone has run this example with libusb? If not or in case it’s not compatible, can anyone recomand an available solution to communicate at maximum speed possible with the board?
Thanks,
Sébastien
LikeLike
I’m not using libusb, and I have not face such a problem with normal USB CDC/Terminal applications.
LikeLike
What kind of usb driving layers do you use to send/receive on the usb on PC side? Should the communication link be treated as a standard serial port? I thought that doing so would cause to get an emulated RS232 port.
LikeLike
I’m using the normal Windows driver on the PC side: usbser.sys
That way I have a virtual COM/serial port.
LikeLike
If I understand well, using usbser.sys permits to deal with the port as a standard serial port in the PC application, but how can I get the maximum speed supported by the device using standard serial port API?
LikeLike
For my projects, the speed always has been suffient, so I had not to use a different approach.
LikeLike
Hello Erich,
Is there a chance that you made/have PE component for MKL24Z64VFM4 for USB CDC setup 🙂 ?
LikeLike
Hi Zoran,
I don’t have that device, but you might give it a try if it works with the KL25 settings?
Erich
LikeLike
I tried that first :-). Then I tried using other cpu’s.
It gives me an error for kl25:
Description Resource Path Location Type
‘WDOG_REFRESH’ undeclared (first use in this function) left-hand operand of comma expression has no effect [-Wunused-value] wdt_kinetis.c /apple_airplay_module/Generated_Code line 44 C/C++ Problem
I guess it needs proper setting of kl24 registers.
I there a way I could add this cpu into this usb wrapper, without making new component?
BR,
Zoran
LikeLike
Ok, I see now your problem. I will add KL24 to the list of CPU’s. I should be able to release it tomorrow or so on SourceForge. Would that help.
LikeLike
Thanks for the support!
BR,
Zoran
LikeLike
And about using kl26 or kl25 with KDS?
How can I procede? There isnt support from KSDK or USB stack for these processors. How can I do a virtual com application on KDS?
LikeLike
I support KL26Z and KL25Z with my USB components, and they work as well in KDS. So this is supported. And USB CDC device is supported too.
LikeLike
Hey Erich,
Hate to dig this up from the dead, but I’ve got KDS and MCUExpresso up, and neither make it very straightforward to bring up a CDC “module” for the KL26 as shown in this example. The options seem to be either a PE implementation that has a generic “USB Module” or a CDC example from the SDK that doesn’t have PE compatibility.
Is this something you would be willing to revisit with current versions of the tools?
LikeLike
Hi Andrew,
I agree with you: Processor Expert made it so much easier to bring up things compared to the SDK, but unfortunately it is not much I can do about it. I keep my Processor Expert components alive, but the same time NXP is moving away from Processor Expert.
Maybe you missed it, but the USB CDC component I maintain does (or should) support the KL26Z too.
What I have managed to get working (and this works very well) is a combination of the ‘McuLib’ (which is mostly generated from Processor Expert, see https://github.com/ErichStyger/McuOnEclipseLibrary for the sources) and NXP MCUXpresso SDK. I have it even working with USB CDC, and an example project I’m actively using is here: https://github.com/ErichStyger/mcuoneclipse/tree/master/Examples/MCUXpresso/tinyK22/tinyK22_RaspberryPi_UPS.
It works perfectly for me to get USB CDC working on a K22. I admit I have not used it with the KL26Z using the SDK.
I hope this helps,
Erich
LikeLike
Hi Erich
Is it possible to reduce FSL_USB_Stack size? I’m using the CDC for a bootloader and I should reduce USB size.
Thanks
LikeLike
Have you turned on the compiler optimizations? This will greatly reduce the code size.
LikeLike
If I create an empty PEx bareboard project for KL25Z128, its size is 6KB. If I add the FSL_USB_Stack, its size is increased through 25KB.
How can I optimize the size of a component? I know if a method isn’t used, it isn’t compiled (for example AppTask).
Thanks!
PS: By the way, did you take a look of this?
https://mcuoneclipse.com/2013/04/28/serial-bootloader-for-the-freedom-board-with-processor-expert/#comment-41923
LikeLike
Hi Juanma,
I thought I had responded to that question already, but looks my answer did not make it through the system. Anyway, I have responded right now again, I appologize for that problem :-(. As for the code size increase: this is not unexpected. I mean the USB stack is not a simple piece of software. Or what code size did you expect? It is certainly in the range of 10-15 kByte (if not more) for a USB stack. If you are looking for something smaller, then I recommend that instead USB a normal serial connection is used? And have you enabled compiler optimizations?
The other point is: not only the things you call are used/linked: keep in mind that everything referenced from an interrupt is linked too. As you have the USB interrupt in your application/USB stack, every function called from the USB interrupts are linked too. This is the reason why you have that code size increase, even if you do not call directly the USB functions from you application. I hope that makes sense?
Erich
LikeLike
Pingback: USB with the Freescale FRDM-K22F Board | MCU on Eclipse
Hi Erich
I’m trying to develop an application using USB CDC with KL25Z.
But it seems that 64bits Windows machines don’t let you install the Freescale CDC Device hardware. Do you know if there is something I can do?
Thank you!
LikeLike
I have Windows 7 64bit, so 64bit is not an issue for me, and I have not seen any problems with it. But I know that for example the problem could be with unsigned drivers, especially in Windows 8. Depends on your Windows version, there is a setting to allow installation of unsigned drivers. Search the web for things like “windows installing unsigned drivers”. I hope this helps.
LikeLike
Hi Erich
Writing back to let you know that it worked great.
Thanks for the help
LikeLike
Hi Erich,
I’m trying use the source code posted in this article. But a file name GPIO_PDD.h” is missing, when I compile with IAR. I’m using KL25Z Black.
I’ve Processor Expert Software – Microcontroller Driver Suite, Version: 10.4.0 and I don’t seem to find USB_stack in that.
Any suggestion would be a greater help for me.
Thanks,
Naruto Uzumaki
LikeLike
You need to load the components fom sourceforge, see
https://mcuoneclipse.com/2014/10/21/mcuoneclipse-releases-on-sourceforge/
LikeLike
Hey. I have a problem. I go step by step the instructions, but I have a few mistakes here.
The board is “FRDM-KL46Z”
More on the figures.


Any idea what I’m doing wrong ??
LikeLike
It seems you have created a kinetis SDK projekt? This is is not supported.
LikeLike
You need to create a project without the Kinetis SDK (set ‘none’ in the project wizard for the Kinetis SDK).
I hope this helps,
Erich
LikeLike
Yes, the problem was that the SDK. But I tried it with FreeRTOS and I have one problem.
The device connects to the windows – OK
But if I send a character, so the program fails – FAIL
I can not find the cause. So I want to ask if by chance someone knows where I’m wrong.
I have here two tasks.
1. Flashing LED
2. Operation USB
The code is here: http://paste.ofcode.org/jYZjn8rJ2iCJrag3PXp4xq
LikeLike
What is not working? I looked at your code, and that looks ok.
Just in case: I have a (bare metal) example with KDS here: https://github.com/ErichStyger/mcuoneclipse/tree/master/Examples/KDS/FRDM-KL46Z/FRDM-KL46Z_USB_CDC
LikeLike
The problem is this:
When I connect to USB CDC and send a couple of characters, so I entered in the buffer.
But when I try to send data to the other side (PC) and the program crashes. And as the last character still returns 0xE8.
Program crashed here: CDC1_SendString(“echo: “);
Complet program: http://paste.ofcode.org/qg5Wqjqpe42pQvpwbqR4kU
LikeLike
Try increasing configMINIMAL_STACK_SIZE. I think you have a stack overflow problem.
LikeLike
Change “configMINIMAL_STACK_SIZE” cause the collapse of the system (the system is blocked after the start of the program)
Complet FreeRTOSConfig.h is here: http://paste.ofcode.org/38csAQibZWv56hEnnvavpZ
LikeLike
If you would debug, I guess you would see that you run into an ‘out of heap’ handler.
I see that your heap size is very small:
#define configTOTAL_HEAP_SIZE ((size_t)(750)) /* size of heap in bytes */
Increase it to something more meaningful (e.g. at least 2048, or even more, depending on the number of tasks).
LikeLike
Hi Erich, i’d like to ask you about the function AppTask, that as far as i understand, tell us whether the device was enumerated or not by the host controller (in practice, this tell us whether the wire is plugged and was recognized by the OS, doesn’t it?). Periodically you check the function, but when i disconnect the USB wire from the PC during the program is running, the LED is still green, so it seems as if it were still connected, and when i try to send anything, the program crashes.
Also if i dont disconnect the USB wire, but i close the port/terminal in the host PC, i dont have any way to be aware about it, and if i try to send something the program crashes too.
Any idea if there is a way to know if the corresponding emulated COM port is open in the host PC, so i can avoid sending data to it?
Thanks in advice.
LikeLike
Hi Javier,
I’ll try to catch a state/event in AppTask which I get from the USB stack for a disconnect event. That works most of the time, but as you noticed, not always. Because the host initiates the USB transfers to the device, I think there is no real good way to know that you are still connected.
However, you say that the program crashes: this did not happen to me, so you must be doing something special? In the USB CDC (with the shell) I have implemented a way to either block on the characters until they are sent, or to discard them. But it should not crash.
LikeLike
Pingback: USB CDC with the Raspberry Pi | MCU on Eclipse
Hi Erich,
I’m planning to integrate USB to UART converter into my K20 MCU. Using this great tutorial I can easily create the USB virtual COM port part. But I still have to channel the data received by CDC to a UART port. And the difficult part is the UART port’s baud rate, handshake settings, etc should be configurable through Windows. Meaning that somehow I need to pass the UART configuration from the Windows client, to the driver, USB interface, and all the way down to the K20 chip. So just take is as something like FTDI USB to UART converter chip. Do you have any idea how to do this?
Thank you in advance.
Johnny
LikeLike
Hi Johnny,
I’m not an expert in all USB aspects. USB CDC does not know (or does not have to know) about baud rate or flow control. To my understanding you could add that to a custom USB CDC driver, but it is not necessary. Because the USB communication itself is using a different protocol. What the K20 can/should do is to sense the baud from the target microcontroller and use whatever is used there.
A few interesting reads on that topic:
http://www.microchip.com/forums/m285533.aspx
FTDI is using a special/dedicated USB CDC driver on the host to their chips: so here they can implement whatever they want and need, including special parameters. But for the ‘standard’ USB CDC on Windows I believe things like baud and control flow are ignored.
LikeLike
Hi Erich,
I am trying to integrate the USB CDC stack into FreeRTOS using KDS and Processor Expert and your example is very helpful. However, instead of polling for the USB status, is there a connect/disconnect event that will notify me of the USB status? Also, is there a callback function for when the USB received data?
Thanks
LikeLike
Hi Andrew,
I have been able to get proper attach events/information, but failed for the detach (they have worked only for about 50% of the cases). Not sure why, and this must be deep in the USB stack I’m using, not sure.
What does exist for the CDC class is CDC1_ApplicationStarted() and CDC1_TransactionsStarted() which do return if enumeration has been done and if a transaction is currently going on.
As for getting a callback for USB received data: there is in the RX Ringbuffer the event OnItemPut() you can use for this.
I hope this helps? And if you know a good way to detect the detach, that would be helpful for me too.
Erich
LikeLike
OK, thanks for the help!
LikeLike
If anybody is scratching there heads wondering why you’re only able to receive the first character of any string you send to your MCU then you might want to increase your Ring Buffer’s size to a value greater than 1. The max is 255.
By default, the Ring Buffer component inherited by Freescale’s USB stack is set to “Buffer Size = 1”.
This tutorial was written before Erich added the Ring Buffer to the USB stack component. So the tutorial doesn’t talk about configuring the Ring Buffer 🙂
Hope this helps.
LikeLike
Hi Carlos,
yes, this helps, thank you. Yes, I know the ring buffers are using a size of 1 by default, so I need to add a note about this. Or better change the default size of the ring buffer?
LikeLike
Hello, your blog is really helpful. Thanks a ton.
So I have a doubt! Is is possible to use PE Multilink debugger with KL25z
If so then how?
Will be waiting for your reply
LikeLike
Yes, I’m using the P&E Multilink (Universal) a lot for all Kinetis devices. Simply select the P&E option for the debugger (or the P&E launch configuration). If you create a project with the Kientis Design Studio, it creates that launch configuration already.
LikeLike
Many settings have to be exactly right, it seems, for the USB Stack to work correctly. I kept getting a hard fault early on in USB0_Init even without the USB cable attached. It turns out I missed the setting under the USB0 subcomponent of the FSL_USB_Stack to enable Clock gate. The default is Do not initialize and triggers a Hard Fault. I’m using Kinetis Design Studio 3.2.0 with the latest PE Components as of 4/25/2016. The settings look a bit different from the How-To but they are all still there in one form or another.
LikeLike
Yes, you need to enable the clock gates (thanks for posting the solution for your problem). The ARM core will cause a hard fault if a peripheral is accesses which is not clocked.
LikeLike
Hi Erich,
sorry to bother you again. Again having troubles getting this to work on KDS3.2.0 (worked fine on processor expert 2 years ago). The issue appears to be that SystemCoreClock is not defined and is being used by the Wait component. Here’s the error message:
Generated_Code/WAIT1.c:183: undefined reference to `SystemCoreClock’
collect2.exe: error: ld returned 1 exit status
Any clue what I might be doing wrong? Where should SystemCoreClock be defined?
Thanks,
Ralph
LikeLike
Hi Ralph,
the SystemCoreClock is only used if you are using the Kinetis SDK (CMSIS-Core).
So in your WAIT1.c you have
#if KSDK1_SDK_VERSION_USED != KSDK1_SDK_VERSION_NONE
extern uint32_t SystemCoreClock; /* clock frequency variable defined system_.h of the SDK */
#define WAIT1_INSTR_CLOCK_HZ SystemCoreClock /* core clock frequency in Hz */
#else
#define WAIT1_INSTR_CLOCK_HZ CPU_CORE_CLK_HZ /* for Kinetis, use core clock as base for instruction execution */
#endif
Which means to me that you have specified an SDK in the KSDK component? Set it to ‘none’ and you should be fine.
I hope this helps,
Erich
LikeLike
Hi Erich,
that is exactly what the problem was.
Thanks so much,
Ralph
LikeLike
Hi Everyone! I’m trying send a word to frdm, like “getsignal”, but the function CDC1_GetCharsInRxBuf returns just one character in buffer.
Does someone knows why?
LikeLike
Have you set the ringbuffer size of the RX and TX components inside the CDC component to a value >1?
LikeLike
Hello Everyone!! I am just trying to follow this tutorial using KDS and PE10.5, but I am having some problems that I couldn’t solve!
In file CLS1config.h, the compiler returns a error on line 43:
#define CLS1_CONFIG_DEFAULT_SERIAL_SEND_FCT_NAME USB1_SendChar
But, one line above, I have this:
#define CLS1_CONFIG_DEFAULT_SERIAL_RECEIVE_FCT_NAME USB1_RecvChar
And in this line, the compiler don’t returns any kind of error!!!
Can anyone help me?
Thanks a lot and congratulations for your blog!
LikeLike
Hi Lucas,
can you share the error? And are you using the latest version of the components (https://mcuoneclipse.com/2017/05/06/mcuoneclipse-components-06-may-2017-release/) and you have installed both .PeUpd files of the Zip?
LikeLike
Hi Erich!!
Sorry, I forgot to put the error!!
Description Resource Path Location Type
‘USB1_SendChar’ undeclared (first use in this function) CLS1config.h /Freedom_USBcdc3/Generated_Code line 43 C/C++ Problem
Yes, I have downloaded and installed the last release (05/06/17)
LikeLike
I downloaded other older (2017-03-12) and then compiled with no errors. I think it have some error in any component.
LikeLike
Hi Lucas,
OK, I will investigate. But it could be that it depends on your settings. Would you be able to send me your project as zip file (I need the project files, not necessarily the sources if you cannot share them).
You find my email address listed on https://mcuoneclipse.com/about/
Thanks!
Erich
LikeLike
Hi Lucas,
I can reproduce it :-(, working on a fix….
Erich
LikeLike
I sent to you my program, but another question, I used the older version and it compiled but it haven’t worked!
I put a led blink in before the “CDC_Run();” and when I program the board, didn’t blink, neither connect the USB.
Have you ever had some problem like this?
Thanks!!!
LikeLike
Hi Lucas,
I have found the problem and applied the fix: https://github.com/ErichStyger/McuOnEclipse_PEx/commit/25ba95b45701a176b96a8b1589ce63b6704a66d4
I have put an updated FSL_USB_Stack package (FSL_USB_Stack_11.05.2017.zip) on SourceForge: https://sourceforge.net/projects/mcuoneclipse/files/PEx%20Components/
Can you try this out?
I’m sorry causing your problems like that one 😦
Erich
LikeLike
Hi Erich! At first, thanks to help me a lot!!
So, I tried your new release and the KDS compiled my code, but I am having an another problem yet.
When I generate the binary and program in my KL25Z board, the code didn’t work! I put a blink test before the for(;;) but nothing. Do you have another hint for me??
Thanks!!
LikeLike
Are you using any of my examples from GitHub? If you have sent me your project, I have not received it.
LikeLike
Yes, I am using this tutorial and the files in your Github, but nothing. I compared my PE.pe file with you and it has a lot of differences.
I will try to send my project to you again.
Thanks Erich!!
LikeLike
Hi Erich, Can you help me?
I am working hard on this and now I have a new problem. I using the last release of your library and follow your tutorial and your examples on SourceForge. I need to use C++ on my project, but the PE only generates files in C. I search on NXP community and in your blog and I did some changes. When I change the main file extension (from c to cpp) and compile, the g++ returns some errors.
undefined reference to `CDC1_App_Task(unsigned char*, unsigned int)’ main.cpp /FCTNew/Sources line 80 C/C++ Problem
undefined reference to `CDC1_GetCharsInRxBuf()’ main.cpp /FCTNew/Sources line 89 C/C++ Problem
undefined reference to `CDC1_SendChar(unsigned char)’ main.cpp /FCTNew/Sources line 95 C/C++ Problem
undefined reference to `CDC1_SendString(unsigned char*)’ main.cpp /FCTNew/Sources line 138 C/C++ Problem
undefined reference to `CDC1_SendString(unsigned char*)’ main.cpp /FCTNew/Sources line 139 C/C++ Problem
undefined reference to `CDC1_SendString(unsigned char*)’ main.cpp /FCTNew/Sources line 140 C/C++ Problem
undefined reference to `CDC1_SendString(unsigned char*)’ main.cpp /FCTNew/Sources line 142 C/C++ Problem
undefined reference to `CDC1_SendString(unsigned char*)’ main.cpp /FCTNew/Sources line 144 C/C++ Problem
undefined reference to `Rx1_Get(unsigned char*)’ main.cpp /FCTNew/Sources line 91 C/C++ Problem
If I return the extension file to c, the code compile and works perfectly. Have you ever this code with cpp?
I’d glad if you could help me!
P.S.: I don’t know if you received my emails, I tried to send 2 times for my other problem (that I solved).
Thank you so much!
Lucas Moraes.
LikeLike
Hi Lucas,
no, I have not received any of your emails. I checked the spam filter, but again: no emails from you :-(.
I’m wondering why you need C++? Anyway, if you are using C libraries, you have to use
extern "C" { ..... }
around the includes where you are using C code.I started using adding this to some of the header files, but not many. I can check the ones for the ring buffer for example.
LikeLike
I’m really don’t know why my emails aren’t delivered for you, because they also didn’t turned back for me. But, ok. I am working in a project that manage a lot of data and I have already written all code in C++ (using class elements).
I solved the problems changing almost all generate code extension to cpp and works well, also I have changed the main file back to cpp extension.
So, in any way, I thank you!
And if you need any help to your blog (update files, create new posts and even translate to Portuguese) I make myself available to help you! Your blog is amazing!!
Again, Thank you so much!
LikeLike
Hi Lucas,
I see that at least some of the components are missing the
extern "C"
in the header files. I will fix this as much as time permits. I already fixed it for the ring buffer component.LikeLike
Hi Erich, I hope you are well. I’m attempting to get crystal-less operation working on a Kinetis KL24 using the IRC48M oscillator. My best efforts only allow me to achieve “47.972352”MHz so when I come to add a USB CDC device, errors are reported when generating the PE code as the USB clock is not 48MHz. Any clues on getting crystal-less operation working for this family of devices? Any help would be greatly received.
LikeLike
Hi Erich, please ignore this question. I’ve managed to get this working by not selecting a KSDK version to begin with. All seems happy and running smoothly
LikeLike
Hi Kevin,
ah, ok, great 🙂
Erich
LikeLike
Hello, the example walks very well with a pc, but exists you it a driver for MAC?
thank you
LikeLike
For Linux or Mac machines, you don’t need any drivers. You can use the normal USB CDC driver which is bundled with the OS.
LikeLike
If I have 2 KL25Z with this firmware, can I make one board talk to another?
LikeLike
With USB CDC? Not directly, as this article is about USB CDC device class. You need to have a USB CDC Host stack running on the other board.
LikeLike
Hi Erick! Do you have any tutorial to explain how to connect and communicate
two freedom board with USB CDC stack(one CDC Device and other CDC Host)?
Thank you!
LikeLike
No, unfortunately not. Implementing USB CDC host on a board has been on my ‘to-do’ list for a very long time, but never made it top on the list to be realized. Sorry.
LikeLike
Hi Eric,
I was able to successfully add the USB component to my project but on compilation the error ‘ USB1_SendChar undeclared’ in the CLS1config.h file pops up. I see the issue arose with some users above here but cannot deduce the fix.
Help appreciated.
LikeLike
I’ll have a look (received your email).
LikeLike
It needs a processor expert components update found here on SourceForge (https://sourceforge.net/projects/mcuoneclipse/files/PEx%20Components/
LikeLiked by 1 person