This simple guide is for anyone interested in learning how to program in assembly language on the Raspberry Pi. When you've read the guide you'll be able to write Hello World to the Raspberry Pi screen in assembly language. The guide doesn’t presume any knowledge of programming in assembly language and at the end will give further links to explore this subject more deeply.
What is Assembly Language?
Assembly language is a low-level programming language; it is very similar to the machine code that a computer uses but it uses words instead of ones and zeroes for commands. A computer cannot understand assembly language directly so it uses an assembler to take the program and convert it into binary code.
Here’s an example of assembly language code:
MOV AL,' ' CLD REP STOSB AND AL,0DFH CMP AL,41H JGE CKVER JMP EXITSPC
As you can see, assembly language is a lot more difficult for a human to understand than a high level programming language such as C, Python or PHP.
Benefits and drawbacks
The benefit of assembly language is that the code runs really fast as the programmer can make the CPU do exactly what they want. The drawback of assembly language is a lot of code is needed: hundreds of lines of instructions are needed to run a program that would take a single high level program command.
The Raspberry Pi runs on 32 bit ARM architecture so we will be developing using the ARM assembly language. We will need an assembler to assemble the assembly code into machine code on the Raspberry Pi. The assembler we’ll be using is the GNU assembler which comes preinstalled with the Raspbian distribution. You can check that you have it on your system by typing:
We don't need any special code editor or IDE to develop with. In this tutorial, I’ll use ```nano but you can use whichever text editor you want.
Create a file called test.s and write the contents shown below. Save it.
@ @ Print Hello world @ .text .global _start _start: mov r7,#4 @ write system call mov r0,#1 @ file (stdout) ldr r1,=message mov r2,#14 @ message length svc #0 mov r7,#1 @ exit system call mov r0,#0 @ return code svc #0 .data message: .ascii "Hello, world!\n"
Note: Anything after the @ sign is a comment which should help you understand the code a little more.
There are two steps to creating a binary file from an assembly language file. First we need to create an object file and then we need to link it and create an executable which we can run.
To compile the assembly language file and create an object file, type in the following command:
as -o test.o test.s
Next, to link the file and create an executable, type in the following code:
ld -o test test.o
You will now have an executable program that you can run by typing:
Congratulations, you've created your first assembly language program.
For further tutorials about using assembly language on the Raspberry Pi, take a look at the following links: