
; PC-9800シリーズ対応 IR Tower

; 8000000Hzのクロックを使用すること

	device	pic16f84
	include "pic16c84.h"

counter300Hz	equ	20h
counter10Hz	equ	21h
sleepcounter	equ	22h
countCS		equ	23h

;PA_IRPW	equ	0
PB_IRTX		equ	0
PB_IRRX		equ	7
PA_CS		equ	0
PA_RX		equ	1
PA_RS		equ	2
PA_TX		equ	3


POWOFF		equ	1	; sec
CSDELAY		equ	15	; 0.05s * 300 = 15
TMR0COUNT	equ	23	; 約38kHz


	org	0

	goto	main

	org	4

intr:
	goto	wakeup

main
	clrf	PORTA
	clrf	PORTB

	; select bank 1
	bcf	STATUS,6
	bsf	STATUS,5

	movlw	8fh
	movwf	OPTIO

	movlw	06h
	movwf	TRISA

	movlw	80h
	movwf	TRISB

	; select bank 0
	bcf	STATUS,5
wakeup:
	clrf	INTCON

;	bsf	PORTA,PA_IRPW
	bcf	PORTA,PA_CS

	clrf	TMR0
init2:
	movlw	-10*POWOFF
	movwf	sleepcounter
init1:
	movlw	-30		; 30分周
	movwf	counter10Hz
init0:
	clrf	counter300Hz	; 256分周
loop:
	btfss	INTCON,2	; T0IF
	goto	loop

	bcf	INTCON,2	; T0IF

	movlw	TMR0COUNT
	subwf	TMR0,F

	btfsc	PORTB,PB_IRRX
	bsf	PORTA,PA_TX
	btfss	PORTB,PB_IRRX
	bcf	PORTA,PA_TX

	bcf	PORTB,PB_IRTX
	btfsc	PORTA,PA_RX
	goto	loop1

	movlw	-10*POWOFF
	movwf	sleepcounter

	btfsc	counter300Hz,0
	bsf	PORTB,PB_IRTX
loop1:
	incfsz	counter300Hz		; 38400 * 2 / 256 = 300Hz
	goto	loop

	btfsc	PORTA,PA_RS
	goto	loop2

	movlw	-CSDELAY
	movwf	countCS
	bcf	PORTA,PA_CS
	goto	loop4
loop2:
	incfsz	countCS,W
	goto	loop3
	bcf	PORTA,PA_CS
	goto	loop4
loop3:
	movwf	countCS
	bsf	PORTA,PA_CS
loop4:
	incfsz	counter10Hz		; 300Hz / 30 = 10Hz
	goto	loop

	goto	init1			;;;;;;;;;; never sleep !	

	incfsz	sleepcounter		; 0.1s * sleepcounter
	goto	init1

	; sleep

powoff:
	bsf	PORTA,PA_TX
	bcf	PORTB,PB_IRTX

	movlw	88h
	movwf	INTCON
	sleep

	end
