; ============================================================
; CTEC 350 - Project 2 (Part 2)
; 4-bit Binary Countdown Timer using Timer 1, Mode 2 (8-bit Auto-Reload)
;
; Timer 1 Mode 2: 8-bit auto-reload timer
;   - TH1 holds the reload value; TL1 is the counting register
;   - On overflow, TL1 is automatically reloaded from TH1
;   - 200 cycles: reload value = 256 - 200 = 56 = 0x38
;   - TH1 = TL1 = 0x38 (set once at initialization)
;   - No need to reset TH1/TL1 before each delay call
;     (auto-reload handles it), except for the first initialization.
;
; 7-segment display connected to Port 1 (active LOW)
; ============================================================

        ORG 0

        MOV TMOD, #20H          ; Configure Timer 1 in Mode 2 (8-bit auto-reload)
        MOV TH1, #038H          ; Reload value: 256 - 200 = 56 = 0x38
        MOV TL1, #038H          ; Initial count value (same as reload value)

        MOV DPTR, #300H         ; Load lookup table base address into DPTR
        MOV A, #00FH            ; Load initial counter value (15)
        MOV R0, A               ; Store counter in R0

COUNTER:
        ACALL DELAY             ; Call delay before displaying
        MOV A, R0               ; Load current counter value into A
        MOVC A, @A+DPTR         ; Translate counter value to 7-seg encoding
        MOV P1, A               ; Output 7-seg value to Port 1
        DJNZ R0, COUNTER        ; Decrement R0; if not zero, loop back

        ; Handle display of 0 (R0 = 0 after DJNZ exits)
        ACALL DELAY
        MOV A, R0               ; A = 0
        MOVC A, @A+DPTR         ; Get 7-seg encoding for 0
        MOV P1, A               ; Display 0

        ; Reset counter and repeat
        MOV A, #00FH            ; Reload counter to 15
        MOV R0, A
        SJMP COUNTER            ; Restart countdown loop

; ============================================================
; DELAY Subroutine - Uses Timer 1, Mode 2 (8-bit auto-reload)
;   TH1/TL1 are initialized once at startup; TL1 auto-reloads
;   from TH1 on each overflow, so no register reset is needed here.
;   Starts timer, polls TF1, then clears TR1 and TF1.
; ============================================================
DELAY:
        SETB TR1                ; Start Timer 1
WAIT:   JNB TF1, WAIT           ; Poll TF1; wait until overflow (200 cycles)
        CLR TR1                 ; Stop Timer 1
        CLR TF1                 ; Clear overflow flag
        RET

; ============================================================
; Lookup Table: Binary value -> 7-segment encoding (active LOW)
; Entries 0-15 (indices match counter value in R0)
; ============================================================
        ORG 300H
BINARY_TO_7SEG_TABLE:
        DB 129, 207, 146, 134, 204, 164, 160, 143, 128, 132, 136, 224, 177, 194, 176, 184
