Keil uvision5

Features:

  • Widgets for PC look and feel: Widgets (window objects, also known as controls) are ready to use control elements for the user interface.
  • Window Manager: The window manager supplies a set of routines which allow you to easily create, move, resize, and otherwise manipulate any number of windows.
  • Dialogs: A dialog is normally a window that appears in order to request input from the user.
  • Touch Screen & Mouse support: Touch screen support for analog touch panels is available. This includes a low level driver,which handles the analog input (from an 8 bit or better AD-converter), de-bouncing and calibration of the touch screen. The window manager deals with touch messages and widgets such as button objects.
  • Memory device contexts: Memory device contexts allow creation of a section to output to the display in the memory of the CPU. All drawing operations can be used. When the image has been build completely, it is transferred to the display in a single operation, allowing flicker free updates even with slow CPUs or slow displays.
  • VNC Support: VNC (Virtual Network Computing) is a graphical desktop sharing system that uses the Remote Frame Buffer protocol (RFB) to remotely control another computer. It can be easily combined with the MDK-ARM Middleware TCP/IP stack.
  • Drivers: The GUI component is delivered with a variety of drivers for the most common LCD controllers.
  • Multiple Layer/Display support: Some graphic controllers offer a flexible layer concept. The multiple layer/multiple display feature allows you to handle more than one layer.
  • Anti-aliasing: AA reduces the jagged, stair-step appearance of any line that is not exactly horizontal or vertical. Different anti-aliasing qualities, anti-aliased fonts and high-resolution coordinates are available.
  • Fonts: Ready-to-use fonts are included in the sizes: 4*6, 6*8, 6*9, 8*8, 8*9, 8*16, 8*17, 8*18, 24*32, and proportional fonts with pixel-heights of 8, 10, 13, 16. New fonts can be defined and simply linked in.
  • Demos: Demos supplied in full source code show the usage of widgets, dialogs and other features. Use them as templates for your own applications.

Объектные и HEX файлы

  • *.(без расширения): Абсолютный объектный файл. (Исполняемая программа, создаваемая компоновщиком).
  • *.AXF: Абсолютный и исполняемый объектный файл, создаваемый компоновщиком.
  • *.Bxx: Абсолютный объектный файл, создаваемый OC51 для индивидуальных кодовых банков (xx может принимать значение из диапазона от 00 до 31 включительно).
  • *.ELF: ELF/DWARF-файл, создаваемый компоновщиком/Locater’ом.
  • *.HEX: Файл Intel Hex.
  • *.H86: Файл Intel Hex.
  • *.LIB: Объектный файл библиотеки.
  • *.OBJ: Перемещаемый объектный файл.
  • *.O: Перемещаемый объектный файл.
  • *.SBR: Файл с информацией для Source Browser, создаваемый компоновщиком/Locater’ом.

Armv8-M and Armv8.1-M Architecture

Armv8-M introduces two profiles baseline (for power and area constrained applications) and mainline (full-featured with optional SIMD, floating-point, and co-processor extensions). Both Armv8-M profiles and Armv8.1M are supported by CMSIS.

The Armv8-M Architecture is described in the Armv8-M Architecture Reference Manual.

The Armv8.1-M Architecture further extends Armv8-M with Helium, an Microcontroller Vector Extension (MVE) and further instruction set and debug extensions. More information about Armv8.1-M Architecture is available under Arm Helium technology.

Tested and Verified Toolchains

The CMSIS-Core Device Templates supplied by Arm have been tested and verified with the following toolchains:

  • Arm: Arm Compiler 5.06 update 6 (not for Cortex-M23/33/35P/55, Armv8-M, Armv8.1-M)
  • Arm: Arm Compiler 6.14
  • Arm: Arm Compiler 6.6.2 (not for Cortex-M0/23/33/35P/55, Armv8-M, Armv8.1-M)
  • GNU: GNU Tools for Arm Embedded 9.2.1 2019q4
  • IAR: IAR ANSI C/C++ Compiler for Arm 8.20.1.14183

Preprocessor Macros

Each library project have different preprocessor macros.

ARM_MATH_BIG_ENDIAN:

Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets.

ARM_MATH_MATRIX_CHECK:

Define macro ARM_MATH_MATRIX_CHECK for checking on the input and output sizes of matrices

ARM_MATH_ROUNDING:

Define macro ARM_MATH_ROUNDING for rounding on support functions

ARM_MATH_LOOPUNROLL:

Define macro ARM_MATH_LOOPUNROLL to enable manual loop unrolling in DSP functions

ARM_MATH_NEON:

