CLion for embedded development

Hi,

Are you interested in embedded development? In this guest blog post our user Ilya Motornyy shares his experience in programming for microcontrollers in CLion.

Ilya Motornyy
Ilya Motornyy
Java/JavaScript Developer at Vaadin.com
DIY Electronics and Embedded Programming Enthusiast.

Introduction

CLion is a relatively new IDE for C/C++, based on very popular IntelliJ Platform, and hopefully it inherits most of the nice features of IntelliJ IDEA like code highlighting, autocompletion, refactoring, and analysis. Although CLion in its current state is not targeted at embedded development, it’s still possible to use it for this purpose. Embedded programming here means no operating systems, clipboards or other processes.

One of the most popular microcontrollers (MCU) nowadays is a huge family of ARM Cortex-M compatible processors, based on the 16/32bit ARM kernels, but made by different companies. Many of them are quite powerful and at the same time cheap and relatively easy-to-program. Let’s try to program something for one of them with CLion.

A good target platform is NUCLEO-F303RE – a development board for STM32f303RE MCU. This is ARM Cortex M4+FPU MCU, 72MHz, 64(RAM)/512(ROM) kB of memory. Let’s use a Linux-based (Ubuntu 16.04) computer for this development.

Hardware, or how to run programs

The main difference between desktop and embedded programming is how to run or debug the program. In case of desktop, the program is just run directly or under dbg for debugging.

In case of embedded, the program (firmware) should be downloaded into the target chip, and then run (in most cases the MCU is just reset after download). This could be done through the bootloader (USB, UART, I2C, SPI, OTA etc.) or through the hardware JTAG probe. To debug firmware, JTAG probe is required as well as remote dbg support for it. It case of ST development boards (both EVAL, Discovery or NUCLEO series), there are on-board ST-link compatible JTAGs. CLion has dbg support, but unfortunately there is no support for remote dbg, and it is not possible to use CLion’s internal debugger for any embedded development yet (please vote).

Luckily, there is a company called Segger that produces its own JTAGs and a debugger on top of that. Now it’s possible to upgrade onboard ST-Link debugger to full-featured J-Link debug probe. Note that the upgrade license allows you to use this upgrade for ST evaluation boards only; production use is prohibited.

Of course, if you have Segger J-Link device, you can use it according to the license terms and just skip board upgrade. In this case, Nucleo onboard st-link jumpers must be removed, and the probe must be connected directly to MCU pins.

To perform this upgrade you need a Windows computer (VirtualBox or VMWare might help) and Segger upgrade utility. The same utility can downgrade the board back to ST-Link.

Other options

If you use another ST ARM MCU or board, you can use this article as a general HowTo, and flash your device using USB DFU mode and dfu-util, or using UART bootloader. See the application note AN2606 for details about STM32 MCUs bootloaders.

If nothing works, then there is openOCD, which can be used to download firmware (and debug, when CLIon introduces remote dbg support).

Software

CLion

Just download it from JetBrains site and install by following the instructions. CLion is a paid product, but it can be used for 30 days for free under trial license. You may be able to apply for a discounted or complimentary license.

CMake

All CLion projects are based on CMake build model. CMake is shipped with CLion and any Linux distribution contains it as well. You can use whichever you want.

Segger

Segger software can be downloaded from their site. J-Link Debugger is a must, all other pieces of software are up to you. Choose the appropriate version (32 bit or 64 bit), and packaging for your version of Linux (DEB for all Debian derivatives, including Ubuntu).

GNU GCC for ARM (gcc-arm-none-eabi)

The absolutely mandatory part of the software is a compiler. We will use gnu-gcc for embedded ARM processors. Thanks to launchpad.net guys, we can just install or download pre-build gcc binaries.

STM32CubeMX

The last piece of required software is STM32CubeMX, a universal GUI tool for configuring MCU peripherals and for code generation. Download the installer from st.com and run it.

Firmware library

Finally, run the utility and install a fresh utility for the target MCU. Open Help->Install New Libraries->STM32CubeF3->check latest revision->Install Now. The firmware library is quite large so the process will take some time.

New Project

STM32CubeMX

Now everything is ready to create your very first project. Run Cube software, click New Project, then select Board Selector tab, and choose the target platform Nucleo64 NUCLEO-F303RE.

image11

