; ARM assembly tutorial for Asmonite, example 05 for the Blue Pill (STM32F103, Arm Cortex-M3).
; Adapted from the ARM-ASM-Tutorial by Niklas Guertler (example BlinkDelay); see ..\LICENSE.txt.
;
; The STM32F103 is the chip of the original tutorial, and this is nearly its example. Two differences:
;   - the LED of the Blue Pill is at PC13 (the original uses PA8), and it is on when the pin is low
;   - the program runs in the RAM (0x20000000): F7 loads it there and stops at _start
; The peripherals of the STM32 are switched on through their clock (RCC_APB2ENR, bit 4 for port C), and a
; pin is configured with 4 bits in GPIOx_CRL (pins 0..7) or GPIOx_CRH (pins 8..15): MODE (2 = output,
; 2 MHz) and CNF (0 = push-pull). GPIOx_BSRR sets a pin with its bit (0..15) and clears it with the bit 16
; higher.
.target stm32f103
.arch thumb
.imagebase 0x20000000

_start:
    ldr  r1, rcc_apb2enr
    ldr  r0, [r1]
    orr  r0, r0, #0x10
    str  r0, [r1]               ; set IOPCEN in RCC_APB2ENR: the clock of port C on

    ldr  r1, gpioc_crh
    ldr  r0, [r1]
    bic  r0, r0, #0x00f00000
    orr  r0, r0, #0x00200000
    str  r0, [r1]               ; CNF13:MODE13 in GPIOC_CRH = 2: PC13 is an output

blink_loop:
    ldr  r1, gpioc_bsrr
    ldr  r0, led_on
    str  r0, [r1]               ; BR13 in GPIOC_BSRR: PC13 low, LED on
    ldr  r2, delay_count
delay1:
    subs r2, r2, #1
    bne  delay1
    ldr  r1, gpioc_bsrr
    ldr  r0, led_off
    str  r0, [r1]               ; BS13 in GPIOC_BSRR: PC13 high, LED off
    ldr  r2, delay_count
delay2:
    subs r2, r2, #1
    bne  delay2
    b    blink_loop

    align 4
rcc_apb2enr: dd 0x40021018      ; RCC_APB2ENR
gpioc_crh:   dd 0x40011004      ; GPIOC_CRH
gpioc_bsrr:  dd 0x40011010      ; GPIOC_BSRR
led_on:      dd 0x20000000      ; BR13 (bit 29)
led_off:     dd 0x00002000      ; BS13 (bit 13)
delay_count: dd 500000
