Hackster is hosting Hackster Holidays, Finale: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Tuesday!Stream Hackster Holidays, Finale on Tuesday!
Patrick Fitzgerald
Published © GPL3+

AVR Assembly Code Subroutines in Arduino Programming

Arduino lets you use blocks of assembly language code as subroutines in your sketches.

IntermediateProtip3 hours507
AVR Assembly Code Subroutines in Arduino Programming

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Marquee LED bar arduino
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

ASMcount.ino

Arduino
Arduino C language sketch to use Assembly code in External .S file
// C program sketch declares 2 functions - start and forever
// the functions are defined externally in .S file
extern "C" {
  // function prototypes
  void start();
  void forever();
}
void setup(){ start(); }
void loop() { forever(); }

assembly.S

C Header File
AVR assembly code for Arduino IDE sketch
can have any filename but must have .S extension
; Arduino sketch written with AVR assembly code
#define __SFR_OFFSET 0x20
#include "avr/io.h"
.global start
.global forever

start:
  LDI R16, 0xFF     ; Setting all PORTB as output
  STS DDRB, R16
  LDI R17, 0x00
  STS PORTB, R17    ; Writing initial value 0 to PORTB
  LDI R16, 0x00
  STS TCCR1A, R16   ; Setting all bits of TCCR1A as 0
  RET

forever: 
  LDI R16, 0xF8
  STS TCNT1H, R16   ; Writing loop delay 0xF8 into TCNT1H (8-bit)
  LDI R16, 0xFB
  STS TCNT1L, R16   ; Writing loop delay 0xFB into TCNT1L (8-bit)
  LDI R16, 0x05
  STS TCCR1B, R16   ; Writing 0x05 into TCCR1B
L:LDS R0, TIFR1     ; Load the value of TIFR1 into R0
  SBRS R0, 0        ; Skip the next statement if overflow has occured. 
  RJMP L            ; Loop until overflow occurs.
  LDI R16, 0x00
  STS TCCR1B, R16   ; Stop the Timer/Counter1
  LDI R16, 0x01
  STS TIFR1, R16    ; Clear the overflow flag by writing 1 to it
  
  ; increment PORTB binary count led blinks 
  INC R17           ; Increment R17 register
  STS PORTB, R17    ; Toggle the LED output
  RET               ; return to label forever:
    

Credits

Patrick Fitzgerald
118 projects • 40 followers

Comments