Arduino Due Inline Assembly Blink

blink

Very basic inline assembler example of the blinky program. A good place to start learning ARM assembly language is through this online book. You will find a concise summary of ARM GCC inline assembly here.

void setup() {
  asm volatile(
    "mov r0, %[led] \n\t" 
    "mov r1, #1     \n\t"
    "lsl r1, #27    \n\t"
    "str r1, [r0]   \n\t" : : [led] "r" (&REG_PIOB_OER)
  );
}

void loop() {
    asm volatile(
      "push {r0-r3, lr}   \n\t" 
      "mov r0, %[led_set] \n\t" 
      "mov r1, #1         \n\t" 
      "lsl r1, #27        \n\t" 
      "str r1, [r0]       \n\t"
      "mov r0, #1000      \n\t"
      "bl delay           \n\t"
      "mov r0, %[led_clr] \n\t"
      "mov r1, #1         \n\t"
      "lsl r1, #27        \n\t"
      "str r1, [r0]       \n\t"
      "mov r0, #1000      \n\t"
      "bl delay           \n\t"
      "pop {r0-r3, lr}    \n\t"
      "bx lr              \n\t"
      : : [led_set] "r" (&REG_PIOB_SODR), [led_clr] "r" (&REG_PIOB_CODR)
    );
}

Interesting to note, the Arduino Due example blink program produces a file 10,092 bytes in size. My inline assembler program is 10,028 bytes, saving a mere 64 bytes (less than 1% smaller). However, the following C version listed below, compiled inside AtmelStudio6 produces a file 4,160 bytes large.

Atmel Studio Blink code:

#include "sam.h"

volatile uint32_t ms;

void Systick_Handler(void) {
  ms++;
}

uint32_t GetTickCount(void) {
  return ms;
}

static void ConfigIO(void) {
  //enable io
  PIOB->PIO_PER = PIO_PB27;
  PIOD->PIO_PER = PIO_PD0;
  //set to output
  PIOB->PIO_OER = PIO_PB27;
  PIOD->PIO_OER = PIO_PD0;
  //disable pull-up
  PIOB->PIO_PUDR = PIO_PB27;
  PIOD->PIO_PUDR = PIO_PD0;
}

void Delay(uint32_t ms) {
  uint32_t start;

  if (ms == 0)
    return;
  start = GetTickCount();
  do {
  } while (GetTickCount() - start < ms);
}

int main(void) {
  //initialize system 
  SystemInit();
  ConfigIO();
  while (1) {
    REG_PIOB_SODR = (1u<<27);
    Delay(1000);
    REG_PIOB_CODR = (1u<<27);
    Delay(1000);
  }
}
Advertisements

About Jim Eli

µC experimenter
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s