; 2010 (c) Bartosz Chodorowski <chomzee@ethernet.pl>
;                              <166142@student.pwr.wroc.pl>
;
; Lista 2, Zadanie 1 uzycie timerow
; 30 marca 2010

#include<usb1287def.inc>

.cseg
.org 0x0000
rjmp Start

.org 0x002a
rjmp IntCmp
.org 0x002e
rjmp IntOvf

; global variables
.def ratio=R16

Start:
ldi R16, low(RAMEND)
ldi R17, high(RAMEND)
out SPH, R17
out SPL, R16

ldi R16, 0b11100000	;PORTB linie 5 do 7 w trybie wejściowym
in R17, PORTB
or R17, R16
out PORTB, R17

ldi R16, 0b00110000	;PORTE linie 4 i 5 w trybie wejściowym
in R17, PORTE
or R17, R16
out PORTE, R17

ldi R16, 0b11110000	;linie 4-7 portu D w trybie wyjściowym, 
in R17, DDRD
or R17, R16			;zasilanie diod LED
out DDRD, R17

; ------------ set timer ------------
ldi R16, 0
out TCNT0, R16 

ldi R16, 0b00000011
sts TIMSK0, R16 ; interrupt mask

; set prescaler (start timer)
ldi R16, 0b00000010
out TCCR0B, R16
sei
; ------------ end of setting timer ------------

ldi ratio, 128
out OCR0A, ratio


; ------------ MainLopp begins here ------------
MainLoop:
sbis PINB, 7
call Up
sbis PINE, 5
call Down
call Wait


cpi ratio, 0
brne MainLoop2

push R17
lds R17, TIMSK0
andi R17, 0b11111110
sts TIMSK0, R17
pop R17
rjmp MainLoop

MainLoop2:
push R17
lds R17, TIMSK0
ori R17, 0b00000001
sts TIMSK0, R17
pop R17
rjmp MainLoop

; ------------ MainLopp ends here ------------


; ------------ Up begins here ------------
Up:
inc ratio
brne UpEnd
ldi ratio, 0xff

UpEnd:
out OCR0A, ratio
ret
; ------------ Up ends here ------------


; ------------ Down begins here ------------
Down:
dec ratio
cpi ratio, 0xff
brne DownEnd
ldi ratio, 0

DownEnd:
out OCR0A, ratio
ret
; ------------ Down ends here ------------


; ------------ Green begins here ------------
Green:
push R16
in R16, PORTD
andi R16, 0x0F
ori R16, 0x40			;0b0100 0000(górna zielona)
out PORTD, R16
pop R16
ret
; ------------ Green ends here ------------


; ------------ Red begins here ------------
Red:
push R16
in R16, PORTD
andi R16, 0x0F
ori R16, 0x80			;0b1000 0000(górna zielona)
out PORTD, R16
pop R16
ret
; ------------ Red ends here ------------

.undef ratio
; ------------ Wait begins here ------------
Wait:
.def waiter=R16
push waiter
ldi waiter, 0
WaitLoop:
nop
nop
nop
nop
nop
inc waiter
cpi waiter, 0
brne WaitLoop
pop waiter
.undef waiter
ret
; ------------ Wait ends here ------------


IntCmp:
push R16
in R16, SREG
push R16

call Green

pop R16
out SREG, R16
pop R16
reti


IntOvf:
push R16
in R16, SREG
push R16

call Red

pop R16
out SREG, R16
pop R16
reti
