Hardware prolog (HelloWorld again)

A project log for AVR Asm Exam

Doing the "exam" of the AVR assembly course

Michael MöllerMichael Möller 02/26/2021 at 22:540 Comments

I am impressed that the Arduino IDE in real life is as comprehensive as the simulator (or is it the other way round ? ;-) ) The same .ino and .S files will compile, upload and run InRealLife as they do in the simulator. The simulator has a few more tricks (the automated view of final assembly code before upload, and the debugging facilities - BREAK does something usefull, and gdb (debugger) can be hooked up)

As my project plan is to do it in the hardware as much as possible, and at this time of writing I only have the Arduino, (parts are on order) another HelloWorld blink LED program is called for, now with an actual loop.

My .ino file is just a comment, this is the .S file. Hit the compile and upload button on the IDE and the real life Arduino will blink.

#define __SFR_OFFSET 0 // makes "PORTB" etc fit the IN/OUT Port, instead of the memory equivalent
#include <avr/io.h>    // Get the "basic" symbolic names for registers
.global main           ; Interface to the Arduino/C startup (It will setup vectortables and stack...)

;====== MAIN, START HERE ====

   ; ==== Initialization =====

  sbi   DDRB,5      ; Set PB5 (Arduino pin 13) as output

   ; ==== Loop =====
  sbi   PORTB,5     ; Set LED ON
  ldi   r24,lo8(1000)
  ldi   r25,hi8(1000)
  call  delayMillis
  cbi   PORTB,5     ; Set LED OFF  -- doenst seem to happen?
  ldi   r24,lo8(1000)
  ldi   r25,hi8(1000)
  call  delayMillis
  rjmp  loop
;====== delay routine (milliseconds) ====
; r24/25 - number of milliseconds. (set to zero on exit)

  push r26
  push r27
2:; 16000 cycles
  ldi r26, lo8(4000)
  ldi r27, hi8(4000)
  sbiw r26, 1  ; 2 cycles
  brne 1b      ; 2 cycles 
  sbiw r24, 1
  brne 2b
  pop r27
  pop r26

The delayMillis routine was supplied by Uri in the course, shameless cut-n-paste there. But I "improved" it by preserving the r26/27 registers. This caused a bug it took me a few hours to find (blinded by my own brilliance there). The wrong code made two push operations for every millisecond, eventually wrapping the stack, overwriting things but fortunatly stopping/looping/getting lost in never-never land before it overwrote the RESET vector (which is vital for uploading a new program(?)).  The debugging process involved running this in the simulator and BREAK everywhere until I finally could slap my forhead with the required force.

This code, too, isnt pretty or educational, a bit inconsistent in naming,defines and so on, but I now have verified I can create working assembly-only programs on my physical Arduino.