Define macro ARM_MATH_NEON to enable Neon versions of the DSP functions. It is not enabled by default when Neon is available because performances are dependent on the compiler and target architecture.

ARM_MATH_NEON_EXPERIMENTAL:

Define macro ARM_MATH_NEON_EXPERIMENTAL to enable experimental Neon versions of of some DSP functions. Experimental Neon versions currently do not have better performances than the scalar versions.

ARM_MATH_HELIUM:

It implies the flags ARM_MATH_MVEF and ARM_MATH_MVEI and ARM_MATH_FLOAT16.

ARM_MATH_MVEF:

Select Helium versions of the f32 algorithms. It implies ARM_MATH_FLOAT16 and ARM_MATH_MVEI.

ARM_MATH_MVEI:

Select Helium versions of the int and fixed point algorithms.

ARM_MATH_FLOAT16:

Float16 implementations of some algorithms (Requires MVE extension).

Файлы проекта

  • *.UVPROJ: Обязательный файл проекта в формате XML.
  • *.UVOPT: Обязательный файл параметров проекта в формате XML. Содержит настройки отладчика, точки останова (breakpoints), текущие открытые файлы и прочее.
  • *.UVMPW: Обязательный файл сложного проекта, состоящего из множества простых проектов. Содержит ссылки на простые проекты (*.UVPROJ) и связывает их в один проект. Файл в формате XML.
  • *.UVGUI: Необязательный файл настроек графического интерфейса. Расширение  добавляется, чтобы предоставить каждому пользователю собственные настройки. Когда файл отсутствует, uVision4 использует настройки по-умолчанию.
  • *.UV2: Файл проекта старых версий uVision. uVision4 поддерживает конвертацию в файл проекта нового типа (*.UVPROJ).
  • *.OPT: Файл параметров проекта старых версий uVision. Содержит настройки отладчика, текущие открытые файлы, позиции экрана и прочее. uVision4 поддерживает конвертацию в файл параметров нового типа (*.UVOPT).

CARM C CompilerDiscontinued – Replaced by RealView Compilation Tools

The Keil CARM C Compiler for the ARM family of microcontrollers
allows you to write ARM applications in C that, once compiled, have
the efficiency and speed of assembly language. Language extensions in
the CARM Compiler give you full access to all resources of
ARM-powered devices.

The CARM Compiler translates C source files into relocatable
object modules which contain full symbolic information for debugging
with the µVision Debugger or an in-circuit emulator. In
addition to the object file, the compiler generates a listing file
which may optionally include symbol table and cross reference
information.

Feature Benefit
ARM Mode andThumb ModeCode Generation You can mix ARM and Thumb code in the same
source file. ARM mode is required for interrupt handlers and fast
signal-processing algorithms while Thumb mode provides the
smallest code size.
FunctionAttributes forHardwareSupport

The Keil C compiler provides function attributes that give you
access to ARM hardware features
For example:

  • __irq and __fiq
    allow you to create standard and fast interrupt service
    routines in C.
  • __swi(id) allows
    you to invoke a software interrupt handler.
  • __ram defines a function
    that is copied to RAM for fast execution or Flash
    programming.
InlineAssembler You may insert assembler code into C
functions with assembler-level access to C variables. This
capability is necessary for fast DSP and other signal-processing
algorithms. The Keil compiler supports full program optimization
even when inline assembler is used.
FunctionIn-lining You may speed-up execution of frequently
called functions by using function in-lining. Inline functions
are expanded inline without the overhead associated with function
call, parameter passing, and return.
AbsoluteVariablePlacement The _at_ keyword may be used to
specify the physical address for a variable. This allows you to
easily define shared memory areas or hardware peripherals.
ParameterPassing inCPU Registers The Keil compiler automatically uses CPU
registers to pass function arguments. It can even pass and return
small C structs in registers.
ReentrantRun-timeLibrary Most library routines are reentrant (refer
to the library reference in the Compiler User’s Guide) and may be
invoked from the main program thread and from interrupts. There
is no need to include special protection schemes for library
calls.
Thread-safeFloating-pointOperations All floating-point operations are
reentrant. Floating-point may be used in the main program thread
and interrupts. No interrupt blocking or special protection
schemes are required.

Прерывания

SysTick

SysTick — это таймер, встроенный в ядро микроконтроллера. STM32Cube использует его для отсчета времени в миллисекундах. Об этой полезной особенности библиотеки у меня есть статья.

Чтобы отсчет времени работал, в проект надо добавить правильную реализацию функции SysTick_Handler(). Это функция обрабатывает прерывания от SysTick, и должна увеличивать счетчик времени на 1.

