Статьи

Обзор: Процессор Эксперт

В « Обзоре: от фрагментов к генерации кода » я рассмотрел несколько инструментов, используемых в моем процессе разработки. Одним из инструментов, который мне очень помогает, является Processor Expert. В этой статье я расскажу об этом инструменте и расскажу о его преимуществах и недостатках.

Название изображения

обзор

В этой статье я расскажу о концепции Processor Expert и о том, как я использую их в своих приложениях. Я использовал его во многих клиентских и исследовательских проектах за последние годы. Поскольку инструмент может не подходить для каждого случая использования, я стараюсь перечислять плюсы и минусы того, как я их вижу.

история

Я не знаю всю историю Processor Expert в любом случае, поэтому вот то, что я знаю и смог собрать: Processor Expert — это инструмент, разработанный Unis начиная с 1994 года в Брно, Чешская Республика. Я начал использовать этот инструмент примерно в 1998 году, а затем с «классическим» CodeWarrior, использующим микроконтроллер Motorola / Freescale HCS12 и HCS08. В то время технология Processor Expert была независимой и доступной не только для процессоров Motorola / Freescale, например, для Fujitsu . В 2001 году ей была присуждена европейская цена IST.

Европейская цена IST упоминается в веб-документах, но кажется, что эта организация / веб-страница IST больше не выходит?

Технология была приобретена в 2008 году компанией Freescale и в настоящее время поддерживает только процессоры Freescale: HCS08, HCS12 (X), DSC, ColdFire, i.MX и Kinetis.

Вначале инструмент был доступен в виде «автономной» версии (без IDE), но затем был интегрирован Metrowerks в CodeWarrior IDE в качестве плагина.

Название изображения

Сегодня он доступен как плагин в Eclipse (например, Kepler, Luna) или интегрирован в Freescale Kinetis Design Studio, и работает на Windows, Mac OS X и Linux.

Название изображения

Pros Cons
Разработайте работающее приложение очень быстро. Нужно время, чтобы изучить инструмент.
Имеет встроенную базу знаний, иногда лучше справочного руководства. Точное понимание микроконтроллера все еще требуется.
Графический интерфейс пользователя. Для запуска графического интерфейса нужны ресурсы на хосте
Интегрирован в интегрированные среды разработки Eclipse и CodeWarrior. Другие не-Eclipse IDE, такие как Keil или IAR, должны использовать его как внешний инструмент, который не очень удобен для пользователя.
Поддерживается широкий диапазон устройств Freescale.

 Только для Freescale

Концепция и поток

Концепция Processor Expert заключается в том, что я могу выбрать «компоненты» из библиотеки компонентов и использовать их в своем приложении. Компоненты похожи на «блоки Lego» с интерфейсами, которые можно соединять и настраивать. Основываясь на этой конфигурации, он затем использует генератор кода для создания обычных исходных файлов C / C ++ / Asm.

Название изображения

Помимо исходных файлов этот генератор кода создает файлы отчетов и документации. Вместе с моими исходными файлами они собираются / связываются для создания ELF / двоичного файла для моей платы.

Pros Cons
Возможность делать быстрые прототипы с компонентами из библиотеки. Зависит от доступности компонента для устройств, поддерживаются не все устройства Freescale.
Исходные файлы оптимизированы и сгенерированы исходя из моих настроек, сгенерированный код статичен. Правила безопасного кодирования могут предотвратить любой «сгенерированный» код. Использование новой версии инструмента может повлиять на сгенерированный код, нуждается в повторной сертификации приложения / кода.
Совместное использование общего кода и библиотечных функций.

Генерация кода, особенно для многих модулей, может замедлить полную сборку приложения.

Библиотека компонентов

Библиотека компонентов имеет «блоки» для считывания аналоговых значений (АЦП) или переключения выводов (бит ввода / вывода) до более сложных вещей, таких как стеки связи (USB), которые сами по себе могут содержать несколько подкомпонентов. Компоненты могут зависеть от аппаратного обеспечения (например, UART) или могут быть чисто программными компонентами, такими как один, для реализации кольцевого буфера.

Название изображения

Установка Processor Expert поставляется со многими компонентами. Можно создавать свои собственные компоненты, используя среду CDE (Component Development Environment).

