Saturday, September 10, 2016

Cutting Through the Confusion with ARM Cortex-M Interrupt Priorities

The insanely popular ARM Cortex-M processor offers very versatile interrupt priority management, but unfortunately, the multiple priority numbering conventions used in managing the interrupt priorities are often counter-intuitive, inconsistent, and confusing, which can lead to bugs. In this post I attempt to explain the subject and cut through the confusion.
The Inverse Relationship Between Priority Numbers and Urgency of the Interrupts
The most important fact to know is that ARM Cortex-M uses the “reversed” priority numbering scheme for interrupts, where priority zero corresponds to the highest urgency interrupt and higher numerical values of priority correspond to lower urgency. This numbering scheme poses a constant threat of confusion, because any use of the terms “higher priority” or “lower priority” immediately requires clarification, whether they represent the numerical value of priority, or perhaps, the urgency of an interrupt.
NOTE: To avoid this confusion, in the rest of this post, the term “priority” means the numerical value of interrupt priority in the ARM Cortex-M convention. The term “urgency” means the capability of an interrupt to preempt other interrupts. A higher-urgency interrupt (lower priority number) can preempt a lower-urgency interrupt (higher priority number).
 Interrupt Priority Configuration Registers in the NVIC
The number of priority levels in the ARM Cortex-M core is configurable, meaning that various silicon vendors can implement different number of priority bits in their chips. However, there is a minimum number of interrupt priority bits that need to be implemented, which is 2 bits in ARM Cortex-M0/M0+ and 3 bits in ARM Cortex-M3/M4.
But here again, the most confusing fact is that the priority bits are implemented in the most-significant bits of the priority configuration registers in the NVIC (Nested Vectored Interrupt Controller). The following figure illustrates the bit assignment in a priority configuration register for 3-bit implementation (part A), such as TI Tiva MCUs, and 4-bit implementation (part B), such as the NXP LPC17xx ARM Cortex-M3 MCUs.
 Interrupt priory registers with 3 bits of priority (A), and 4 bits of priority (B)
Interrupt priory registers with 3 bits of priority (A), and 4 bits of priority (B)
The relevance of the bit representation in the NVIC priority register is that this creates another priority numbering scheme, in which the numerical value of the priority is shifted to the left by the number of unimplemented priority bits. If you ever write directly to the priority registers in the NVIC, you must remember to use this convention.
NOTE: The interrupt priorities don't need to be uniquely assigned, so it is perfectly legal to assign the same interrupt priority to many interrupts in the system. That means that your application can service many more interrupts than the number of interrupt priority levels.
NOTE: Out of reset, all interrupts and exceptions with configurable priority have the same default priority of zero. This priority number represents the highest-possible interrupt urgency.


The Cortex Microcontroller Software Interface Standard (CMSIS) provided by ARM Ltd. is the recommended way of programming Cortex-M microcontrollers in a portable way. The CMSIS standard provides the function NVIC_SetPriority(IRQn, priority) for setting the interrupts priorities.
However, it is very important to note that the 'priority' argument of this function must not be shifted by the number of unimplemented bits, because the function performs the shifting by (8 - __NVIC_PRIO_BITS) internally, before writing the value to the appropriate priority configuration register in the NVIC. The number of implemented priority bits __NVIC_PRIO_BITS is defined in CMSIS for each ARM Cortex-M device.
For example, calling NVIC_SetPriority(7, 6) will set the priority configuration register corresponding to IRQ#7 to 1100,0000 binary on ARM Cortex-M with 3-bits of interrupt priority and it will set the same register to 0110,0000 binary on ARM Cortex-M with 4-bits of priority.
NOTE: The confusion about the priority numbering scheme used in the NVIC_SetPriority() is further promulgated by various code examples on the Internet and even in reputable books. For example the book “The Definitive Guide to ARM Cortex-M3, Second Edition”, ISBN 979-0-12-382091-4, Section 8.3 on page 138 includes a call NVIC_SetPriority(7, 0xC0) with the intent to set priority of IR#7 to 6. This call is incorrect and at least in CMSIS version 3.x will set the priority of IR#7 to zero.


The interrupt priority registers for each interrupt is further divided into two parts. The upper part (most-significant bits) is the preempt priority, and the lower part (least-significant bits) is the subpriority. The number of bits in each part of the priority registers is configurable via the Application Interrupt and Reset Control Register (AIRC, at address 0xE000ED0C).
The preempt priority level defines whether an interrupt can be serviced when the processor is already running another interrupt handler. In other words, preempt priority determines if one interrupt can preempt another.
The subpriority level value is used only when two exceptions with the same preempt priority level are pending (because interrupts are disabled, for example). When the interrupts are re-enabled, the exception with the lower subpriority (higher urgency) will be handled first.
In most applications, I would highly recommended to assign all the interrupt priority bits to the preempt priority group, leaving no priority bits as subpriority bits, which is the default setting out of reset. Any other configuration complicates the otherwise direct relationship between the interrupt priority number and interrupt urgency.
NOTE: Some third-party code libraries (e.g., the STM32 driver library) change the priority grouping configuration to non-standard. Therefore, it is highly recommended to explicitly re-set the priority grouping to the default by calling the CMSIS function NVIC_SetPriorityGrouping(0U) after initializing such external libraries.


Often in real-time embedded programming it is necessary to perform certain operations atomically to prevent data corruption.  The simplest way to achieve the atomicity is to briefly disable and re-enabe interrupts.
The ARM Cortex-M offers two methods of disabling and re-enabling interrupts. The simplest method is to set and clear the interrupt bit in the PRIMASK register. Specifically, disabling interrupts can be achieved with the “CPSID i” instruction and enabling interrupts with the “CPSIE i” instruction. This method is simple and fast, but it disables all interrupt levels indiscriminately. This is the only method available in the ARMv6-M architecture (Cortex-M0/M0+).
However, the more advanced ARMv7-M (Cortex-M3/M4/M4F) provides additionally the BASEPRI special register, which allows you to disable interrupts more selectively. Specifically, you can disable interrupts only with urgency lower than a certain level and leave the higher-urgency interrupts not disabled at all. (This feature is sometimes called "zero interrupt latency".)
NOTE: The BASEPRI register cannot disable interrupt priority 0 (highest urgency). In fact, writing 0 into BASEPRI re-enables all interrupt priority levels.
The CMSIS provides the function __set_BASEPRI(priority) for changing the value of the BASEPRI register. The function uses the hardware convention for the 'priority' argument, which means that the priority must be shifted left by the number of unimplemented bits (8 - __NVIC_PRIO_BITS).
NOTE: The priority numbering convention used in __set_BASEPRI(priority) is thus different than in the NVIC_SetPriority(priority) function, which expects the “priority” argument not shifted.

A few uses for an autonomous vehicle

From the time technology that we have come to know was invented, it has been used to gain an advantage militarily or to make life easier. Military usage seems to be a driving factor, but it is not the only factor.
Guerilla tactics played an even greater part in the US conflict in Iraq and Afghanistan. Using lessons learned fighting the Soviets in the 1980s and training from US backed anti-Soviet forces, the guerilla tactics did increasing damage to US military forces. Insurgents could build an IED from unexploded ordnance they recovered and use a cell phone to remotely detonate the device. These were particularly effective against the flat-bottom of the High Mobility Multipurpose Wheeled Vehicle (HMMWV or Humvee) in use at the time. New vehicle were developed, like the Mine-Resistant Ambush Protected (MRAP) vehicle. It has an angled bottom to help deflect the blast force away from the passengers. (Cougar, n.d.)
The most limiting factor for an airplane is the human pilot. The human body can only withstand so many G-forces before the pilot loses consciousness. A computer is not limited by those same forces.

