; 2010 (c) Bartosz Chodorowski <chomzee@ethernet.pl>
;                              <166142@student.pwr.wroc.pl>
;
; Lista 2, Zadanie 2 uzycie timerow
; 30 marca 2010


#include<usb1287def.inc>

.cseg
.org 0x0000
rjmp Start

.org 0x002a
rjmp IntCmpA
.org 0x002c
rjmp IntCmpB


; global variables

.def ratio=R16
.def const1=R17
.def const2=R18


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, 0b00000110 ; interrupt mask
sts TIMSK0, R16

; set CTC mode
ldi R16, 0b00000010
out TCCR0A, R16

ldi R16, 100 ; compare A value
out OCR0A, R16

; set prescaler (start timer)
ldi R16, 0b00000010
out TCCR0B, R16
sei
; ------------ end of setting timer ------------

ldi ratio, 10
out OCR0B, ratio
ldi const1, 21
ldi const2, 197


; ------------ MainLopp begins here ------------
MainLoop:

call Wait

mul ratio, const1
mov ratio, R0
LoopMod2:
cpi ratio, 100
brlo LoopMod2End
subi ratio, 100
rjmp LoopMod2
LoopMod2End:

add ratio, const2
LoopMod:
cpi ratio, 100
brlo LoopModEnd
subi ratio, 100
rjmp LoopMod

LoopModEnd:

out OCR0B, ratio
rjmp MainLoop
; ------------ MainLopp 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 czerwona)
out PORTD, R16
pop R16
ret
; ------------ Red ends here ------------

.undef ratio
.undef const1
.undef const2

; ------------ Wait begins here ------------
Wait:
.def waiter=R16
.def waiter2=R17
push waiter
push waiter2
ldi waiter, 0
WaitLoop2:
WaitLoop:
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
inc waiter
cpi waiter, 0
brne WaitLoop
inc waiter2
cpi waiter2, 0
brne WaitLoop2
pop waiter2
pop waiter
.undef waiter
.undef waiter2
ret
; ------------ Wait ends here ------------

IntCmpB:
push R16
in R16, SREG
push R16

call Green

pop R16
out SREG, R16
pop R16
reti


IntCmpA:
push R16
in R16, SREG
push R16

call Red

pop R16
out SREG, R16
pop R16
reti