Добавим в файл main.c следующий код:

void SysTick_Handler(void) {
    HAL_IncTick();
}

Таблица прерываний

В файле startup_ARMCMx.c задается таблица прерываний. Изначально она не соответствует реальным микроконтроллерам. Таблицу надо сформировать самостоятельно.

Файл содержит объявление функций-обработчиков прерываний:

/*----------------------------------------------------------------------------
  Exception / Interrupt Handler
 *----------------------------------------------------------------------------*/
/* Cortex-M4 Processor Exceptions */
void NMI_Handler         (void) __attribute__ ((weak, alias("Default_Handler")));
void HardFault_Handler   (void) __attribute__ ((weak, alias("Default_Handler")));
void MemManage_Handler   (void) __attribute__ ((weak, alias("Default_Handler")));
void BusFault_Handler    (void) __attribute__ ((weak, alias("Default_Handler")));
void UsageFault_Handler  (void) __attribute__ ((weak, alias("Default_Handler")));
void SVC_Handler         (void) __attribute__ ((weak, alias("Default_Handler")));
void DebugMon_Handler    (void) __attribute__ ((weak, alias("Default_Handler")));
void PendSV_Handler      (void) __attribute__ ((weak, alias("Default_Handler")));
void SysTick_Handler     (void) __attribute__ ((weak, alias("Default_Handler")));

...

За объявлениями следует таблица прерываний:

/*----------------------------------------------------------------------------
  Exception / Interrupt Vector table
 *----------------------------------------------------------------------------*/
