Skip to content

Assembly Programming on Arduino ​

In Experiments 1 and 2 you wrote assembly for an ARM processor; in Experiment 3 you wrote C for the Arduino. This experiment joins the two. You write small AVR assembly functions for the Mega's ATmega2560, call them from an ordinary sketch, and control pins through the port registers that pinMode() and digitalWrite() use underneath.

Objectives ​

  • Find the port and bit behind an Arduino pin, and set it up with the DDRx, PORTx and PINx registers.
  • Write an assembly function in a .S file and call it from a sketch.
  • Pass a value from C to assembly in r24, and branch on it.
  • Turn pins on and off with sbi and cbi, and read a button with sbis.

Before the lab

Finish Experiment 3. You need binary and hex: bit 7 of a byte is 0b10000000, which is 0x80.

Background ​

Registers and address spaces ​

The ATmega2560 is an 8-bit processor. It works on 32 general registers, r0 to r31, each 8 bits wide. Like ARM, it only does arithmetic in registers, and memory is reached with load and store instructions. Unlike ARM, the result of add r24, r22 goes back into the first register, r24.

Everything the processor can read or write has an address in one data space:

Data addressHolds
0x0000–0x001FThe 32 registers r0–r31
0x0020–0x005FThe 64 I/O registers: ports A–G, timers, status
0x0060–0x01FFExtended I/O: ports H–L and the other peripherals
0x0200–0x21FF8 KB of SRAM for variables

The 64 I/O registers can also be reached through a short I/O address, 0x20 lower than the data address, with the fast instructions in, out, sbi and cbi. DDRB is data address 0x24 but I/O address 0x04. The line #define __SFR_OFFSET 0 at the top of each program makes names such as DDRB mean the I/O address, which is what those instructions expect.

Port registers ​

The Mega's pins are grouped into ports of 8, named A to L. Each Arduino pin is one bit of one port; the Mega pinout labels them, as PA0 for port A bit 0. The pins this experiment uses:

Arduino pinPort bit
4PG5: port G, bit 5
13, the on-board LED LPB7: port B, bit 7
22, 23, 24 … 29PA0, PA1, PA2 … PA7: port A, bits 0–7

Port A is convenient: its 8 bits are 8 neighbouring header pins, and pin 22 + n is bit n.

Three registers control each port x, one bit per pin:

RegisterBit = 1Bit = 0
DDRx (data direction)OutputInput
PORTx, output pinDrive HIGHDrive LOW
PORTx, input pinInternal pull-up onPull-up off
PINx (read only)Pin reads HIGHPin reads LOW

So pin 13 as an output, driven HIGH, is bit 7 of DDRB set and bit 7 of PORTB set: what pinMode(13, OUTPUT) and digitalWrite(13, HIGH) do for you.

Addressing modes ​

The addressing mode is how an instruction finds its operand. The ones you meet on the AVR:

ModeExampleEffect
Registerinc r24r24 ← r24 + 1
Two registersadd r24, r22r24 ← r24 + r22
Immediateldi r18, 0xFFr18 ← 0xFF. Only r16–r31.
I/O directout DDRA, r18
in r24, PINA
Copy a register to an I/O register, or back. I/O address 0–63.
I/O bitsbi PORTB, 7Set or clear one bit of an I/O register. I/O address 0–31 only.
Data directlds r24, 0x0200r24 ← the byte at data address 0x0200. sts stores.
Indirectld r24, Xr24 ← the byte at the address held in X (r27:r26). Also Y and Z.
Indirect, post-incrementld r24, X+The same, then X ← X + 1: steps through an array.

X, Y and Z are the register pairs r27:r26, r29:r28 and r31:r30, used together as 16-bit addresses.

Ports H to L are out of reach

Ports A–G sit at I/O addresses below 32, so sbi, cbi and sbis work on them. Ports H–L are extended I/O and need lds and sts. That rules out pins 6–9, among others; this experiment uses only pins on ports A, B and G.

Calling assembly from a sketch ​

A sketch with assembly in it has two files in one folder: the usual .ino, and a .S file with the assembly. The .ino declares the assembly functions inside extern "C" and calls them like any other function:

cpp
extern "C" {
  void start();         // written in asm.S
  void led(byte on);
}

The .S file marks each function .global, so the .ino can find it, and starts it with a label of the same name. Each function ends with ret, which returns to the line after the call. Comments start with ;.

The C compiler and your assembly share the registers, so follow its rules:

RegisterRule
r24Holds the first byte argument when the function starts. A byte result goes back in r24.
r18–r27, r30, r31Free to use.
r1Leave alone: C expects it to be 0.
r2–r17, r28, r29Belong to the caller. Save them with push and restore with pop if you use them.