Now we can see the default MCU configuration for the board. Pin PA5, connected to onboard LED, is already set to GPIO_Output mode, and we can use it for classic “blink” example.

image15

Now it’s time to generate project code. Press Project->Generate Code. In the opened dialog, configure the target folder and set the target Toolchain/IDE to SW4STM32, since CLion is not supported by Cube software.

After pressing OK, Cube software generates the full set of sources, including libraries, linker script and startup code for the given MCU type.

image16

CLion Project & Settings

Now that the codebase is generated in the target folder, let’s create a CLion project on top of that. A good start is to choose Import Project from Sources (the same can also be done from the home screen or from the File menu). The IDE generates a CMakeLists.txt file for us, but for this project you should create a different one:

There are some adjustments for the compiler and .bin and .hex files generation.

The next step is to write the cross-compiler toolchain file. For STM32f303xE this file looks like this:

Before first compilation, your CLion project will need some adjustments. Go to File -> Settings and under Build, Execution, Deployment -> CMake set the following:
CMake options: -DCMAKE_TOOLCHAIN_FILE=STM32F303xE.cmake
Build output path: build

image04

Reload your CLion project (Tools -> CMake -> Reset Cache and Reload Project). Now the project is ready to be compiled in the IDE (Run -> Build). If everything is done correctly, .bin and .hex files should appear in build folder.

First run of Segger J-Link Debugger

Select Run -> Edit Configurations… and create a new Application. Enter any name and specify the following options:

  • All Targets for Target
  • Debug for Configuration
  • /opt/SEGGER/jlinkdebugger/2.14.9/JLinkDebugger for Executable
  • run.jdebug for Program arguments
  • Enter the project folder path for Working Directory
  • Check Single Instance only

Finally, click OK.

image18

Now the debugger can be started right from the IDE. Segger Debugger needs its own project to be created. To make it happy, choose File -> New -> New Project Wizard…

In the open wizard, choose the appropriate MCU, then interface configuration, then data file – i.e. our compiled .elf file in the build folder.

image17

image19

image12

When the wizard finishes, click File -> Save Project As…, choose your project folder and enter run.jdebug into the File Name field (same as in run configuration in CLion).

Wait, when we are going to code?

Exactly! Now everything is set up and ready for you to start coding. To see a real “blink” example, just add those two lines inside a while loop in the main() function.

image13

After this modification, you can just run your JLINK Debugger configuration. The project will be automatically built, and the debugger will be started on top of that. In the debugger, press F5 to download and start the firmware, then click Yes to agree with the evaluation mode, then press F5 again to run the main() function. The green LED LD2 will start blinking with 1Hz frequency.
Now you are able to use all Segger debugger features.

image14

Pro Tip

STM32CubeMX code regeneration

You can run Cube software over your project multiple times, and regenerate configuration code as many times as you need. To preserve your own changes to the sources during code generation, surround your the changes with the comments /* USER CODE BEGIN ??? */ and /* USER CODE END ??? */. Cube leaves those code blocks untouched. Of course, you can add your own .c files to the project.

Conclusion

CLion is really good IDE for C-based projects, and as you can see here, it’s possible to use it for embedded ARM MCU development. This article covers only one MCU chip and only one JTAG probe, but the manual can be easily adapted to any STM32 MCU and other vendors’ chips as well. At the moment, CLion team is working on remote GDB support.

This entry was posted in Tips'n'Tricks and tagged , . Bookmark the permalink.

54 Responses to CLion for embedded development

  1. Carroll Vance says:

    Thanks for this! Working on getting a similar setup for my NXP Kinetis FRDM-K66F dev kit and many of the steps are the same.

    BTW, us embedded folk will be eternally thankful to Jetbrains when remote debugging support is added :)

  2. Sean Wood says:

    I guess one without access to a segger compatible (read: exclusionary) debugger chip could get the Eclipse standalone debugger with a bit of fiddling to work in the above circumstance. Very very excited to finally see some interest in helping out getting a massive embedded C/C++ community Jetbrains-enabled. I’ve waited years for this!

  3. Please vote for my tickets at CLion bugtracker.
    Looks like that really can push embedded stuff forward :)
    Just put “+1” comments there

    https://youtrack.jetbrains.com/issue/CPP-7103
    https://youtrack.jetbrains.com/issue/CPP-7105
    https://youtrack.jetbrains.com/issue/CPP-7107

  4. Dmitry Romanov says:

    Could you publish STM project on GitHUB, pleast?

  5. I am not sure if JetBrains is interested in embedded business. They will never be able to compete against professional tools, and today, hobbyists can find everything for embedded programming in Eclipse. Free of charge. Including excellent web support pages like MCU on Eclipse (https://mcuoneclipse.com). It will be difficult to achieve such standard and move this user from Eclipse to JetBrains.

    BTW, looking at your CV, for me is more interested the implementation of Vaadin on embedded systems. I am successfully running Vaadin on small Kinetis/NTX and ST boards as front end GUI. Not a simple task, I had to change the Vaadin code a bit and compile from source, because you sometimes reference server classes from the client code. This would force me to install huge client packages along with server and shared libs which waste the limited embedded memory. Anyway, my Vaadin including embedded Jetty has about 5 MB and runs fine on Cortex M3.

    • Actually JetBrains Idea has a very good market position despite of huge amount of Eclipses installed. Idea is shipped by google as an official IDE for android development. I believe they could fight at C/C++ IDE market against existing monsters.

      About Vaadin… You have really surprised me! What JVM did you use? What the hardware? Could you share your project?

  6. Pingback: The Week in C++ 2016.25: June 19th-25th | Utah C++  Users Group

  7. Hellmut Kohlsdorf says:

    I was delighted using PyCharm, I was even more delighted to see I could get it to work on Arduino boards. Apparently I was over optimistic to be able to do the same for LPCxpresso boards and Stellaris Launchpad.

    But I want to highlight that the qualified and supportive actions from Jetbrains strengthened my wish to use the Jetbrains tools.

  8. Jonathan says:

    I don’t see why JetBrains couldn’t compete with giants of the sector. But actually, do they really have to compete?
    How could JetBrains compete with the free XCode on iOS? Well, they are doing it, and I would hate to have to use XCode.
    Even though I have Resharper, I use CLion as much as I can for editing C/C++ code.

    What differentiate JetBrains product from other products, in my opinion, is that everything is actually thought for developers. And that includes the ability to confirm pretty much any dialog by hitting Ctrl+Enter.

    The “instant search” thanks to indexing is a huge benefit to me. Of course I could do the same before, it would just take a lot longer. All of the very quick completion and navigation… I miss them so much when working under other IDEs.

    I would love CLion to have

    • Anastasia Kazakova says:

      Thank you very much for such kind words. Do you mind us sharing your words as a testimonial on our site? Especially the middle part)

  9. jerry says:

    how to use openocd for debug? st-link v2

  10. Hellmut1956 says:

    Any advances in remote debug support for CLion?

    • Anastasia Kazakova says:

      Not sure what you mean. Remote debug feature is present in CLion since 2016.2 (for Windows since 2016.3).

  11. kudl4t4 says:

    Great articule, although needs some update. For example JLINK Debugger is now Ozone – The J-Link Debugger

  12. Tim Walther says:

    Hi, I followed the instructions to no avail and afterwards tried the project from github on 2016.3 (Mac), but it didn’t build. Any chance this is updated soon? I’d love to use CLion for my STM32 projects, because eclipse is such a pita.

    • Anastasia Kazakova says:

      Is it smth like this: https://youtrack.jetbrains.com/issue/CPP-9179?
      Or some other error?

      • Tim Walther says:

        Well, yes. When I open the project from github on 2016.3, it doesn’t set the toolchain file in the build options. (in Preferences > Build, Execution, Deployment > CMake) But after setting these to the correct values, the error is the same as in the link you posted.

        • Tim Walther says:

          It seems it chokes on the assembly file included in the project.
          I think it’s not calling the arm-none-eabi version..
          I had similar problems when trying to make my own project.

          • Anastasia Kazakova says:

            Do you have the same error when calling CMake from the command line (without CLion)?

          • Tim Walther says:

            I tried calling cmake (3.7.2) from the command line, I got similar errors:

            batman-2:f3_blink-master timwalther2$ cmake . -DCMAKE_TOOLCHAIN_FILE=STM32F303xE.cmake
            CMake Deprecation Warning at /usr/local/Cellar/cmake/3.7.2/share/cmake/Modules/CMakeForceCompiler.cmake:69 (message):
            The CMAKE_FORCE_C_COMPILER macro is deprecated. Instead just set
            CMAKE_C_COMPILER and allow CMake to identify the compiler.
            Call Stack (most recent call first):
            /Users/timwalther2/Documents/Werk/Projecten/Eigen Beheer/TimeTosser2/f3_blink-master/STM32F303xE.cmake:7 (CMAKE_FORCE_C_COMPILER)
            CMakeFiles/3.7.2/CMakeSystem.cmake:6 (include)
            CMakeLists.txt:1 (project)

            CMake Deprecation Warning at /usr/local/Cellar/cmake/3.7.2/share/cmake/Modules/CMakeForceCompiler.cmake:83 (message):
            The CMAKE_FORCE_CXX_COMPILER macro is deprecated. Instead just set
            CMAKE_CXX_COMPILER and allow CMake to identify the compiler.
            Call Stack (most recent call first):
            /Users/timwalther2/Documents/Werk/Projecten/Eigen Beheer/TimeTosser2/f3_blink-master/STM32F303xE.cmake:8 (CMAKE_FORCE_CXX_COMPILER)
            CMakeFiles/3.7.2/CMakeSystem.cmake:6 (include)
            CMakeLists.txt:1 (project)

            — Configuring done
            — Generating done
            CMake Warning:
            Manually-specified variables were not used by the project:

            CMAKE_TOOLCHAIN_FILE

            — Build files have been written to: /Users/timwalther2/f3_blink-master
            batman-2:f3_blink-master timwalther2$ make
            Scanning dependencies of target HAL
            [ 4%] Building C object CMakeFiles/HAL.dir/Drivers/STM32F3xx_HAL_Driver/Src/stm32f3xx_hal_cortex.c.obj
            /var/folders/6s/ks15wdh17sjgj9fjzvr891480000gp/T//ccVwOUq4.s: Assembler messages:
            /var/folders/6s/ks15wdh17sjgj9fjzvr891480000gp/T//ccVwOUq4.s:482: Error: selected processor does not support dsb 0xF' in ARM mode
            /var/folders/6s/ks15wdh17sjgj9fjzvr891480000gp/T//ccVwOUq4.s:495: Error: selected processor does not support
            dsb 0xF’ in ARM mode
            make[2]: *** [CMakeFiles/HAL.dir/Drivers/STM32F3xx_HAL_Driver/Src/stm32f3xx_hal_cortex.c.obj] Error 1
            make[1]: *** [CMakeFiles/HAL.dir/all] Error 2
            make: *** [all] Error 2

          • Anastasia Kazakova says:

            So it looks like the problem with the CMake project itself. Not sure I know a good solution. Have you tried made a clean for CMake Cache and redo?

          • Tim Walther says:

            Yes, i tried that. My guess is that the common flags (“-mcpu=cortex-m4 -mthumb -mthumb-interwork -mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffunction-sections -fdata-sections -g -fno-common -fmessage-length=0”) are not passed to the assembler.. Maybe there is an easy solution to do this, but I’m not quite sure how.

        • Tim Walther says:

          I noticed that ASM_FLAGS was empty in CMakeCache.txt,
          So I appended “SET(CMAKE_ASM_FLAGS “${COMMON_FLAGS}”)” to the STM32F303xE.cmake and now it builds!
          Next step is to adjust the project to my target MCU and see if it actually works, will keep you updated!

  13. Actually that does not work. The problem looks like cmake project parse/cache problems. I added my comment to the https://youtrack.jetbrains.com/issue/CPP-9179.

    This bug is kinda annoying but definitely not a show stopper. Usually it is fixed with “Reload CMake Project” in cmake tool window.

  14. UPDATE
    1. As mentioned before, JLinkDebugger now is named Ozone.
    2. Now CLion supports remote gdb
    3. There is a mistake in toolchain file, please use corrected one:

    STM32F303xE.cmake:

  15. Luis David Moreno Ramirez says:

    How compile I for C++?

    • Anastasia Kazakova says:

      Not sure, what is the question about. Could you share more details pls?

      • Luis David Moreno Ramirez says:

        I’m working in CLION with Stm32f103c8t6 and STMCUBEMX, all ok, but I’m work in ECLIPSE IDE my project with C++ and I’m trying in CLION compile main.cpp and it compiled alright but at the moment that program on mcu, it’s not running

        • Anastasia Kazakova says:

          Maybe, it worths checking the CMake files advised in the blog post and compare with yours. Check you do compile for the board correctly.

        • I have very limited experience with C++ on embedded platform, but what can go wrong:
          * c++ usually requires more stack size. Please ensure if you have enough stack memory in your linker script
          * c++ requires memory handling, that requires a memory heap of some size, and memory handling routines working. try to play around with -specs= compiler/linker switches.

  16. han says:

    Can it be used for other mcu such as PIC32?

  17. I spent all evening trying to work out why this would not work for me – mostly because I have (had) no idea how to drive cmake. In the end, it was simple but I do not know why it failed.

    I was getting errors because the toolchain settings seemed to be ignored and builds were trying to use clang (I have a mac)

    The solution was to put the full path to the tools in the toolchain file:

    SET(TOOLCHAIN “/usr/local/arm/gcc-arm/bin/”)
    SET(CMAKE_C_COMPILER ${TOOLCHAIN}/arm-none-eabi-gcc)
    SET(CMAKE_CXX_COMPILER ${TOOLCHAIN}/arm-none-eabi-gcc)

    Even though the tools are in the path on the command line. Anyone care to suggest why I needed to do this?

    Oh, and the mapfile option for the linker should be -Map=binary.map, not -M=binary.map

    • Anastasia Kazakova says:

      What was the original issue? Were you trying to change the compiler? Have you tried resetting the CMake Cache?

      • Whatever I tried from the article and the comments, when I cleared the cache and reloaded the project, CLion and CMake between them would not recognise the ARM toolchain. Maybe there is something about my path that breaks it all. Anyway, with the full path entered in the script, it worked OK.

        However, I just went back and took out the path specification and it all worked just fine. It was very late by the time I finished. Maybe I changed something else as well.

        It may be better to specify the path anyway since it would make it easier to point to another toolchain. Fore example, you may have a project built with an older version that needs to get used when patching.

        • Anastasia Kazakova says:

          Ok, let me know if the problem is back.

          • Andrew Wade says:

            I Have the same Issue on Windows.

            It only works if I include the full path to arm-none-eabi-g++.exe and arm-non-eabi-gcc.exe.

            That folder is included in my Windows PATH.
            Using MinGW 5.

            I’d like to use this on different computers without having to change the file path each time.

            Please Help.

          • Anastasia Kazakova says:

            Could you please check the following:
            1) Does it work with the same parameters as you point in CLion, but from the console (I mean the CMake call)?
            2) If you go to CMake settings, check environment variables: include parent environment variables should be selected and you can check them when clicking on Show. PATH should be there.
            We’ll be grateful for the details.

          • Anton Makeev says:

            We have pin-pointed the problem, please follow the bug-report https://youtrack.jetbrains.com/issue/CPP-87

  18. George Kosentes says:

    Hi, thank you for the tutorial. Before finding your post, I watched an STM32 tutorial using a different board and decided to get it. How different is the code for the stm32 keil tutorial? My board has the STM32F0 controller.

    Thanks,
    George

    • I used the same approach for F0, F1, F3, F4, L0, L1 and L4 STM32 series, and both of them worked.
      Since the code in both, the video tutorial and the blogpost, is based on on stm32cubemx output and libraries, the C source code and is gonna be identical. However, some build files(???.cmake and CMakeLists.txt) require some mcu-specific adjustments. Linker script(???.ld) is automatically generated by stm32cubemx, and does not require any changes usually.

  19. Simon Schauppenlehner says:

    First of all, thank you for the tutorial. I was really happy when i get here.
    Could you please update the article and explain the process to set CLion up with OpenOCD as flash and debugging tool? :) I know it should already be possible but I’m not able to make it with success..

  20. Thibault F. says:

    Hi ,
    Thank you for your work, it’s very nice and clear.
    I was searching a way to discover Clion with my hardware platform and your topic help me to achieve this goal.
    But you said you made this for multiples platforms (“F0, F1, F3, F4, L0, L1 and L4 STM32”), Are these project open source and available for download? It would be nice in order what CLion offer for embedded systems in an easier way.

    Thanks,
    Thibault

Leave a Reply

Your email address will not be published. Required fields are marked *