Book Image

ARM® Cortex® M4 Cookbook

By : Mark Fisher, Dr. Mark Fisher
Book Image

ARM® Cortex® M4 Cookbook

By: Mark Fisher, Dr. Mark Fisher

Overview of this book

Embedded microcontrollers are at the core of many everyday electronic devices. Electronic automotive systems rely on these devices for engine management, anti-lock brakes, in car entertainment, automatic transmission, active suspension, satellite navigation, etc. The so-called internet of things drives the market for such technology, so much so that embedded cores now represent 90% of all processor’s sold. The ARM Cortex-M4 is one of the most powerful microcontrollers on the market and includes a floating point unit (FPU) which enables it to address applications. The ARM Cortex-M4 Microcontroller Cookbook provides a practical introduction to programming an embedded microcontroller architecture. This book attempts to address this through a series of recipes that develop embedded applications targeting the ARM-Cortex M4 device family. The recipes in this book have all been tested using the Keil MCBSTM32F400 board. This board includes a small graphic LCD touchscreen (320x240 pixels) that can be used to create a variety of 2D gaming applications. These motivate a younger audience and are used throughout the book to illustrate particular hardware peripherals and software concepts. C language is used predominantly throughout but one chapter is devoted to recipes involving assembly language. Programs are mostly written using ARM’s free microcontroller development kit (MDK) but for those looking for open source development environments the book also shows how to configure the ARM-GNU toolchain. Some of the recipes described in the book are the basis for laboratories and assignments undertaken by undergraduates.
Table of Contents (16 chapters)
ARM Cortex M4 Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Writing a simple program


This section explains how to write, build, and execute a simple program. We also describe the various files that, together, make up a uVision project.

How to do it…

  1. Use Windows Explorer to create a new (empty) folder called helloBlinky_c1v0. Invoke uVision5, and create a new project (ProjectNew uVision Project…). Navigate to the folder, and create a project file called hello_blinky.uvprojx. When prompted, choose the STM32F407IGHx device. Click OK.

  2. In ManageRun Time Environment, choose the MCB32F400 board support using the drop-down list, and tick the LED API (since our application will flash an LED). Expand the Device option list, and tick Startup and Classic.

  3. Notice that the Validation Output pane display warns us that, to drive LEDs, we also need CMSIS core, GPIO driver, and system start-up components. Press the Resolve button to automatically include any libraries needed by the board features selected, then click OK. The project window in uVision5 should show that the files have been successfully loaded. The names of the folders can be changed using a right-click menu, and fields can be expanded to show individual components, thereby allowing the file components to be edited. Note: Some library files are read-only.

  4. Right-click Source Group 1, and select Add New Item to Group 'Source Group 1'…; then select a C File (.c) template. Name the file hello_Blinky.c, and enter the following program:

    /*------------------------------------------------
     * Recipe:  helloBlinky_c1v0
     * Name:    hello_blinky.c
     * Purpose: Very Simple MCBSTM32F400 LED Flasher
     *------------------------------------------------
     * 
     * Modification History
     * 16.01.14 Created
     * 27.11.15 Updated 
     * (uVision5 v5.17STM32F4xx_DFP2.6.0)
     *
     * Dr Mark Fisher, CMP, UEA, Norwich, UK
     *------------------------------------------------*/
    #include "stm32f4xx_hal.h"
    #include "Board_LED.h"
    
    int main (void) {
      const unsigned int num = 0;
      unsigned int i;
    
      LED_Initialize();    /* LED Initialization */
    
      for (;;) {                      /* Loop forever */
    	 LED_On (num);        /* Turn specified LED on */	
        for (i = 0; i < 10000000; i++)
    	/* empty statement */ ;       /* Wait */
    	  LED_Off (num);     /* Turn specified LED off */
        for (i = 0; i < 10000000; i++)
    	/* empty statement */ ;       /* Wait */			
      } /* end for */
    }
  5. The RTE manager of uVision5 will have configured the device options with values from the device database, but the debug options should be reviewed by selecting ProjectOptions for Target 'MCBSTMF400'… to ensure that they specify the ULINK2/ME Cortex Debugger.

  6. Build the project by selecting ProjectRebuild all Target Files. Again, there is a toolbar icon that provides a helpful shortcut.

  7. Write the executable code to the microcontroller's flash memory using FlashDownload. Press the RESET button on the evaluation board to run the program.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How it works…

Those familiar with uVision4 will notice that the most obvious feature for of this program is that a call to SystemInit() is missing, as this code is executed before main() is called. The function called main() is the entry point for our program, and each project should declare only one file that defines a main function. Conventionally, this might be called main.c, or adopt a file name that is shared by the project such as helloBlinky.c.

Tip

Most of the file helloBlinky.c comprises comments, which are highlighted in green. Comments do not produce any executable code, but they are essential for understanding the program. You may be tempted to omit comments, but you will appreciate their value if, at some later date, you need to reuse code written by others, or even yourself.

The source code file begins with a large comment statement that extends over several lines and contains information about the program. Then there are C pre-processor directives; we discuss these in Chapter 2, C Language Programming. The program comprises a main function that declares two variables named i and num. There follows a function call to LED_Initialize() (written by developers) that sets up the GPIO peripheral which drives the LEDs. The program contains three so called for loops. The outer loop, is known as a superloop and never terminates. These statements within this loop are executed again and again, forever (well for as long as power is supplied to the evaluation board). The statements within the loop turn the specified LED ON and OFF by calling yet another function written by Keil developers. The other two for loops, nested within the superloop, simply waste time by incrementing the loop variable i. Implementing a delay in this way represents a very naïve approach, and we'll explore much more efficient techniques later. If you have not programmed in C before, then although you'll probably appreciate that this program is very compact, you may find it confusing. Don't worry, we'll revisit this program again when we introduce the C programming language in Chapter 2, C Language Programming.

There's more…

The structure of the uVision MDK projects has evolved considerably over the past few years and uVision5 represents a significant revision in this respect. Developers of uVision5 have attempted to make microcontroller software development much simpler by providing library functions that can be used to control peripherals such as LEDs, accelerometers, touchscreen, and so on. Many application developers migrating from uVision4 find this burdensome, and favor more classic approaches that do not rely on intrinsic interface functions. Application programmers who wish to use their own middleware functions are advised to download the ARMs MDK legacy support pack (http://www2.keil.com/mdk5/legacy). The source files that, together with the project options, define the helloBlinky project are summarized in the following table:

File Type

File extension

Description

C File

.c

Source code written in ANSI C.

Header File

.h

File containing additional information to be included in the source code

Assembly Language File

.s

Source code written in ARMs Thumb2 assembly language (Cortex-M cores)

Text File

.txt

Text file, usually containing description of the project or instructions for running the code.

A configuration wizard is provided to customize some files (for example, startup_stm32F40xx.s). However, we will deal with these more advanced aspects in subsequent chapters. Further, library and header file components, declared within the source files themselves, are also listed in the project window, and can be opened in the editor window. The file types you will encounter are described briefly in the following table, but will be discussed in more detail in Chapter 2, C Language Programming.

File Type

File extension

Description

C File

.c

Source code written in ANSI C.

Header File

.h

File containing additional information to be included in the source code

Assembly Language File

.s

Source code written in ARMs Thumb2 assembly language (Cortex-M cores)

Text File

.txt

Text file, usually containing description of the project or instructions for running the code.

The project options are functionally grouped together. They are accessed through the tabs within the Project Options menu, and summarized in the following table. Further details are available in the uVision User Guide.

Tab

Description

Device

Select the microcontroller device from the database

Target

Specify hardware parameters

Output

Define output files of the tool chain

Listing

Specify all listing files generated by the tool chain

User

Specify user programs executed before compilation / build

C/C++

Set C / C++ compiler-specific tool options

Asm

Set assembler-specific tool options such as macro processing

Linker

Set linker-related options, and define physical memory parameters.

Debug

Specify settings for the uVision debugger

Utilities

Configure utilities for flash programming

The options allow the developer to control quite small details of the build—for example, you might find it more convenient to execute code as soon as it is downloaded to the target by configuring the flash programming settings using the utilities tab as shown in the following image:

The STM32F400IGHx microcontroller implements 1MB On-chip Flash memory. RAM for Algorithm defines the address space used by the programming algorithm for the device.