Pros Cons
Повторное использование общих блоков в качестве библиотеки в приложении. До недавнего времени (Processor Expert for Kinetis v3.0.0) не было возможности использовать несколько репозиториев.
Обзор и поиск функциональности / компонентов. Если функциональность не предоставляется Freescale, необходимо добавить / создать собственный или сторонний компонент.
Широкий спектр компонентов, как правило, охватывает функциональность на кристалле. Доступно очень мало компонентов вне чипа, таких как датчики или другие внешние компоненты Freescale предоставляет компоненты только для устройств Freescale.
Графический интерфейс пользователя с онлайн-справкой «Справка по компоненту».

Отсутствие документации, учебных пособий и примеров проектов.

Бины высокого уровня, драйверы логических устройств и компоненты SDK

В Processor Expert есть три разных типа компонентов:

  1. Компоненты высокого уровня или бобы (HLB): они были представлены первыми. Они используют простой API. Например, чтобы послать символ в UART, я вызываю AS1_SendChar (‘a’): AsynchroSerial High Level BeanAsynchroSerial High Level BeanЭто может быть легко использовано для голого металла и применения с ОСРВ. Конечно, при использовании устройства из нескольких задач необходима синхронизация. Наибольшим преимуществом «Beans» является то, что они имеют общий API для разных архитектур, поэтому я могу использовать один и тот же API / компоненты для устройств HCS08, HCSC12, DSC и ColdFire, например. Поэтому перенос приложения с одной архитектуры на другую обычно занимает несколько часов.
  2. Later on the Logical Device Drivers have been introduced with the introduction of Freescale Kinetis Devices. These components have the “_LDD” at the end of the name. The difference is that now a ‘device handle’ needs to be passed in each API call:Serial_LDDThese components are not that easy to use and not as efficient as the High Level Beans as there is always that extra parameter. While that ‘device handle’ is a good thing for some applications, it is an overkill for bare metal applications or where a device is used by a single RTOS task only (which in many cases is the default use case). The biggest issues with the LDD is that their API did break compatibility with previous (say S08 and S12) projects, as only available for Kinetis. That’s why soon after the release of LDD components Freescale had to provide High Level Beans for Kinetis too to provide a compatibility API. So with using inheritance both API’s were offered: LDD как унаследованный компонент внутри компонента высокого уровняLDD as inherited component inside the High Level Component
  3. With the introduction of the Kinetis SDK a new type of components were introduced: the SDK components which have the “fsl_” in front of their name. Компонент fsl_uart SDKfsl_uart SDK ComponentThe SDK components itself do not generate the full driver. Instead, they generate the configuration structures for the Kinetis SDK. The SDK is using a HAL (Hardware Abstraction Layer), and for this there are as well ‘_hal’ components offered and which are used inside the ‘fsl_’ components. Even if these components do not generate the code, they offer an easy visual way to use the Kinetis SDK.
Pros Cons
Simple API for High Level Beans. Easy to use and learn. Application code needs to deal with synchronization
Extended set of functionality e.g. for Timers or the Flex Timers on Kinetis. Overhead and complexity of LDD which is not needed for many applications. Hard to use/learn
Generic Device handle for LDD, easier to use it in an RTOS environment which uses device handles (e.g. MQX). LDD API not compatible with previous applications using HLB components.
‘Static’ configuration and code generation with SDK components. Components are for ‘configuration’, not code generation. Easy and visual way to use the Kinetis SDK and HAL API.

SDK components break again with previous projects. Components/projects cannot use/mix different components, no portability API. SDK itself adds complexity and overhead.

Methods, Events and Properties

I can use components from the Component Library. A component can use Methods, Events,Properties and Inheritance:

  • Methods: Functions/procedures of the driver. E.g. SendChar() for an UART component
  • Events: Hooks or interrupt events. E.g. OnRxChar() interrupt hook for an UART component
  • Properties: Settings of the component which affect the behaviour of the driver.
  • Inheritance: Multiple components can be combined or using links/interfaces to other components, in an object-oriented way. For example a UART component can inherit from a low-level UART component and build up a new interface with new functionalities.

Название изображения

Methods and events can be enabled or disabled it not used (marked with a small ‘x’) in above screenshot. Methods which are disabled are not generated, and the component code generator might optimize the driver based on what is enabled/disabled. For example if there is no ‘GetStatus()’ method needed, then the component might not need to store a status somewhere at all.

