;=======================================================
; Проект 46. Метроном с регулировкой темпа
; ATmega8, 8 МГц. Пьезоизлучатель — PB0,
; кнопки: PD3 быстрее, PD4 медленнее. Светодиод такта — PB1
;=======================================================
.include "m8def.inc"

.def tmp   = r16
.def tempo = r17                        ; чем меньше, тем быстрее
.def cnt   = r18

.cseg
.org 0x0000
        rjmp    RESET

RESET:
        ldi     tmp, low(RAMEND)
        out     SPL, tmp
        ldi     tmp, high(RAMEND)
        out     SPH, tmp

        ldi     tmp, 0b00000011
        out     DDRB, tmp
        sbi     PORTD, 3                ; подтяжки кнопок
        sbi     PORTD, 4
        ldi     tempo, 20               ; стартовый темп

MAIN:
        rcall   Click                   ; щелчок и вспышка
        mov     cnt, tempo
PAUSE:
        rcall   Delay20ms
        sbis    PIND, 3
        rcall   Faster
        sbis    PIND, 4
        rcall   Slower
        dec     cnt
        brne    PAUSE
        rjmp    MAIN

;--- короткий тональный щелчок ---
Click:
        sbi     PORTB, 1
        ldi     r19, 60                 ; ~60 периодов звука
CL:     sbi     PORTB, 0
        rcall   Delay500us
        cbi     PORTB, 0
        rcall   Delay500us
        dec     r19
        brne    CL
        cbi     PORTB, 1
        ret

Faster:
        rcall   Delay20ms
        sbic    PIND, 3
        ret
        cpi     tempo, 5                ; предел скорости
        breq    FA_REL
        dec     tempo
FA_REL:
        sbis    PIND, 3
        rjmp    FA_REL
        ret

Slower:
        rcall   Delay20ms
        sbic    PIND, 4
        ret
        cpi     tempo, 60
        breq    SL_REL
        inc     tempo
SL_REL:
        sbis    PIND, 4
        rjmp    SL_REL
        ret

Delay500us:
        ldi     r20, 250
T1:     nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        dec     r20
        brne    T1
        ret

Delay20ms:
        ldi     r20, 255
T2:     ldi     r21, 210
T3:     dec     r21
        brne    T3
        dec     r20
        brne    T2
        ret
