LABORATORIO DI ARCHITETTURE E PROGRAMMAZIONE DEI SISTEMI ELETTRONICI INDUSTRIALI Laboratory Lesson 1: - Introduction to System Workbench for STM32 - Programming and debugging Prof. Luca Benini <luca.benini@unibo.it> Simone Benatti <simone.benatti@unibo.it> Bojan Milosevic <bojan.milosevic@unibo.it>
Outline Course organization C programming basics Writing the code Data and memory organization System Workbench: creating a project ST StdPeriph library First project: create, compile and debug
Course Introduction
Course Organization Theory lessons: Thursday 17.00 19.00 room 1.3 Hands-on session 1: LAB1 Thursday 14.00 17.00 Hands-on session 2: LAB1 Friday 11.00 14.00 Check website for announcements, course material: http://courses.eees.dei.unibo.it/labarch/
Lab Calendar 16/03 17/03 Lab1: IDE & Debug 23/03 24/03 Lab2: GPIO & SysTick 30/03 31/03 Lab3: Advanced Debugging 06/04 07/04 Lab4: EXTI & Debounce 20/04 21/04 Lab5: Timers 27/04 28/04 Lab6: DMA & Flash 04/05 05/05 Lab7: USART 11/05 12/05 Lab8: ADC 18/05 19/05 Lab9: I2C/SPI 25/05 26/05 Lab10: CMSIS 08/06 09/06 Lab11: Final projects
Lab1 You have a dedicated user account for this course: Username: Password: ele04 81Moto!! Lab PCs and the user account should be used only for the course Local user data will be erased at every log-out Take care to copy your files If you need access to lab outside of lab lessons (practice, assignments) you have to fill the form for the authorization (on the lab1 website) Please check the website and the lab rules here: http://www.dei.unibo.it/it/attivita-didattica/laboratori-e-tirocini/laboratorididattici/lab1
Group Organization Each group is composed by 2or 3 people (2 people groups are preferred) Please, register your group: https://goo.gl/forms/fw0izpkpl4xrlfyo1 Each group is provided with a development board, you need to get a mini USB cable You can use the Lab PCs or your personal Laptop All material is returned during the final discussion
Equipment checklist Computer with: Windows ( 7 / 8 / 10) or Linux (Ubuntu LTS) Lab PCs have everything you need, but you can use your own PC Development Board We will provide boards, but you are encouraged to buy one Mini USB Cable You have to buy one System Workbench for STM32 - www.openstm32.org You need to create an account to download the software (free)
Final Exam Final exam: Discussion (Theory Module 1 & 2) + Lab Evaluation Discussion: oral exam with questions on theory Lab evaluation: Weekly assignments (to be checked every week) Final project Lab Discussion (on lab project, additional to theory discussion) Lab assignments completion impact on final lab evaluation: All on time 2 late > 2 late Projects Projects Projects All lab assignments are mandatory to pass the exam at least they have to be returned before the exam Lab Discussion Lab Discussion Lab Discussion
Embedded Programming Basics
Embedded Programming Basics Common High level View of Computing Cache CPU Memory I/O Compilers Operating Systems Performance Costs Embedded Designer s View Memory Size I/O specs HW requirements Performance Costs
C programming language The C programming language is the most popular programming language for programming embedded systems C is very popular among microcontroller developers due to the code efficiency and reduced development time. C offers low-level control and is more readable than assembly. Additionally, using C increases portability, since C code can be compiled for different types of processors. Wide availability of existing libraries and examples ready to use.
From code to execution Preprocessor: The preprocessor handles directives for source file inclusion (#include), definitions (#define) and conditional inclusion (#if) Compiler: transforms source code into assembler modules Assembler: creates object code by translating assembly instruction mnemonics into opcodes Linker: it is a program that takes one or more objects generated by a compiler and combines them into a single executable program.
Cross-compiler Cross compiler Compiler capable to create executable code for a platform other than one in which the compiler is running. Cross compiler tools are used to generate executable code for embedded system or multiple platforms: The GNU Compiler Collection (GCC) is an open source compiler system produced by the GNU Project supporting various programming languages. Integrated Design Evironment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development An IDE normally consists of: source code editor compiler (or cross-compiler) Assembler Linker Debugger
Embedded System Debugging Debugging embedded systems is different in many aspects from traditional application debugging, due to hardware constraints and limited resources. This makes it inconvenient or even impossible to run a software debugger together with the debugged program on the same system. Because of these restrictions, embedded systems are usually debugged using remote debugging: The debugger is running on a host computer, and controls the target either through hardware, or through a small software running on the target. The developer can passively watch the code and the data flow or actively stop the target at the interest points.
JTAG JTAG (Joint Test Action Group) implements standards for on-chip instrumentation for device testing. It specifies the use of a dedicated debug port implementing a serial communications interface for low-overhead access to the system components (registers and memory). It allows the device programmer to transfer data into the internal memory. It is used for device programming and for active debugging (testing) of the executed program.
JTAG for debugging To debug with JTAG we need: 1) UI 2) Debugger 3) Daemon 4) Jtag interface 5) Target HW USB cable JTAG Target HW
Writing the Code
Writing the Code Programming style is very important! The style used in writing the code constrains the ease with which the program can be read, interpreted; The maintenance of the written source code, when adhering to a coding standard is easy to interpret, maintain and change; Programmers can develop their own programming style. However, for team work, they must meet a set of rules that provide uniformity to allow easy interpretation of the code by all team members
Writing the Code Use lots of comments to provide enough information to fully understand the code /* This is a comment */ Comment each procedure telling: /*----------------------------------*/ /* ProcedureName what it does */ /* Parameters: */ /* Param1 what param1 is */ /* Param2 what param2 is */ /* Returns: */ /* What is returned, if anything */ /*----------------------------------*/ Use lots of white space or blank lines Always use indentation: Align code blocks to highlight the functionality Each new scope is indented 2 spaces from previous Put { on end of previous line or start of next line Line matching } up below if(a < b) { b = a; a = 0; } else { a = b; b = 0; }
Variables Variables are symbolic names that hold values. Variable declarations include: A symbolic name; Type (int, char, double); Scope (that is the code region where the variable is defined); Variables are stored in memory or in registers. The compiler keeps track of where a variable value is currently stored and when it needs to be moved from memory to a register, or from a register to memory or deleted. The variables should be initialized when they are declared. The use of global variables should be avoided: they permanently use memory, but can make execution faster.
Declaration: Local versus Global Global variables: Declared outside of a function Accessible throughout the code Stored in Global Data Section of memory Scope is entire program Initialized to zero Local variables: Declared within one function and are only accessible during its execution Declared at the beginning of a block Stored on the stack Scope is from point of declaration to the end of the block Un-initialized Some tips: Avoid global variables. (if possible ) Keep declarations as close as you can to where you use the variables keep the scope as small as you can. It s better to explicitly pass parameters to functions, rather than use global variables.
Identifiers const: Used to declare a constant (content is not changed in the course of code implementation); Stored in program section memory. extern: Used to make reference to variables declared elsewhere, for example in another module. register: Used to store a variable in a processor s register; Promotes faster access to the contents of the variable; Only used locally and depends on the register s availability. static: Declared within a function or a program block; Preserves the variable even after a function or block has been executed. volatile: A statement using this descriptor informs the compiler that this variable should not be optimized.
Operators C supports a rich set of operators that allow to manipulate variables Assignment (=) changes the values of variables Arithmetic (+ - * / %) add, subtract, multiply, divide, module Bitwise (& ^ ~) AND, OR, XOR, NOT, and shifts on Integers Relational (==!= <) equality, inequality, less-than, etc. Logical (&&!) AND, OR, NOT on Booleans Increment/Decrement ( ++ --)
Order of Evaluation Precedence The order in which operators and expressions are evaluated Associativity The order which in which operators of the same precedence are evaluated Left to Right for +,, *, /, % Right to Left for some other operators Parentheses Override the evaluation rules
Data and Memory Organization
Primitive Numeric Data Types Data Type Size Range byte u8/s8 1 byte Integers in the range of -128 to +128 short u16/s16 2 bytes Integers in the range of -32,768 to +32,767 int u32/s32 4 bytes Integers in the range of -2,147,483,648 to +2,147,483,647 long u64/s64 8 bytes Integers in the range of - 9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 float float 4 bytes Floating-point numbers between ±3.4x10-38 to ±3.4x10 38 with 7 digits of accuracy double double 8 bytes Floating-point numbers between ±1.7x10-308 and ±1.7x10 308 with 15 digits of accuracy
Arrays Array declaration and usage double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; double balance[10]; balance [0] = 3,2: balance [1] = 3,12:.. balance [9] = 36,2:
Structures Structure fields Variable structure declaration Data assignment
Memory Organization (Physical) Embedded systems have memory constraints Memory allocation is very important Physical allocation: RAM (Data) Flash (Code) With exceptions! (some code can be stored in RAM and some Data can be stored in Flash)
Memory Segments In classical architectures there are five basic memory areas: DATA initialized global and static variables. BSS (Block Started by Symbol) uninitialized global and static variables. HEAP Dynamically allocated memory. (Malloc operations are not recommended in embedded software) STACK LIFO structure located in the higher parts of memory. Manage function calls and local variables of the functions. TEXT Code segment that contains executable instructions.
Memory Allocations int data_bss; int isize; int data_data=32; } BSS DATA SEGMENTS Stack PHYSICAL MEMORY RAM void main(void) { int a =2; char *p; } STACK Free Memory static int b; static int c=11; isize = 8; p = malloc(isize); } DATA HEAP (8 Bytes) Heap BSS Data RAM RAM FLASH/RAM } a=example(); Text FLASH
System Workbench for STM32
System Workbench System Workbench for STM32 (SW4STM32) is an Eclipse-based IDE. Eclipse + dedicated plugins (GCC, OpenOCD, OpenSTM32) It provides a complete and free development platform for STM32 MCUs. It integrates a complete code editor, compilation tools (compiler, assembler, linker ) and remote-debugging tools. Features STM32 Devices database and libraries Source code editor Linker script generator Building tools (GCC cross compiler, assembler, linker) Debugging tools (OpenOCD, GDB) Flash programing tools
Workspace In Eclipse, the Workspace is a folder containing different projects, which are conveniently grouped together. At startup you are asked where to create a workspace (by default in user/documents), You can easily switch between different workspaces: File -> Switch Workspace You can have a workspace for a certain MCU or board and keep there the related projects It s easy to have shared resources (e.g. libraries) for different projects in a workspace If you want a new workspace just switch to a new empty folder.
Workspace LAB PCs Local user data is erased at each logout, you have to take care to save and backup everything you do (e.g. copy files on USB memory). Every time you login, you will have to create a new workspace and there to create a new project or to import an existing project 1. Create a folder on the desktop as your new Workspace 2. Open SW4STM32 and set that folder as your Workspace
Workspace Personal PCs You can create a Workspace folder where you prefer, and you can use it throughout the course. You can create a new workspace whenever you want 1. Create a folder where you prefer 2. Open SW4STM32 and set that folder as your Workspace 3. At next startup you can select the same folder and you will have existing projects already there
firmware directory SW4STM32 provides libraries for the common ST development boards, including our board. When you create a new project you can specify a board and add the related libraries All needed libraries are downloaded the first time you try to use them By default SW4STM32 downloads and searches for libraries in the following (hidden) folder: C:\Users\<UserName>\AppData\Roaming\Ac6\SW4STM32\firmwares\
firmware directory LAB PCs no internet, default firmwares folder is not accessible we already downloaded the libraries in the folder C:\Ac6\firmwares\ You have to set SW4STM32 to search for the libraries in that folder: Go to: Window -> Preferences -> System Workbench -> Firmware Installation Click on New and select the folder C:\Ac6\firmwares\ Click on OK Personal PCs You can use the default firmware directory and download the libraries when needed.
Project creation You have different options to create a project: Use the wizard to create a new project Import existing project into workspace (from directory or zip) Copy existing project already in the workspace and rename it
Create a new project (1/5) File -> New -> C Project
Create a new project (2/5) Project and Toolchain Insert Project Name Use default location (creates a new project folder in the current workspace) Project Type: Executable -> Empty Project -> Ac6 STM32 MCU GCC Toolchains: Ac6 STM32 MCU GCC Next
Create a new project (3/5) Available configurations Leave as default Next
Create a new project (4/5) MCU Configuration Series: STM32F4 Board: STM32F4DISCOVERY Next Important to select the right MCU to use the correct memory and startup settings Selecting the wrong MCU the project will NOT work
Create a new project (5/5) Standard Peripheral Library (StdPeriph) LAB PCs: it should be already available, if not check the firmware directory (see here) Personal PCs: at first use download it Add low level drivers in the project As source in the application project This will copy the StdLib in your project directory PRO: no external dependencies, everything is in the project folder CON: StdLib copied in every project in the workspace NO additional drivers, NO utilities Finish
Import Existing Project File -> Import General -> Archive file (if you have a zip with the project to import) General -> Existing Project into Workspace (to import project from folder) Select root directory (or archive file) Copy project into workspace
Copy Project Useful to duplicate existing project Right-click on project folder -> Copy Right-click on project explorer -> Paste Rename Project
Project Structure Project folder StdPeriph library Utilities library Project include files Stm32f4xx_it.h Interrupt definition Header File Project source files main.c: main with your code syscalls.c System calls (stdio.h for embedded) system_stm32f4xx.c: system initialization (executed before main) Startup: the very first code executed by MCU and interrupt prototypes CMSIS library Linker Script
ST StdPeriph Library
Standard Peripheral Library The STM32F4xx standard peripherals library provides a complete register address mapping with all bits, bit-fields and registers declared in C. includes a collection of routines and data structures, covering all the MCU s internal peripherals functions and their drivers. The development of each driver is driven by a common API, which standardizes the driver structure, the functions and the parameter names. Moreover a set of examples are provided, covering all available peripherals with template projects for the most common development tools.
Standard Peripheral Library CMSIS Library developed by ARM to provide access to Cortex M CORE registers
Standard Peripheral Library StdPeriph Driver developed by ST to deliver high level functions to access peripherals (one file for each peripheral)
Standard Peripheral Library Utilities library developed by ST to provide useful functions to access external devices on the board (buttons, LEDs, etc )
Your First Project
Your First project Create new project Now you should have an empty new project Copy the provided main to your main.c: Go to course website For each Lab the needed files are provided Chose Lab1: main-lab1-01.c Select All > Copy-Paste into your main.c
Look at the code Include Microcontroller library and board library Function prototype Global variable Local variables Utility functions to init LEDs Find maximum in an array Turn on LED according to result Never exit from the Main!!!
Look at the code Function parameters Local variables Return result
Eclipse Interface 1. Save 2. Build (compile) 3. Debug (do not click now)
Eclipse Tips By default, you have to save your file before building it with the latest modification. To automatically save before build, go to Window > Preferences > General > Workspace and check Save automatically before build If you get reference not found errors even if you included the correct headers, rebuild the index: Project -> C/C++ Index -> Rebuild Suggested operations: 1. Modify code 2. Save all 3. Rebuild index 4. Compile 5. Debug
Eclipse Interface warnings Breakpoint (code execution during debug pauses here) Build Output Console
Eclipse View Perspectives Interface perspectives for developing code (as seen for now) and for debug Debug Interface Compile interface
Start Debugger Right click on project -> Debug as Ac6 STM32 C/C++ Application
Open Debug Perspective Click Allow access for Windows firewall Click Yes to open Debug Perspective (you can tick Remember my decision to automatically open debug perspective)
Debug Interface Start / pause code execution Stop / disconnect debugger Debug steps: - Step Into - Step Over - Step Out Debug status: Check green Play light
Debug Interface Mouse over a variable name to check its value Current debugger location Breakpoints (code execution pauses here)
Variables monitoring
IDE Troubleshooting To debug a project: Right click project name -> Debug As ->AC6 STM32 C/C++ When you stop the debug session always REMOVE the session using Terminate If you have errors that should not be present try: Right Click Project Name -> Index ->Rebuild Always remove errors related to some strange EABI++ not found (IDE bug) If you cannot start the debugger: Check that the board is connected and you have RED or GREEN Led on then one of the following: If you have red and green led blinking, you have another debug session active, terminate it and restart If Red and Green led are both on (orange light) there is a communication error, disconnect and reconnect the board Go to Task Manager and terminate openocd process
Practice with debug Try to debug code on the board Monitor variables Check debug steps buttons Is everything working correctly? Do the functions works properly? Are the results correct?
Weekly assignments
WEEKLY assignments Every week we will give you some assignments Assignments have exercises and questions We provide you a main.c with the code used for explanation and the exercises will asks you to modify it There may be additional questions related to the lab lesson. Every group has to complete the assignments and to send them via email before the next lab One email per group to Bojan and Simone Subject (mandatory!): LABARCH2017 Group XX Lab XX For each exercise prepare one main.c file (and comment your code!) Attach file with replies to questions (txt, doc or.pdf)
Exercise: 1. Add a function that finds the index of a given value in a provided array: Input: array, value to find Output: index of value in array, (-1 if not present, if there are multiple values it return the first one) 2. Create a function to verify if a given string is a PALINDROME (e.g. AVALLAVA, OTTETTO) 1. Input: string (or array of chars, test the differences) 2. Output: 1 = palindrome, 0 = not palindrome