;
; irq_lopri.inc: low priority interrupt handling
;
; led / key handling.
;
; author: Marko Kanala, raato ]a t[ mulletronic.com
;
; LICENSE
; Creative Commons Attribution-NonCommercial-ShareALike 2.5
;
; You are free:
;
; * to copy, distribute, display, and perform the work
; * to make derivative works
;
; Under the following conditions:
;	
; 1. Attribution. You must attribute the work in the manner specified by the 
;    author or licensor.
; 2. Noncommercial. You may not use this work for commercial purposes.
; 3. Share Alike. If you alter, transform, or build upon this work, you may 
;    distribute the resulting work only under a license identical to this one.
;
; * For any reuse or distribution, you must make clear to others the license 
;   terms of this work.
; * Any of these conditions can be waived if you get permission from the 
;   copyright holder.
;
; Your fair use and other rights are in no way affected by the above.
;
; This is a human-readable summary of the Legal Code.
; See full license at http://creativecommons.org/licenses/by-nc-sa/2.5/legalcode
;
; Copyright: Marko Kanala (raato@mulletronic.com).
;

lp_irq:
	movwf	lp_irq_wtmp
	movff	STATUS, lp_irq_statustmp
	movff	BSR, lp_irq_bsrtmp

; which interrupt occurred ?
lp_check_irq:
	; timer 0 ?
	btfsc	INTCON, TMR0IF
	bra		lp_irq_timer0

	; timer 2 ?
  	btfsc	PIR1, TMR2IF 	
  	bra	  	lp_irq_keysleds

	; a/d converter ready ?
	btfsc	PIR1, ADIF
	bra		lp_irq_adc

	; TODO: check din run/stop while at it to prevent
	;  the sequencer from stucking if din sync
	;  is lost ? (press stop key?)

	; TODO: what to do if midi stop is missed and
	;  midi clock is lost ? (press stop key?)

	; decrement lcdwait if needed
	decfsz	lcdwaitcounter
	bra		lp_irq_nolcdwait
	tstfsz	lcdwait
	decf	lcdwait
lp_irq_nolcdwait:

	movff	lp_irq_bsrtmp, BSR
	movf	lp_irq_wtmp, W
	movff	lp_irq_statustmp, STATUS
	retfie

lp_irq_keysleds:
	; light up leds and read keys
	call	do_keysleds		; see keysleds.inc
	; restart tempo pot a/d if necessary
	call	ad_timer2		; see adc.inc

	decfsz	blink_counter	; toggle blink bit
	bra		lp_blink_ok		;  if necessary
	decfsz	blink_counter2
	bra		lp_blink_ok
	movlw	blink_speed
	movwf	blink_counter
	movlw	blink_speed2
	movwf	blink_counter2
	btg		blink, 0
lp_blink_ok:
	IFRUNNING lp_setstartled
	bcf		LEDREG_START, LED_START
lp_startleddone:
	bcf		PIR1, TMR2IF
	bra		lp_check_irq

; sets the start led
lp_setstartled:
	IFMODE	MODE_PWRITE, lp_blink_start
	; light up start led if in play mode
	bsf		LEDREG_START, LED_START	
	bra		lp_startleddone
lp_blink_start:
	; blink start if in write mode
	btfss	blink_tempo, 0
	bra		lp_blink_ns
	bsf		LEDREG_START, LED_START
	bra		lp_startleddone
lp_blink_ns:
	bcf		LEDREG_START, LED_START
	bra		lp_startleddone

lp_irq_adc:
	; a/d done
	call	ad_irq			; see adc.inc
	bcf		PIR1, ADIF
	bra		lp_check_irq

; din clock off
lp_irq_timer0:
	call	din_clock_off
	bcf		INTCON, TMR0IF
	bra		lp_check_irq

External Labels :

do_keysleds
ad_timer2
ad_irq
din_clock_off