The instructions used here ​

InstructionEffect
sbi P, bSet bit b of I/O register P to 1
cbi P, bClear bit b of I/O register P to 0
sbis P, bSkip the next instruction if bit b of P is 1
sbic P, bSkip the next instruction if bit b of P is 0
ldi r, KLoad the constant K into r (r16–r31)
out P, r / in r, PCopy a whole byte to or from I/O register P
cpi r, KCompare r with the constant K, setting the flags (r16–r31)
breq label / brne labelBranch if the last compare was equal / not equal
rjmp labelJump
retReturn from the function

sbi DDRB, 7 changes only bit 7. ldi r18, 0x80 then out DDRB, r18 also makes PB7 an output, but writes all 8 bits, so every other pin of port B becomes an input.

Materials ​

  • Arduino Mega 2560 and USB cable
  • Breadboard and jumper wires
  • 2 LEDs and 2 × 220 Ω resistors
  • Push button

Examples ​

Make a sketch with an assembly file ​

Do this once for each example and lab work:

  1. In the Arduino IDE, create a new sketch and save it, for example as blink.
  2. Click the three dots at the right end of the tab bar, choose New Tab, and name it asm.S. The S must be a capital: a lower-case .s file is ignored, and the sketch fails with "undefined reference".
  3. Paste the .ino code into the first tab and the assembly into asm.S, then upload as usual.

No wiring: this uses the on-board LED on pin 13, PB7.

cpp
// blink.ino: the C side. It only calls the two assembly functions in asm.S.

extern "C" {            // these functions are written in assembly, in asm.S
  void start();
  void led(byte on);
}

void setup() {
  start();              // set pin 13 as an output
}

void loop() {
  led(1);               // on
  delay(200);
  led(0);               // off
  delay(200);
}
asm
; asm.S: turn the on-board LED (pin 13 = PB7) on and off

; Names such as DDRB, as I/O addresses.
; Never put a comment on the next two lines.
#define __SFR_OFFSET 0
#include <avr/io.h>

.global start                   ; make the functions visible to blink.ino
.global led

start:
  sbi DDRB, 7                   ; bit 7 of DDRB = 1: PB7 is an output
  ret                           ; back to setup()

led:                            ; the argument "on" arrives in r24
  cpi r24, 0                    ; compare r24 with 0
  breq off                      ; equal: jump to off
  sbi PORTB, 7                  ; not 0: PB7 HIGH, LED on
  ret                           ; back to loop()
off:
  cbi PORTB, 7                  ; PB7 LOW, LED off
  ret

The LED blinks, on 200 ms and off 200 ms. loop() calls led(1), so r24 is 1: cpi finds it is not 0, breq does not jump, and sbi turns the LED on. led(0) makes breq jump to off, and cbi turns it off.

Example 2: LED follows a button ​

Wire a push button between pin 4 (PG5) and GND. The internal pull-up holds the pin at 1 until you press it.

cpp
// button.ino: the LED on pin 13 is on while the button on pin 4 is held.

extern "C" {
  void start();
  void update();
}

void setup() {
  start();
}

void loop() {
  update();             // read the button once and set the LED
}
asm
; asm.S: LED on pin 13 (PB7) follows the button on pin 4 (PG5)
; Button between pin 4 and GND, with the internal pull-up:
; released reads 1, pressed reads 0.

#define __SFR_OFFSET 0
#include <avr/io.h>

.global start
.global update

start:
  sbi DDRB, 7                   ; PB7 output (LED)
  cbi DDRG, 5                   ; PG5 input (button)
  sbi PORTG, 5                  ; PG5 is an input, so this turns on its pull-up
  ret

update:
  sbis PING, 5                  ; skip the next line if PG5 reads 1 (released)
  rjmp pressed                  ; PG5 reads 0: pressed
  cbi PORTB, 7                  ; released: LED off
  ret
pressed:
  sbi PORTB, 7                  ; pressed: LED on
  ret

The LED is on while you hold the button and off when you let go. sbis is the assembly form of if: when the pin reads 1 it skips rjmp pressed and falls into the "released" lines.

Lab work ​

Each lab work starts from a sketch that already works except for a few lines marked TODO, all in asm.S. Copy both files into the IDE, fill in the TODOs, and upload.

Lab work 1: two LEDs take turns ​

LED A is on for 1 s while LED B is off, then they swap, and so on.

Wire LED A to pin 22 (PA0) and LED B to pin 23 (PA1), each through 220 Ω to GND.