For the components, there is a view to change and inspect the properties: for the UART component for example I can turn on interrupts and assigns the pins to be used for Rx and Tx:

Название изображения

I’m showing the ‘classic’ view in above screenshot. There is a ‘tab’ view (default) too, but that tab view in my opinion is much harder to use, so I recommend to use the ‘classic’ view. See “Switching between ‘tabs’ and ‘no-tabs’ UI in Processor Expert” for details.

Basically, this gives me a graphical front end for my UART driver. Based on my settings, it will configure and produce software Files for me:

Generated UART Driver code

The source code for sending a character over UART will look like this:

/*
** ===================================================================
** Method : AS1_SendChar (component AsynchroSerial)
** Description :
** Sends one character to the channel. If the component is
** temporarily disabled (Disable method) SendChar method only
** stores data into an output buffer. In case of a zero output
** buffer size, only one character can be stored. Enabling the
** component (Enable method) starts the transmission of the
** stored data. This method is available only if the
** transmitter property is enabled.
** Parameters :
** NAME - DESCRIPTION
** Chr - Character to send
** Returns :
** --- - Error code, possible codes:
** ERR_OK - OK
** ERR_SPEED - This device does not work in
** the active speed mode
** ERR_TXFULL - Transmitter is full
** ===================================================================
*/
byte AS1_SendChar(AS1_TComData Chr)
{
 if (SCI1S1_TDRE == 0U) { /* Is the transmitter full? */
   return ERR_TXFULL; /* If yes then error */
 }
 SCI1D = (byte)Chr; /* Store char to the transmitter register */
 return ERR_OK; /* OK */
}

So this is not much different from any other UART driver. The difference is the knowledge and the consistency checking Processor Expert is doing. For example it knows which pins are available for the Rx function, and which pins are already used by something else:

Название изображения

There is as well the CPU view which keeps tracks about which blocks and pins are used:

Название изображения

The other thing is that it proposes me possible UART Baud values I can use:

Название изображения

For this it keeps track of the internal clocks and clock paths:

Название изображения

All this information would be present in the device reference manual too. But it is much easier and faster to use the AsynchroSerial/UART component:

  1. Add component to project
  2. Select UART device (e.g. UART0)
  3. Choose Rx and Tx pins
  4. Specifiy initial UART Baud rate
  5. Generate the driver/configuration
  6. Use it in my application

If I’m not happy with the generated code, I have the option to ‘freeze’ the code generation of a component. See “Disable my Code Generation«

Pros Cons
Easy and simple way to have a driver. Still need to understand how the hardware works to some extend.
Graphical UI for configuration. Requires IDE integration (Eclipse).
Consistency checking prevents wrong or bad settings. Consistency checking requires time, slows down the tool. Sometimes ‘rekursive’ dependencies are not properly resolved.
Generates driver code and example code ‘which works’.

API and coding style might not match own preferences. Because the driver need to deal with many different use cases, it is not the most efficient one (code size, speed).

Physical Device Drivers

In case the generated functions and methods are not enough, there is a lower layer of API which can be used: the Physical Device Drivers (PDD, see “Low-Level Coding with PDD (Physical Device Driver)“). Basically the PDD are low-level macros which can be used to access the low-level functionality of the device. Because the PDD macros are tight to the device used, they are not much portable between different devices.

Название изображения

Pros Cons
Small and tight code. Hard to understand API and how to use it.
Access to low-level peripheral function. Macros are device dependent, not portable.
Graphical UI to drag&drop macros/functions

Lack of documentation.

Inheritance

Another great functionality of Processor Expert components is their ‘inheritance’ model: A component can inherit functionality from other components. The following shows the LED component which is inheriting functionality from a ‘BitIO’ component:

Название изображения

The LED function On() (to turn the LED on) will use either the BitIO ClrVal() or SetVal() to change the logic level of the pin, according to the LED settings how the cathode/anode of the LED are connected to the port pin. This inheritance scheme is very powerful and enables component sharing. Processor Expert has as well the ability to ‘link’ to other components. For example the LED component can link to a Shell component, and that way automatically enable command line support for that component:

Название изображения

