; ============================================================
; CTEC 350 - Project 2 (Part 1)
; 4-bit Binary Countdown Timer using Timer 0, Mode 1 (16-bit)
;
; Timer 0 Mode 1: 16-bit timer
;   - Counts from loaded value up to 0xFFFF, then sets TF0
;   - 200 cycles: load value = 65536 - 200 = 65336 = 0xFF38
;   - TH0 = 0xFF, TL0 = 0x38
;
; 7-segment display connected to Port 1 (active LOW)
; ============================================================

        ORG 0

        MOV TMOD, #01H          ; Configure Timer 0 in Mode 1 (16-bit timer)
        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 0, Mode 1 (16-bit)
;   Counts 200 cycles: load 0xFF38 into TH0:TL0
;   Resets TH0/TL0 on every call, starts timer,
;   polls TF0, then clears TR0 and TF0.
; ============================================================
DELAY:
        MOV TH0, #0FFH          ; Load high byte (0xFF38 = 65536 - 200)
        MOV TL0, #038H          ; Load low byte
        SETB TR0                ; Start Timer 0
WAIT:   JNB TF0, WAIT           ; Poll TF0; wait until overflow (200 cycles)
        CLR TR0                 ; Stop Timer 0
        CLR TF0                 ; 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
