
; p2_2.s Toggling LED using assembly language 
; This program toggles green LED for 0.5 second ON and 0.5 second OFF.
; The green LED is connected to PTB19.
; The LEDs are low active (a '0' turns ON the LED).

; System Integration Module System Clock Gating Control Register 5
SIM_SCGC5 EQU 0x40048038
; Port B Pin Control Register 19
PORTB_PCR19 EQU 0x4004A04C
; Port B Pin Direction Register
GPIOB_PDDR EQU 0x400FF054
; Port B Pin Set Output Register
GPIOB_PDOR EQU 0x400FF040

        THUMB
        AREA    |.text|, CODE, READONLY, ALIGN=2
        EXPORT  __main

__main
        ; enable clock to Port B
        LDR     R0, =SIM_SCGC5  ; load SCGC5 Reg in R1
        LDR     R1, [R0]
        LDR     R2, =0x400      ; load bit 10 mask
        ORRS    R1, R2          ; OR with bit mask
        STR     R1, [R0]        ; store back to SCGC5
        
        ; make PTB19 pin as GPIO
        LDR     R0, =PORTB_PCR19
        LDR     R1, =0x100      ; pin mux GPIO (See Table 2-4)
        STR     R1, [R0]        ; store in PCR19

        ; make PTB19 as output pin
        LDR     R0, =GPIOB_PDDR ; load Dir Reg in R1
        LDR     R1, [R0]
        LDR     R2, =0x80000    ; load bit 19 mask
        ORRS    R1, R2          ; OR with bit mask
        STR     R1, [R0]        ; store back to Dir Reg

loop
        ; turn on green LED
        LDR     R0, =GPIOB_PDOR ; load Data Reg in R1
        LDR     R1, [R0]
        LDR     R2, =0x80000    ; load bit 19 mask
        MVNS    R2, R2          ; complement bit mask
        ANDS    R1, R2          ; AND with bit mask
        STR     R1, [R0]        ; store back to Data Reg
        
        ; delay for 0.5 second
        LDR     R0, =500
        BL      delayMs

        ; turn off green LED
        LDR     R0, =GPIOB_PDOR ; load Data Reg in R1
        LDR     R1, [R0]
        LDR     R2, =0x80000    ; load bit 19 mask
        ORRS    R1, R2          ; OR with bit mask
        STR     R1, [R0]        ; store back to Data Reg
        
        ; delay for 0.5 second
        LDR     R0, =500
        BL      delayMs

        ; repeat the loop
        B       loop

; This subroutine performs a delay of N ms 
; (for 41.94 MHz CPU clock). 
; N is the value in R0.
delayMs
        MOVS    R0, R0          ; if N = 0, return
        BNE     L1
        BX      LR
L1      LDR     R1, =14022      ; do inner loop 14022 times
L2      SUBS    R1, #1          ; inner loop
        BNE     L2
        SUBS    R0, #1          ; do outer loop N times
        BNE     L1
        BX      LR

        ALIGN
        END
