Skip to content

PRO TIP Block youtube.com at the DNS level — Pi-hole, NextDNS or your hosts file — but allow youtube-nocookie.com and i.ytimg.com. These tutorials keep playing; the rabbit hole does not.

Learning without distractions

#8 Functions in C and the call stack

109.8K views on YouTube

Embedded Systems Programming Lesson-8 introduces you to functions and the call stack. You will learn what a function is, how to declare it with a function prototype, how to define it, and how to call it.

The lesson starts with an observation that the blinky code written so far repeats the delay loop in two places. Such code violates the DRY (Don’t Repeat Yourself) programming principle and should be avoided.

Next, you see how to turn a piece of code into a function and then call this function as many times as needed instead of repeating the code verbatim.

Next, you inspect the machine code and see that the function is called by means of the BL (Branch with Link) instruction, which stores the return address in the Link Register (LR).

In the function body, you see that the local variable ‘counter’ is allocated in a special memory region called the stack. You learn about the Stack Pointer (SP) register and you learn how the stack can grow and shrink.

Next, you see how a function returns by means of the BX (Branch and Exchange) instruction. You learn about the THUMB-mode bit in the return code and you see what happens when the THUMB-bit is absent.

Next, you learn how to add an argument to the delay function, to allow you to change the delay at every invocation. You see how the function prototype ensures that every call provides the argument.

Finally, you step down to disassembly and you see that the argument is passed in the R0 register.

The next lesson will explain more about the stack and functions calling other functions, including functions calling themselves recursively. You will also learn more about function arguments as well as the non-void return types. Finally, at the low level, you will learn about the ARM Procedure Call Standard.

Stay tuned…

——
Resources:

Companion web page for this video course:
https://www.state-machine.com/quickstart

GitHub repository for projects for this video course:
https://github.com/QuantumLeaps/modern-embedded-programming-course

Transcript of this lesson:
https://www.state-machine.com/course/lesson8.txt

Music credits:
The opening/closing background music comes from:
FreePlay Music, Motivation Vol 1, 2001, “Can Do”
https://freeplaymusic.com/#/music/23187