Iar embedded workbench

IAR Embedded Workbench Tutorial for MSP430

Iar embedded workbench

Iar embedded workbench

A short tutorial on how to use the IAR Embedded Workbench  5.3 to program and debug MSP430 microcontrollers on a windows box.The article teaches the reader to create and  compile a simple C Project to blink the LED on a launchpad development board  from Texas Instruments.The article can also be used with other MSP430 emulators like MSP430 Flash Emulation Tool (MSP-FET).

IAR Embedded Workbench for MSP430 is a commercial integrated development environment developed by IAR Systems. The IDE comes in a paid full version and a code limited trial version.

The free version can be downloaded from the IAR website free of charge and supports all the MSP430 derivatives. It is limited to a program size of 4KB.

This would sufficient for programming most MSP430G2xxx series that comes with Launchpad development kit.

If you require more program size than 4 KB then you can try Code Composer Studio from Texas Instruments (Free Version –16 KB code limit) or Open source MSPGCC compiler.

Installation

Installation is simple, you can download the .exe file from the IAR website to your computer. They may ask you to register first before downloading. After the executable is downloaded run it and complete the installation. Please restart your computer after the installation is completed otherwise the drivers may not function properly.

Creating a Project in IAR

After the installation is complete double click on the IAR EW icon in the desktop. This will launch the IDE with a blank workspace and some release notes .

We are going to create a small C project to blink an LED on a Launch pad Development board from TI. You can download the sample codes for the appropriate controller (here MSP430G2553) from Texas instrument Website.

Now click on the “Project “ menu from the menu bar and select “Create New Project….” which will open a new window called “Create New Project”.

On this window we can see templates for creating Assembly language, C, and C++ projects. If we select the “asm” template it would create default assembler project with a *.s43 file (assembly language source file).Here we want to create a C project ,So click on “main” and press ok. Now the IDE will ask you to save the project. Please create a folder and save your project files in it.

Now IDE will show a file called “ main.c” with some default code in it.

Now either you can edit the “main.c” or you can remove it by right clicking on it and selecting “Remove “ option. In this case we are going to remove the “main.c” .Removing the file will not delete file from the directory so open your project directory and manually delete “main.c”.

Now click on the new document icon on the menu bar

It would create a new file called “untitled”, Save the file in your project directory as “led_blink.c” by right clicking on it.

Now Type / Paste the following code into led_blink.c and save it.

// A simple program to blink LED on P1.0// of Msp430g2553 on Launchpad#include “msp430g2553.h” //header file for msp430g2553void main(void) {     WDTCTL = WDTPW + WDTHOLD;// Stop the watchdog     P1DIR |= BIT0;           // P1.0 as o/p     P1OUT = 0x00;            // clear Port 1      int i;     while(1) //infinite loop          {            for(i=0;i

Использование примеров для STM32F4DISCOVERY в IAR Embedded Workbench for ARM

Iar embedded workbench