const pFunc __Vectors[] __attribute__ ((section(".vectors"))) = {
  /* Cortex-M4 Exceptions Handler */
  (pFunc)&__StackTop,                       /*      Initial Stack Pointer     */
  Reset_Handler,                            /*      Reset Handler             */
  NMI_Handler,                              /*      NMI Handler               */
  HardFault_Handler,                        /*      Hard Fault Handler        */
  MemManage_Handler,                        /*      MPU Fault Handler         */
  BusFault_Handler,                         /*      Bus Fault Handler         */
  UsageFault_Handler,                       /*      Usage Fault Handler       */
  0,                                        /*      Reserved                  */
  0,                                        /*      Reserved                  */
  0,                                        /*      Reserved                  */
  0,                                        /*      Reserved                  */
  SVC_Handler,                              /*      SVCall Handler            */
  DebugMon_Handler,                         /*      Debug Monitor Handler     */
  0,                                        /*      Reserved                  */
  PendSV_Handler,                           /*      PendSV Handler            */
  SysTick_Handler,                          /*      SysTick Handler           */

...

Массив __Vectors[] содержит имена функций-обработчиков прерываний.

Первая часть таблицы (до SysTick_Handler включительно) общая для всех микроконтроллеров. Остальное нужно дописать аналогичным образом на основании документации на микроконтроллер.

Cortex-M Reference Manuals

The Cortex-M Device Generic User Guides contain the programmers model and detailed information about the core peripherals and are available for:

  • Cortex-M0 Devices Generic User Guide (Armv6-M architecture)
  • Cortex-M0+ Devices Generic User Guide (Armv6-M architecture)
  • Cortex-M3 Devices Generic User Guide (Armv7-M architecture)
  • Cortex-M4 Devices Generic User Guide (ARMv7-M architecture)
  • Cortex-M7 Devices Generic User Guide (Armv7-M architecture)

The Cortex-M23 and Cortex-M33 are described with Technical Reference Manuals that are available here:

  • Cortex-M23 Technical Reference Manual (Armv8-M baseline architecture)
  • Cortex-M33 Technical Reference Manual (Armv8-M mainline architecture)

CMSIS also supports the following Cortex-M processor variants:

  • Cortex-M1 is a processor designed specifically for implementation in FPGAs (Armv6-M architecture).
  • SecurCore SC000 is designed specifically for smartcard and security applications (Armv6-M architecture).
  • SecurCore SC300 is designed specifically for smartcard and security applications (Armv7-M architecture).
  • Cortex-M35P is a temper resistant Cortex-M processor with optional software isolation using TrustZone for Armv8-M.

Introduction

This user manual describes the CMSIS DSP software library, a suite of common signal processing functions for use on Cortex-M and Cortex-A processor based devices.

The library is divided into a number of functions each covering a specific category:

  • Basic math functions
  • Fast math functions
  • Complex math functions
  • Filtering functions
  • Matrix functions
  • Transform functions
  • Motor control functions
  • Statistical functions
  • Support functions
  • Interpolation functions
  • Support Vector Machine functions (SVM)
  • Bayes classifier functions
  • Distance functions

The library has generally separate functions for operating on 8-bit integers, 16-bit integers, 32-bit integer and 32-bit floating-point values.

Прочие файлы

  • *.CDB: µVision Device Database file.
  • *.DEP: Dependency File for a Target build.
  • *.IC: Intermediate C source file created by the EC++ Compiler.
  • *.LIN: Linker Control File (scatter loading).
  • *.LNP: Linker Input File generated by µVision4 to pass command line.
  • *.ORC: Global Register Coloring File for Optimization.
  • *.PLG: Protocol file that summarizes the last build process.
  • PROJECT_GUI.XSD: µVision4 XML schema file describing the *.UVGUI file structure. Located in the \UV4 folder.
  • PROJECT_MPW.XSD: µVision4 XML schema file describing the *.UVMPW file structure. Located in the \UV4 folder.
  • PROJECT_OPT.XSD: µVision4 XML schema file describing the *.UVOPT file structure. Located in the \UV4 folder.
  • PROJECT_PROJ.XSD: µVision4 XML schema file describing the *.UVPROJ file structure. Located in the \UV4 folder.
  • *.UVL: Signal definition file. Export the Logic Analyzer signal definitions to a file.
  • *.UVLA: File to store recorded signals. Saves recorded signal data to later analysis.
  • *.SFD: Intermediary pseudo-XML file used to create an *.SFR file (*.SVD.XML files are used as input).
  • *.SFR: Binary file storing information read by the System Viewer.
  • *.SVD.XML, *.SVD, *.XML: CMSIS-XML file formats describing the device (CMSIS System View Description file). The file is provided by the vendor.

Создание проекта

Теперь есть все необходимое, чтобы создать проект.

Чтобы создать проект на языке C, выберем меню File -> New -> C Project.

Можно создать проект на языке C++, но возникнет множество нюансов, которые усложнят разработку. О них я расскажу в другой статье.

В появившемся окне будет предложено задать имя проекта, его расположение, тип проекта и набор инструментов.

Проект я назову example. Тип — пустой проект (Empty Project). Набор инструментов — Cross ARM GCC, что соответствует ранее установленному GCC ARM.

После нажатия Next будет предложено выбрать конфигурации проекта. Конфигурации позволяют по разному собирать проект, с разными настройками. В дальнейшем можно создать любое количество конфигураций. Но придется возиться с их настройками. Для простоты оставим одну конфигурацию Release.

Далее будет предложено уточнить набор инструментов и указать путь к ним. По умолчанию выбран набор GCC ARM: «GNU Tools for ARM Embedded Processors (arm-none-eabi-gcc)«. В качестве пути нужно указать путь к папке GNU ARM.

После нажатия Finish проект будет создан. Его иерархическая структура отображается во вкладке Project Explorer. В этой же вкладе может отображаться множество проектов.

CMSIS

CMSIS — это базовая библиотека для ARM-микроконтроллеров.

Ее можно скачать с сайта ARM после регистрации.

CMSIS распространяется в виде архива, который нужно распаковываем в удобное место.

Подключение библиотеки будет разобрано в соответствующем разделе далее.

В CMSIS есть папка

Device/ARM/ARMCMx/Source/GCC/

Есть несколько папок ARMCMx, которые соответствуют разным ядрам микроконтроллеров. Имя папки расшифровывается как ARM Cortex-M. Выбираем папку в соответствии с микроконтроллером.

Из этой папки в папку проекта требуется скопировать пару файлов:

  • gcc_arm.ld
  • startup_ARMCMx.c

Чтобы файлы появились в Eclipse, нажмите F5 в Project Explorer, либо в контекстном меню проекта выберете Refresh. Это обновит список файлов.

Оба файла придется отредактировать.

gcc_arm.ld

Это скрипт для линковки проекта. Он отвечает за распределение разных областей памяти в микроконтроллере.

В этом файле задается объем постоянной и оперативной памяти микроконтроллера, а также их начальные адреса. Эти параметры нужно отредактировать в соответствии с используемым микроконтроллером.

Параметры задаются в самом начале файла с помощью следующего кода:


/* Linker script to configure memory regions. */
MEMORY
{
  FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x40000   /* 256k */
  RAM (rwx)  : ORIGIN = 0x20000000, LENGTH = 0x08000   /*  32k */
}

В переменной ORIGIN задается начальный адрес области памяти, а в LENGTH — ее объем в байтах. FLASH — это постоянная память, RAM — оперативная.

В STM32 начальный адрес постоянной памяти — 0x08000000, оперативной (как и указано) — 0x20000000.

startup_ARMCMx.c

Это файл с исходным кодом на языке C, который содержит базовый код программы и таблицу прерываний. Кроме того в файле задается объем  и кучи. Код из этого файла выполняется до вызова функции main() и вызывает функцию main().

Таблица прерываний в этом файле скорее всего не соответствует таблице используемого микроконтроллера. Файл нужно отредактировать в соответствии с таблицей прерываний микроконтроллера. Об этом речь пойдет позже.

Размер кучи и стека должен соответствовать потребностям проекта и объему оперативной памяти микроконтроллера.

Размер кучи и стека задается следующим кодом:

...
  #define __STACK_SIZE 0x00000400
...
  #define __HEAP_SIZE 0x00000C00
...

__STACK_SIZE определяет объем стека. __HEAP_SIZE — объем кучи. В сумме оба значения не должны превышать объем оперативной памяти.

GNU ARM Eclipse

GNU ARM Eclipse — это дополнение для Eclipse, которое поможет связать его с GCC ARM.

Для его установки запустим Eclipse и выберем меню Help -> Install New Software:

В появившемся окне нажмем кнопку Add, чтобы добавить источник дополнения.

После нажатия OK необходимо немного подождать пока в таблице загрузится список пакетов.

Ставим галочку напротив GNU ARM C/C++ Cross Development Tools и нажимаем Next.

Затем проходим процедуру установки нажимая Next и соглашаясь с условиями лицензии.

Установка займет некоторое время. В какой-то момент в диалоговом окне появится вопрос, продолжить ли установку неподписанного содержимого, смело жмем OK.

В конце установки будет предложено перезапустить Eclipse. Соглашаемся.

Первый проект в Keil 5 + STM32 CubeMX

Details
Автор Super User

В статье описано, каким образом можно создать проект с помощью программы STM32CubeMX (да, именно так она теперь называется) и библиотеки HAL. В проекте используется микроконтроллер STM32F407VGT6, но для других моделей действия будут аналогичны.

Для работы нам понадобятся:

  • Keil uVision 5;
  • STM32CubeMX;
  • микроконтроллер;
  • программатор.

Шаг 0. Если на вашем компьютере не установлен STM32CubeMX или Keil uVision 5, скачайте и установите их. При установке STM32CubeMX может потребоваться установка Java-платформы.

Шаг 1. Запускаем STM32CubeMX, выбираем «New project». В появившемся окне выставляем фильтр на требуемый микроконтроллер, выбираем его и жмем «ОК».

Шаг 2. Попробуем создать проект, в котором контроллер будет управлять работой светодиода. На моей отладочной плате светодиод подключен к выводу «PORTD.12» (узнать это можно из документации к плате). Выбираем нужный вывод микроконтроллера на схеме и кликаем по нему левой кнопкой мыши и из предложенных настроек вывода выбираем «GPIO_Output», т.е. назначаем его на вывод. Контроллер настроен!

Шаг 3. Настройка генерации проекта. Нажимаем «Project»  -> «Settings».

В открывшемся окне на вкладке «Project» в первое поле вводим название проекта, в следующее поле — путь к папке, где будет храниться проект, ниже в выпадающем списке выбираем IDE, для которой создается проект, и нажимаем кнопку «ОК». Про оставшиеся настройки расскажу в следующих статьях.

Шаг 4. Генерация проекта. Для того, чтобы запустилась генерация проекта, необходимо нажать на кнопку с шестеренкой и в открывшемся окне нажать кнопку «Open project».

Шаг 5. Проверка созданного проекта. После нажатия на кнопку начнет запускаться Keil.

Переходим в Keil, в обозревателе проекта раскрываем группу «Application/User», открываем файл «Main.c», ищем в нем цикл «while(1)» и вписываем пару строк кода.

В первой строке кода вызывается процедура, которая меняет состояние вывода на противоположное (т.е. если светодиод светился, то должен погаснуть и наоборот). Вторая строка кода — это пауза.

Далее нажимаем на кнопку постройки проекта.

Пока проект собирается, подключаем отладочную плату к компьютеру. Как только проект будет скомпилирован, нажимаем на кнопку загрузки кода в микроконтроллер. После загрузки необходимо перезагрузить микроконтроллер. По умолчанию STM32CubeMX в настройках проекта устанавливает программатор «St-Link», если используется другой программатор, необходимо зайти в настройки проекта и установить нужный программатор.

Если все сделано правильно, светодиод на плате вам поморгает ;-)

Оцените статью:
Оставить комментарий