Currently, research and field trials are being conducted on unmanned and autonomous vehicles. Autonomous vehicles can be programmed to follow a route or make decisions based on data from sensors. There are many reasons to use these vehicles on the battlefield. Unmanned aerial vehicles (UAV) can circle far above an area, unobserved, for as long as their fuel lasts, while sending live video feed back to the command center. Unlike manned aircraft, a UAV doesn’t place a human life at risk in the event of detection and counterattack. A small UAV could be carried on a backpack and used with an infrared camera or video camera to gain intelligence in a similar manner to the Civil War balloons. Pilots for larger drones, like the Predator, can fly from the other side of the world using satellites to carry the signal. (How, n.d.)
An unmanned ground vehicle (UGV), like the Recon Robotics ThrowBot could be quietly driven to a spot or even thrown through a window and provide a live feed so a plan could be developed to reduce human casualties. Some Police and Special Weapons and Tactics units are also making use of the Throwbot. Small vehicles like the iRobot PackBot can be carried and deployed to gain intelligence or deactivate Improvised Explosive Devices (IED). Some soldiers have been using radio controlled hobby vehicles to scout for IEDs ahead of their vehicle patrols. One vehicle found its fifth and final IED when “…the little truck was vaporized when it managed to set off a 500 pound IED that might have otherwise been triggered by the Humvee itself…” (Ackerman, 2011, para. 2)
In an effort to remove humans completely from danger, the Defense Advanced Research Projects Agency (DARPA) has sponsored competitions to develop autonomous, self-driving vehicles. The first competition placed vehicles in a desert environment. Another competition place the vehicles in an urban environment with other autonomous vehicles and human traffic. Autonomous convoys could deliver supplies through dangerous areas eliminating that risk to humans and freeing them for other uses.
The field of Search and Rescue (SAR) is a field ready for autonomous vehicles. When a building collapses, there is no room for humans to fit through the wreckage, or it could be too unstable. A small autonomous vehicle could fit through small openings to search for survivors and is expendable if it is lost. Unlike humans, autonomous vehicles don't suffer from long-term health conditions from exposure to asbestos dust or other dust from a collapsed building. Vehicles equipped with sensors could relay information about temperature and possible chemical leaks.
An aerial vehicle could be equipped with a Forward Looking Infrared Camera (FLIR) to help locate a lost person outside, but would be limited by overhead trees. An underwater vehicle could search rivers and lakes at deeper depths and for longer periods of time than a diver could.
An aerial vehicle could fly over flood waters and drop needed supplies to stranded people. They could be used in Third World countries to air-drop medical supplies to remote villages.
At the home, robotic vacuum cleaners could keep the floor clean. Robotic lawn mowers can keep the grass cut and snow plowing vehicles could keep the sidewalk clear.
For all the advantages of unmanned vehicles, there are many disadvantages. Humans still retain the final decision to fire weapons, so how many levels that decision has to travel, could make it a disadvantage. To avoid confusion, a clear chain of command must be established and maintained. 
Man-portable devices are limited in size and dependent on how many replacement batteries are carried. Larger systems require more logistical support. UAVs are dependent on fuel to stay in the air.
In Vietnam and other areas of the world, even parts of the US, the jungle canopy provides a barrier that helps to conceal movement from aerial vehicles. This can be mitigated to some extent by infrared cameras that detect differences in heat between an object and the surrounding environment.
Live-feed video is a remarkable surveillance tool when used properly. Improper use can lead to “battlefield micromanagement”. “More and more frequently, generals insert themselves into situations inappropriately, and their command leadership role becomes command interference.” (Singer, n.d., pg. 80)
“While this general was doing a job normally entrusted to junior officers, who was doing his job? New technologies allow him and other senior flags to make tactical decisions as never before. But the captains, majors, colonels, and so forth, whom they cut out of the chain, cannot, in turn, assume responsibility for the strategic and policy questions that the generals would have wrestled with instead.” (Singer, n.d., pg. 81)
Those officers in the field may not gain the decision making experience they will need when they are promoted to higher ranks. This lack of experience could cause a significant problem as senior leadership retires.
One concern with the use of unmanned vehicles is that, without human lives being at stake, more wars will be fought because the machines can be more easily replaced. The only way to prevent this would be adherence to strict international policy.
Another advantage and disadvantage is that the opposing force will not be able to directly attack the stronger force, leading to a rise in asymmetric warfare. Guerilla tactics, like ambushes and IEDs, could become more prevalent. New technologies, like autonomous vehicles, will be developed to counteract this. This could result in an arms and tactics race between the two forces.
With the rise in guerilla warfare and unknown terrorist cells, DARPA’s Improv Program has asked industry and skilled hobbyists for submissions for new ways technology could place assets at risk. 

Choosing a Microcontroller for Your Vehicle

There are many things to take into consideration when choosing a microcontroller or microprocessor for your autonomous vehicle.

Some processors run on 5V and others use 3.3V.  Be sure to check the documentation before you buy.  Make sure your supply has a high enough amp rating that your microcontroller doesn't lose pwer.

Can the system run using batteries?  Large, automotive sized vehicles can be run from large batteries or inverters in the vehicle.  Smaller vehicle power supplies must be scaled down in order for the vehicle to be able to move.  Regular AC power must be plugged into a wall and would be limited by the length of the wire.
If you are building one item, price may not be a big concern.  If you are designing for production, every penny counts.  
Storage / Memory
Larger programs take more space to store and to run.  Microcontrollers typically do not have the storage space and vast amounts of memory that a microprocessor would normally have.  Programs must be smaller and should be more efficient.
Some older chips are no longer widely available, and can be expensive when they are found.  This can be a major consideration if you are designing something for production.
Many inexpensive microcontrollers are 8 bit, but prices for 32-bit controllers are getting lower.  For a basic vehicle, like a line-follower or simple obstacle avoider, an 8-bit microcontroller like the Arduino Uno is sufficient.  If you are going to have many sensors and motors or servos or vision processing, a 32-bit microcontroller with a Real Time Operating System (RTOS) would be a better choice.
Input and Output
When you choose a microcontroller, you must count the number of inputs and outputs that are required for the project and choose the microcontroller accordingly.  Something to keep in mind while doing that is the possibility of future expansion.
You must also count types of inputs and outputs, like pulse width modulation for motors and serial pins.

The following is a list of microcontrollers that I own, most were purchased when a couple nearby Radio Shack stores closed down.  It is by no means a complete list - each company has different models and each model could have variations.

GM Engine Control Computer for 1991 Chevrolet S10
This is a factory engine control module from a 1991 Chevrolet S10.  Its purpose is to control the fuel injectors and read sensor data inputs.  Because of its environment, it is housed in an aluminum case.

8088 Single Board Computer
It is no longer necessary to build a Single Board Computer (SBC), like this Intel 8088 model, in order to control an autonomous vehicle.  This particular model, built for the Microcontroller classes I took, is limited by size and power requirements.  The original project was just the board, but I had to transport mine back and forth from class, so I thought a case would be better.  The power supply is from a full-sized computer.  It communicates with the "host computer" via a 9-pin serial cable.

Parallax Basic Stamp
There are a few kits and vehicles based on this chip and form factor available from retailers.

Parallax Propeller
The Propeller has 8 cores.

Texas Instrument MSP430 Launchpad Value Line Development Kit
There are different boards and chips available that have different amounts of memory and Input and Output pins.
I haven't used this board much.  So far, the problem I have with this board is that there are no holes for mounting it to something.

Arduino Uno
This board has been called the "Basic Stamp Killer".  It is widely available and easy to work with.
There are many kits and add-on boards available for this non-standard pitch form factor.
If you use the 10mm standoffs available at Radio Shack, you will have to file notches or chuck the standoff in a lathe and turn it down in order for them to fit.

Arduino AtMega2560

This board has many more Input and Output pins than the Uno.

10mm Radio Shack standoffs must be modified for this one, too.

Intel 8051
If you want to use a microcontroller dating from around 1980, that is still being used, there is the Intel 8051.  The chips above were produced by Atmel.

The boards above are typically small and have a limited number of pins available.  This can be a problem sometimes.
If you need more processing power and an RTOS, there are other boards you can use.  These include the Arduino Yun, BeagleBone Black, Raspberry Pi, and Intel Galileo, for example.

BeagleBone Black

I just got this board a few days ago, and haven't used it much yet.
One of the 10mm Radio Shack standoffs must be modified a little in order for it to fit properly for this one, too.

Raspberry Pi

I have used this board connected to a television with an RCA plug.  You can connect a mouse, keyboard, network cable, and either HDMI or RCA monitor.  It runs Linux from an SD card.

What are some other things to keep in mind?