cpp
// lab1.ino: Lab work 1. Nothing to change here; the TODOs are in asm.S.
// LED A on pin 22 (PA0), LED B on pin 23 (PA1), each through 220 ohm to GND.

extern "C" {
  void start();
  void show(byte which);
}

void setup() {
  start();
}

void loop() {
  show(0);              // LED A on, LED B off
  delay(1000);
  show(1);              // LED B on, LED A off
  delay(1000);
}
asm
; asm.S: Lab work 1. Fill in the three TODOs.
; LED A = PA0 (pin 22), LED B = PA1 (pin 23)

#define __SFR_OFFSET 0
#include <avr/io.h>

.global start
.global show

start:
  sbi DDRA, 0                   ; PA0 output
  ; TODO 1: make PA1 an output too
  ret

show:                           ; "which" arrives in r24
  cpi r24, 0
  breq showA                    ; which = 0: jump to showA
  cbi PORTA, 0                  ; which = 1: LED A off
  ; TODO 2: LED B on
  ret
showA:
  ; TODO 3: LED A on, LED B off (two lines)
  ret

Hints

  • Every TODO is one sbi or cbi line on port A. Use DDRA to make a pin an output and PORTA to turn it on or off.
  • TODO 1: sbi DDRA, 1
  • TODO 3: look at the two lines under cpi: they do the opposite.

Lab work 2: a button picks the LED ​

While the button is released, LED A is on and LED B is off. While it is held, LED B is on and LED A is off.

Wire LED A to pin 25 (PA3), LED B to pin 27 (PA5), each through 220 Ω to GND, and the button between pin 23 (PA1) and GND.

cpp
// lab2.ino: Lab work 2. Nothing to change here; the TODOs are in asm.S.
// LED A on pin 25 (PA3), LED B on pin 27 (PA5), each through 220 ohm to GND.
// Button between pin 23 (PA1) and GND.

extern "C" {
  void start();
  void update();
}

void setup() {
  start();
}

void loop() {
  update();
}
asm
; asm.S: Lab work 2. Fill in the three TODOs.
; LED A = PA3 (pin 25), LED B = PA5 (pin 27), button = PA1 (pin 23)
; Released: LED A on, LED B off. Pressed: LED B on, LED A off.

#define __SFR_OFFSET 0
#include <avr/io.h>

.global start
.global update

start:
  sbi DDRA, 3                   ; PA3 output (LED A)
  sbi DDRA, 5                   ; PA5 output (LED B)
  cbi DDRA, 1                   ; PA1 input (button)
  ; TODO 1: turn on the pull-up of PA1
  ret

update:
  sbis PINA, 1                  ; skip the next line if PA1 reads 1 (released)
  rjmp pressed
  ; TODO 2: released: LED A on, LED B off (two lines)
  ret
pressed:
  ; TODO 3: pressed: LED B on, LED A off (two lines)
  ret

Hints

  • TODO 1: an input pin's pull-up is turned on by setting its PORTA bit, as in Example 2.
  • TODO 2 and 3: two lines each, one sbi and one cbi. LED A is bit 3 and LED B is bit 5.
  • Both LEDs on at once means a cbi is missing.

Common problems ​

SymptomCause and fix
"undefined reference to start"The tab is named asm.s instead of asm.S, the function has no .global line, or the .ino lacks extern "C".
"token ";" is not valid in preprocessor expressions"A ; comment on a #define or #include line. Those lines go through the C preprocessor; put the comment on its own line.
"operand out of range" on an sbi, cbi or sbis line#define __SFR_OFFSET 0 is missing, so PORTB means its data address, 0x25. Or the pin is on ports H–L, which these instructions cannot reach.
"register number above 15 required"ldi or cpi used with r0–r15. Use r16–r31, preferably r18–r25.
The board freezes or resets after your functionA missing ret, so the processor runs on into whatever follows. Or r1, or one of r2–r17, was changed without being saved.
The LED never lightsIts DDRx bit is still 0, so the pin is an input and the PORTx bit only switches the pull-up.
The button always reads pressed, or flickersThe pull-up is not on: set the pin's PORTx bit while it is an input.

Things to try ​

  • Toggle the LED with one instruction: writing a 1 to a PINx bit flips that output, so sbi PINB, 7 replaces the cpi/breq logic. Make led() a toggle() with no argument.
  • Return a value: write byte readButton() in assembly that puts 1 or 0 in r24 before ret, and print it from loop() with Serial.println().
  • Wire 8 LEDs to pins 22–29 and write void show(byte pattern) that does out PORTA, r24. Then count in binary from loop().
  • Replace delay() with an assembly delay: nested loops of dec and brne. At 16 MHz, how many passes make 1 ms?