Pros Cons
Ability to turn on/off functions to optimize the code. Sometimes unclear what the impact of enabling/disabling functionality will be.
Easy way to generate code “which works” or can be used as reference implementation. Code sometimes not ideal, or not very well documented.
Automatically checks for dependencies, configures the pins and clocks for me. Checks for conflicts. Still need to understand the microcontroller. Making bad settings will result in bad results.
I can disable code generation and do my own changes.

Freescale provided components are ‘closed’: I cannot edit or change them.

Component Development Environment

The component framework in Processor Expert allows me to create my own components. that capability is free of charge (no license required) if I’m not going to sell the components created. This is the ‘Community Edition License’, and if no other license is found, this text in the Eclipse Console View is printed:

CDE: no license found, using Community Edition License

I wrote a tutorial “Tutorial: Creating a Processor Expert Component for an Accelerometer” how to create my own components. Newer Processor Expert releases come with a Java based/Eclipse plugin to create/change your components. In classic CodeWarrior there was the ‘BeanWizard’ (standalone), but this one required a paid/Professional CodeWarrior license.

Using CDE, I can create components like the one on McuOnEclipse SourceForge site, or like the components provided by Freescale. With one exception: it is not possible to create Processor components:

Название изображения

Pros Cons
Can create my own components. Not easy to learn, takes a lot of experience.
Free license (Eclipse plugin) Cannot sell components, cannot create Processor components. Classic BeanWizard is not free of charge.
Graphical wizard and user interface to create components.

The CDE plugin in Eclipse is not very mature and not as easy to use as the ‘classic’ BeanWizard.

Portability

The other big advantage of using components is: as the component interface remains the same, and because Processor Expert is available on multiple Freescale platforms, it is very easy to move projects between different derivatives. For example I have my INTRO Robot application running on Freescale S08, ColdFire and Kinetis (ARM), all with the same set of components. So Processor Expert makes it really easy to move from one device to another (e.g. Kinetis KL25Z to Kinetis K64F) or from one architecture to another (e.g. HCS08 to Kinetis KL25Z), or from one toolchain to another (e.g. CodeWarrior to KDS or to any other Eclipse IDE).

For example this is a project for an S08 (Freescale S08 16bit microprocessor) on CodeWarrior which uses multiple components including an LCD:

Название изображения

The same functionality/project on a 32bit Kinetis (ARM Cortex-M0+) on Eclipse Kinetis Design Studio:

Название изображения

Porting such a project is a matter of an hour or less:

  1. Create a new (empty) project for Processor Expert for the new target
  2. Copy-Paste the components to the new project (see “Copy of Processor Expert Components«)
  3. Change the component settings to use the new pins on the new board
  4. Copy the application code
  5. Generate Code, build and test

A good example how Processor Expert components can be portable across different toolchains, architectures and IDE’s is the FreeRTOS Processor Expert component maintained in the McuOnEclipse project:

Название изображения

A single component with a graphical user interface to configure FreeRTOS:

  • 9 Compilers and 6 Architectures: Freescale chc12, chc08, DSC, ColdFire V1, ColdFire V2 and ARM compilers, GNU GCC ARM Embedded (launchpad), IAR, Keil
  • 7 IDE’s: CodeWarrior (classic) 6.x, CodeWarrior (eclipse) 10.x, Kinetis Design Studio, Driver Suite 10.x, Atollic TrueStudio, Emprog Thunderbench, NXP LPCXpresso
  • 3 component types supported: HLB (High Level Beans), LDD (Logical Device Drivers) and Kinetis SDK

One component to rule them all! 

Summary

I know this is a rather long post, and I hope it gives an overview for newbies what Processor Expert is: A component based framework which encapsulates software with a graphical configuration front end. There is much more behind this framework, including automated build and generation support. Of course no tool is perfect, and no tool fits every need. The problem I see is that the framework should be faster especially for large projects. But the biggest disadvantage (maybe Freescale might say that this is the key feature that it exists only for Freescale devices). So once someone has explored the power of it, it will be hard to move to another vendor.

To me, Processor Expert is like C++: it takes some learning and time to master it, but then it is incredible powerful. Sometimes I feel like at the old days when C/C++ compilers got introduced, and everyone was using assemblers: high level language was considered as slow, inefficient and “I can program this better!” But today there is no argument about using compilers because they have both improved and second we need to be more productive. And everything else looks like stone age.