В  статье “Программное обеспечение для STM32F4DISCOVERY  (http://firsthand.ru/node/298)” я уже писал, что примеры которые идут вместе с IAR EWARM (IAR Embedded Workbench for ARM) для микроконтроллеров STM32F4 не работают с STM32F4Discovery, потому что они ориентированы на их собственную отладочную плату IAR KickStart Kit for STM32F407ZG.

Для того чтобы работать в IAR EWARM с STM32F4Discovery нужны примеры именно для STM32F4-Discovery и именно для среды разработки или toolchain IAR EWARM (IAR Embedded Workbench for ARM).

Такие примеры есть у самой компании STMicroelectronics и их можно свободно использовать.

Скачать примеры можно с сайта “www.st.com” компании “STMicroelectronics” со страницы с названием

STSW-STM32068
STM32F4DISCOVERY board firmware package, including 22 examples (covering USB Host, audio, MEMS accelerometer and microphone) (AN3983)

Попасть на неё легче через поиск. Можно и по другому, но мне нравиться через поиск. Так быстрее. Просто набираешь “STSW-STM32068” и первая ссылка ведет куда надо.

Ищем внизу на странице раздел “Get Software” и жмем на кнопочку “Download” напротив STSW-STM32068. После этого загружается zip-архив stsw-stm32068.zip.

В данном архиве, после распаковки, видим папку STM32F4-Discovery_FW_V1.1.0. Эта папка и содержит примеры для STM32f4discovery.

Эту папку можно теперь перенести в папку с проектами IAR EWARM, оставить там где она есть или перенести в, специально созданную для экспериментов, свою папку.

У меня такой папкой является E:PROJSTM32F4, вот туда я и перенес папку STM32F4-Discovery_FW_V1.1.0. со всем её содержимым.

Практически во всех примерах от официальных изготовителей микроконтроллеров и изготовителей отладочных плат файлы проектов для IAR EWARM (IAR Embedded Workbench for ARM) размещаются в папках с названием EWARM.

Например, есть папка “Demonstration” с файлами проекта демонстрации некоторых основных возможностей отладочной платы, а в ней есть папка  EWARM, в которой находятся файлы проекта для IAR EWARM.

Пример работы с портами ввода/вывода GPIO я нашел в папке “E:PROJSTM32F4STM32F4-Discovery_FW_V1.1.0ProjectPeripheral_ExamplesIO_Toggle” и файлы проекта для  IAR EWARM соответственно в папке “E:PROJSTM32F4STM32F4-Discovery_FW_V1.1.0ProjectPeripheral_ExamplesIO_ToggleEWARM

Далее находим файл с расширением “.eww” – это IO_Toggle.eww. Это основной файл для проекта в IAR EWARM. Щелкаем по нему мышкой и если toolchain IAR EWARM установлен правильно, то вскоре откроется IAR Embedded Workbench for ARM с загруженным проектом IO_Toggle.

Слева отображается состав проекта, а внизу две строчки сообщают что проект создан для STM32F407VG.

В папке User находиться файл main.c в котором содержиться основной код программы и откуда всегда стоит начинать изучать примеры. Но сейчас мы этот шаг изучения пропустим, потому что основная цель – это проверить работоспособность примеров для STM32F4discovery в среде разработки IAR Embedded Workbench for ARM.

Для этого просто откомпилируем пример работы с портом ввода/вывода GPIO. Для этого в меню выбираем “Project”, затем “Rebuild All”. Так проверим наличие ошибок, все ли файлы присутствуют и, если всё хорошо, откомпилируем пример.

После компиляции проекта выходит сообщение о том, что ошибок нет и замечаний нет.

Теперь загрузим полученную прошивку в микроконтроллер в режиме отладки. Если отладочная плата STM32F4discovery ещё не подключена, то самое время её подключить. В меню выбираем “Project”, затем “Download and Debug”.

После загрузки, выполнение программы останавливается на строке подсвеченной зеленым цветом.

Теперь можно проверить работу программы в пошаговом режиме, или запустить непрерывное выполнение. Для непрерывного выполнения нажимаем на кнопочку “Go”. Ранее погасшие светодиоды начинают мигать по часовой стрелке. То есть, пример откомпилировался, загрузился и нормально себя чувствует в памяти микроконтроллера, выполняя заданную работу.

Теперь можно остановить отладку. При этом программа в микроконтроллере никуда не изчезает, а спокойно продолжает работать.

И как итог, получаем что примеры для STM32F4-Discovery с сайта st.com для IAR EWARM вполне рабочие и ими можно пользоваться для изучения и освоения микроконтроллера STM32F407VG.

ZiB

Iar embedded workbench

Прошло уже много времени с первого знакомства с микроконтроллерами STM8, на текущий момент у меня сложилось уже некоторое “понимание” компилятора Cosmic и появилось желание сравнить его с популярным продуктом IAR Embedded Workbench ®. Точнее меня интересует как реализовано выполнения кода из ОЗУ.

IAR Embedded Workbench® это интегрированная среда для разработки и отладки программ для различных платформ, в данном случае для микроконтроллеров серии STM8A, STM8S и STM8L.

На текущий момент предлагается версия 1.30 и два варианта использования:

  • 30-day evaluation edition – 30 дневная пробная версия, без ограничения по размеру кода
  • 8kB KickStart edition – почти без ограничения по времени (на текущий момент выдают лицензию до 2036 года), но с ограничением по размеру кода (8 кБ)

И ещё два варианта: купить полноценную версию или крякнуть ?

Переустанавливать программы я не люблю, взламывать не наши методы, поэтому я выбрал 8kB KickStart edition для пробы более чем достаточно.

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

Процесс регистрации, загрузки и установки описывать не буду там все тривиально, отмечу только что размер дистрибутива составляет 106 Мб.

Первый запуск

Как и в эклипсе первым делом необходимо создать рабочее пространство Workspace:

и новый проект:

я выбрал обычный Си.

Получилась вот такая заготовка:

Осталось только настроить проект под наши нужды.

Для этого открываем настройки проекта (Alt+F7) и производим следующие:

  • выбираем необходимый микроконтроллер, в моем случае это STM8S105C6
  • изменяем уровень оптимизации на максимальный
  • и выбраем ST-Link

Для примера я взял инициализацию OLED дисплея, скопировал все файлы в директорию проекта и подключил исходник для OLED дисплея:

Собралось все без проблем, что удивило ?

Разница в размере получилась не большая:

  • IAR – 762 байт
  • Cosmic – 701 байт

Но это для меня не главное, как я уже говорил мне интересно выполнение кода из ОЗУ.

Дело в том что если в коде используются какие либо библиотечные функции, то они по прежнему остаются во флеш. В космике я не смог пока решить эту проблему.

Для проверки объявил функцию задержки с атрибутом __ramfunc , но чуда и тут не произошло

как видим идет вызов встроенной подпрограммы load32_10_dbsp расположенной по прежнему во флеш ? (адрес 0x822C)

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

Если кто знает как решить или есть какие-то мысли по этому поводу напишите пожалуйста.

IAR Embedded Workbench – PDF

Iar embedded workbench

1 IAR Embedded Workbench IDE Project Management and Building Guide UIDEEW-7

2 COPYRIGHT NOTICE IAR Systems AB. No part of this document may be reproduced without the prior written consent of IAR Systems AB. The software described in this document is furnished under a license and may only be used or copied in accordance with the terms of such a license.

DISCLAIMER The information in this document is subject to change without notice and does not represent a commitment on any part of IAR Systems. While the information contained herein is assumed to be accurate, IAR Systems assumes no responsibility for any errors or omissions.

In no event shall IAR Systems, its employees, its contractors, or the authors of this document be liable for special, direct, indirect, or consequential damage, losses, costs, charges, claims, demands, claim for lost profits, fees, or expenses of any nature or kind.

TRADEMARKS IAR Systems, IAR Embedded Workbench, C-SPY, visualstate, The Code to Success, IAR KickStart Kit, I-jet, I-scope, IAR, and the logotype of IAR Systems are trademarks or registered trademarks owned by IAR Systems AB. Microsoft and Windows are registered trademarks of Microsoft Corporation.

Adobe and Acrobat Reader are registered trademarks of Adobe Systems Incorporated. All other product names are trademarks or registered trademarks of their respective owners. EDITION NOTICE Seventh edition: April 2014 Part number: UIDEEW-7 Internal reference: M15, Hom7.0.x, IJOA. 2 IDE Project Management and Building Guide

3 Brief contents Tables Preface Part 1. Project management and building The development environment Project management Building projects Editing Part 2. Reference information Installed files Menu reference Glossary Index

4 4 IDE Project Management and Building Guide

5 Contents Tables Preface Who should read this guide Required knowledge How to use this guide Some descriptions do not apply to your product What this guide contains Part 1. Project management and building Part 2.

Reference information Other documentation User and reference guides The online help system Web sites Document conventions Typographic conventions Naming conventions Part 1.

Project management and building The development environment Introduction to the IAR Embedded Workbench IDE Briefly about the IDE and the build toolchain An extensible and modular environment Organizing the windows on the screen Using and customizing the IDE Running the IDE Organizing windows Specifying tool options Recognizing filename extensions Getting started using external analyzers Invoking external tools from the Tools menu

6 Adding command line commands to the Tools menu Using an external editor Reference information on the IDE IAR Embedded Workbench IDE window Tool Output window Common Fonts options Key Bindings options Language options Editor options Configure Auto Indent dialog box External Editor options Editor Setup Files options Editor Colors and Fonts options Messages options Project options External Analyzers options External Analyzer dialog box Source Code Control options Debugger options Stack options Register Filter options Terminal I/O options Configure Tools dialog box Configure Viewers dialog box Edit Viewer Extensions dialog box Filename Extensions dialog box Filename Extension Overrides dialog box Edit Filename Extensions dialog box Argument variables Configure Custom Argument Variables dialog box Project management Introduction to managing projects Briefly about managing projects

7 Contents How projects are organized Interacting with version control systems Managing projects Creating and managing workspaces Viewing the workspace Interacting with SCC-compatible systems Interacting with Subversion Reference information on managing projects Workspace window Create New Project dialog box Configurations for project dialog box New Configuration dialog box Add Project Connection dialog box Version Control System menu for SCC Select Source Code Control Provider dialog box Check In Files dialog box Check Out Files dialog box Source code control states Version Control System menu for Subversion Subversion states Building projects Introduction to building projects Briefly about building a project Extending the toolchain Building a project Setting project options using the Options dialog box Building your project Correcting errors found during build Using pre- and post-build actions Building multiple configurations in a batch Building from the command line Adding an external tool

8 Reference information on building Options dialog box Build window Batch Build dialog box Edit Batch Build dialog box Editing Introduction to the IAR Embedded Workbench editor Briefly about the editor Briefly about source browse information Customizing the editor environment Editing a file Indenting text automatically Matching brackets and parentheses Splitting the editor window into panes Dragging text Code folding Word completion Code completion Parameter hint Using and adding code templates Syntax coloring Adding bookmarks Using and customizing editor commands and shortcut keys Displaying status information Programming assistance Navigating to a function Finding a definition or declarations of a symbol Finding references to a symbol Finding function calls for a selected function Switching between source and header files Displaying source browse information Text searching Accessing online help for reference information

9 Contents Reference information on the editor Editor window Find dialog box Find in Files window Replace dialog box Find in Files dialog box Replace in Files dialog box Incremental Search dialog box Declarations window Ambiguous Definitions window References window Source Browser window Resolve File Ambiguity dialog box Call Graph window Template dialog box Editor shortcut key summary Part 2. Reference information Installed files Directory structure Root directory The cpuname directory The common directory The install-info directory File types Menu reference Menus File menu Edit menu View menu Erase Memory dialog box Project menu

10 Tools menu Window menu Help menu Glossary Index

11 Tables 1: Filename extensions in XLINK versus ILINK : Typographic conventions used in this guide : Naming conventions used in this guide : Argument variables : iarbuild.

exe command line options : Editor shortcut keys for insertion point navigation : Editor shortcut keys for selecting text : Editor shortcut keys for scrolling : Miscellaneous editor shortcut keys : Miscellaneous editor shortcut keys : The cpuname directory : The common directory : File types

12 12

IAR Embedded Workbench

Iar embedded workbench

The IDE has new artwork, enhancements to window management and docking, customizable toolbars, revised Information Center, and new tutorials.

Support for the C11 language standard

The compiler and libraries add support for the latest C language standard ISO/IEC 9899:2011.

Support for the C++14 language standard

The compiler and libraries now support the latest C++ standard ISO/IEC 14882:2014.

Unicode support

The Unicode standard for consistent encoding, representation, and handling of text is now supported. This means that you can use Unicode characters (alphabetic, numeric, symbols, emoji, etc) in the source code.

Stack usage analysis

With stack usage analysis enabled, a stack usage section will be added to the linker map file with listings of the maximum stack depth for each call graph root. The analysis process can be customized to take into account such constructs as calls via function pointers and recursion. The output can optionally be generated in XML format for post-processing activities.

Stack protection

The IAR C/C++ compiler for RH850 now supports stack protection.

A canary value will be placed between the stack variables and the return address so that the system can detect corruption of a function return address before the function returns to that address.

The compiler will use heuristic to determine whether a function needs stack protection or not. If any defined local variable has the array type or a structure type that contains a member of array type, the function will need stack protection.

Renesas Smart Configurator included

Renesas Smart Configurator is a standalone tool for automatically generating control programs (device driver programs) for peripheral modules in accordance with settings. It fully supports code generation for IAR Embedded Workbench for RH850 and the generated modules are incorporated via the IAR Project Connection mechanism.

Enhanced Registers and Symbols windows in C-SPY

The C-SPY Symbols and Registers windows have been re-designed with new features.

The Symbols window now has a filtering function and a new column displaying to which program module a certain symbol belongs.

Some of the new features in the Registers window are drag-and-drop support from source code windows, detailed register tool-tip information, and improved handling of user-defined registers groups.

C-STAT MISRA C

The MISRA C 2004 package in C-STAT has been updated with about 20 new checks, some of which are enabled by default.

Использование среды разработки IAR Ebedded Workbench IDE

Iar embedded workbench

Используя разные микроконтроллеры, возникает необходимость выбрать удобную среду разработки. Нам есть из чего выбирать – будь то IAR или Keil µVision, или, даже Code Composer Studio. Ниже пойдет речь об IAR Embedded Workbench IDE на примере STM32F10x. Эта среда разработки достаточно мощная. Имеются всякие вкусняшки.

Настройка IAR

В первую очередь нужно настроить IAR.

Основные настройки

После запуска IAR заходим в опции (Tools->Options…). Сразу же будет выбран пункт Editor. В поле Ident size число указывает на количество пробелов при нажатии Tab. Для меня удобно использовать число 4.
Стоит уделить внимание пункту Key Bindings.

Здесь можно назначить горячие клавиши. Согласитесь, все-таки, удобно и быстро пользоваться комбинациями клавиш. Пока что, можно назначить комбинацию Ctrl+W как закрытие активных вкладок. Для этого в Menu выбираем Window и для команды Close active tab назначаем Ctrl+W.

С остальными горячими клавишами познакомимся ниже.

Настройки проекта

Допустим, создавать новый проект мы умеем (если нет, то Project->Create New Project…). После создания проекта нам доступны две конфигурации проекта – Debug и Release. Переключаться между ними можно в окне Workspace:

Рис.

1 – Окно Workspace

Удобно использовать несколько конфигураций. В конфигурации Debug можно выбрать симулятор программатора, а в Release – конкретный программатор (к примеру, J-Link).

Что позволит сначала отлаживать в симуляторе, не теряя время на прошивку микроконтроллера, а потом уже прошивать под конфигурацией Release.

Добавлять новые конфигурации можно через меню: Project->Edit Configurations.
Опции самого проекта – Project->Options… (Alt+F7). Для открытия окна опций проекта нужно выделить сам проект в окне Workspace, иначе откроются опции того файла, который был выделен.
Настройки буду приводить для конфигурации Debug (в скобках – для Release).
Открываем опции (Alt+F7)

  • General Options.
    Вкладка Target. Выбираем Device – например, ST STM32F100xB (у меня STM32VLDISCOVERY с STM32F100RBT6 на борту).
  • С/C++ Compiler.
    Вкладка Optimizations. Выбираем LevelNone (для ReleaseHigh).
    Вкладка Preprocessor. В поле Additional include directories вводим все пути заголовочных файлов, имеющих расширение *.h. Например:
    $PROJ_DIR$..Libinclude
    Остальные переменные, на подобии $PROJ_DIR$, можете посмотреть в хелпе по F1, введя в поиске Argument variables.
    В этой же вкладке, в поле Defined symbols вписываем нужные дефайны. Это аналог обычной директивы #define. Для нашей отладочной платки нужно ввести STM32F10X_MD_VL, если мы хотим использовать библиотеки от криворуких STM’овцев.
    Так же для конфигурации Debug можно завести дефайн DEBUG. Это удобно, если использовать, к примеру, конструкцию:
    #ifndef DEBUG Delay(100 часов);

    #endif

    Зачем же нам ждать это время при отладке, правда же?

  • Linker.
    Вкладка Config. Здесь можно выбрать конфигурационный файл для линковщика, если это необходимо (если у вас не 8-ми битный микроконтроллер). Если необходимо перераспределить память микроконтроллера по-своему, то нужно ковырять файл *.icf. Об этом можно прочитать в Help->C/C++ Development Guide страница 81 Linking your application. Если эта тема сложная, то можно написать об этом отдельно. Спрашивайте, если что.
  • Debugger.
    Вкладка Setup. В поле Driver выбираем Simulator (для Release – свой программатор. Для моей платы – ST-LINK. В настройках для него нужно выбрать интерфейс SWD).

    Рис. 2 – Дерево проекта И, напоследок, создайте дерево проекта на ваш вкус.

  • Некоторые приемы

    Горячие клавиши

    Поиск:

    Обычный поиск – Ctrl+F
    Найти дальше – F3
    Поиск по файлам проекта – Ctrl+Shift+F
    Шагать по найденному (или по ошибкам/ворнингам) – F4

    Перейти к объявлению переменной (даже, если она в другом файле) – F12 — очень полезная функция!
    Навигация вперед – Alt+Right
    Навигация назад – Alt+Left

    Разное:

    Открыть header/source – Ctrl+Shift+H (или П.К.

    М в редакторе, и в контекстном меню выбрать Open Header/Source File)
    Закомментировать выделенный блок – Ctrl+K
    Разкомментировать – Ctrl+Shift+K
    Выделить содержимое скобок – Ctrl+B
    Автовыравнивание – Ctrl+T
    Поставить/убрать Breakpoint – F9
    Вставить шаблон – Ctrl+Shift+Space – тоже интересная штука.

    Чтобы добавить свой шаблон, нужно открыть файл CodeTemplates.ENU.txt через меню Edit->Code Templates->Edit Templates

    Теперь можно ввести примерно следующее:#TEMPLATE “&Warning”,”Введите текст:”=”Не забыть изменить”
    #warning %1
    Синтаксис шаблона:

    #TEMPLATE ,[=default value], … Знак «&» нужен для быстрого доступа (буква будет подчеркнута). Можно использовать знак «>» для создания подменю. Все интуитивно понятно.

    Сохраним файл и вызовем Template menu (Ctrl+Shift+Space). В нем выберем Warning:

    Рис. 3 – Вызов меню Template Введем необходимый текст:
    Рис. 4 – Шаблон Warning Жмякаем по кнопке OK. В результате, появится строчка:
    Рис. 5 – Результат использования шаблона

    При компиляции все ворнинги и ерроры (#error ) будут выводиться в окне Build.

    Заключение

    В этой статье были приведены основные возможности IAR, позволяющие достаточно быстро ориентироваться в проекте. Рекомендую использовать горячие клавиши. Это значительно сокращает время работы над проектом. Буду признателен, если читатель дополнит или поправит меня.

    Используемая литература

    Оцените статью
    Просто о технологиях
    Добавить комментарии

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: