API: HAL

A hardware abstraction layer (HAL) is a conceptual interface between the user and hardware. The definition sounds very similar to API, and that’s because HAL is a specific form of API that hides away hardware details. Recall the TV remote analogy used in the introduction. In a sense, this is a form of HAL: you know that each button does something (like changing the channel or adjusting the volume), but how each button actually does its functions (through transmitting a signal to the TV and decoding it) is totally obscured from you.


To apply it to our purposes, suppose you wanted to turn on LED 1 on the Launchpad. Assume that LED 1 has already been configured as an output. Using DriverLib, we can do the following:

GPIO_setOutputHighOnPin(GPIO_PORT_P1, GPIO_PIN0);

This, however, is not a form of HAL. If we encapsulate that into a function, however, it would be considered HAL.

TurnOn_Launchpad_LED1();

Where the function definition is:

void TurnOn_Launchpad_LED1()

{

    GPIO_setOutputHighOnPin(GPIO_PORT_P1, GPIO_PIN0);

}

At this point, it seems redundant to do so. However, using functions to develop a HAL provides us with a unique advantage: portability.


In programming, portability refers to how easily you can export code to a different architecture. To put it into context, suppose Texas Instruments develop a brand new Launchpad, with an overhauled architecture from the one we are currently using. With this new Launchpad, LED 1 is now mapped to Port 4, Pin 3. If we tried exporting the following code to this new Launchpad:

GPIO_setOutputHighOnPin(GPIO_PORT_P1, GPIO_PIN0);

We would not get the intended results. Of course, a simple fix for this is to change the parameters to match the specifications of this new Launchpad. However, what if this function appears multiple times throughout the code? You would have to scout out every single instance of that function and replace the parameters, making the code not very portable. Contrast that with exporting this code:

TurnOn_Launchpad_LED1();

To make this code compatible with the new hardware, all you would have to do is change the function declaration as such:

void TurnOn_Launchpad_LED1()

{

    GPIO_setOutputHighOnPin(GPIO_PORT_P4, GPIO_PIN3);

}

This code is very portable, as a result. Minimal changes are needed in order to make the code work for a new hardware.


As a concept, HAL strives to keep functions high-level so that another person using the code can understand the very basics of how it all works. Developing a HAL for coding projects is highly encouraged as it helps keep your code readable and easy to debug and fix. While HAL isn’t necessary to make a project work, developing a HAL is good coding style. Keep in mind that many practical coding projects require collaboration between several programmers. The easier your code is to understand and use, the smoother the project will run and the fewer frustrated collaborators you’ll have.