Hackster is hosting Hackster Holidays, Ep. 4: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Wednesday!Stream Hackster Holidays, Ep. 4 on Wednesday!
Yeshvanth Muniraj
Published

Arduino Blink Example in Assembly using Timer/Counter1

Tutorial on how to use the Timer /Counter1 module in ATmega328P using AVR Assembly to demonstrate a simple LED blink example.

BeginnerProtip30 minutes9,754
Arduino Blink Example in Assembly using Timer/Counter1

Things used in this project

Story

Read more

Schematics

Fritzing File

Code

Blink.ino (for linking the assembly file)

C/C++
In the same folder with the assembly code file
extern "C" {
  // function prototypes
  void start();
  void forever();
}

void setup() {
  start();
}

void loop() {
  forever();
}

Blink.ino (C code)

C/C++
const int LED_Pin = 8;
void setup() 
{
  pinMode(LED_Pin, OUTPUT);
}

void loop() 
{
  digitalWrite(LED_Pin, LOW);
  delay(1000); 
  digitalWrite(LED_Pin, HIGH);
  delay(1000);
}

Blink.S

Assembly x86
Assembly File
#define __SFR_OFFSET 0x20
  
#include "avr/io.h"

.global start
.global forever

start:
  LDI R16, 0x01     ; Setting 1st bit of PORTB as output
  STS DDRB, R16
  LDI R17, 0x00
  STS PORTB, R17    ; Writing 0 to PORTB
  LDI R16, 0x00
  STS TCCR1A, R16   ; Setting all bits of TCCR1A as 0
  RET

forever: 
  LDI R16, 0xC2
  STS TCNT1H, R16   ; Writing 0xC2 into TCNT1H (8-bit)
  LDI R16, 0xF7
  STS TCNT1L, R16   ; Writing 0xF7 into TCNT1H (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
  COM R17           ; Complement R17 register
  STS PORTB, R17    ; Toggle the LED output
  RET

    

Credits

Yeshvanth Muniraj

Yeshvanth Muniraj

20 projects • 35 followers
Hands-on experience in Embedded Systems and IoT. Good knowledge of FPGAs and Microcontrollers.

Comments