.area FUSE (ABS)
.org 0x3ff*2
.word ( 0x0260 | 1<<0 | 5<<2 | 1<<7 | 3<<10 )
; reserved_bits | security_off | lvr_1v8 | io_drv_norm | boot_fast

.area OSEG (OVR,DATA)
pwm: .ds 1

.even ; SP must be aligned
stack_start: .ds 1
.area SSEG
stack: .ds 1

; io addresses
clkmd = 0x03
inten = 0x04
intrq = 0x05
tm2c = 0x1C
tm2b = 0x09
tm2s = 0x17
t16m  = 0x06
eoscr = 0x0A
padier = 0x0D
pa = 0x10
pac = 0x11
paph = 0x12
misc = 0x1B
gpcc = 0x1A
ihrcr = 0x0B

calib_freq = 4294967 ; Hz
calib_vdd  = 3000 ; mV

; portA.3 -> ivr debug signal
; portA.4 -> pwm output

.area CSEG (CODE,ABS)
.org 0x0000
	GOTO	init

.org 0x0020
	goto	interrupt

init:
	; clock setup (no calibration):
	set1	clkmd, #4	; enable IHRC
	mov	a, #(( 0<<5 | 1<<4 | 0<<3 | 1<<2 | 0<<1 | 0<<0 ))
	mov	clkmd, a	; switch to IHRC/4, WDT off; keep ILRC on

	; calibration placeholder:
	and	a, #'R'
	and	a, #'C'
	and	a, #1 ; IHRC
	and	a, #( calib_freq )
	and	a, #( calib_freq>>8 )
	and	a, #( calib_freq>>16 )
	and	a, #( calib_freq>>24 )
	and	a, #( calib_vdd )
	and	a, #( calib_vdd>>8 )
	and	a, #ihrcr

	;stack setup:
	mov	a, #stack_start
	mov	sp, a

	; portA setup:
	mov	a, #0xff
	mov	pac, a		; data direction: all output
	mov	a, #0
	mov	padier, a	; disable pin wakeup
	mov	pa, a		; PortA data = 0
	mov	paph, a		; disable all pull-ups

	mov	a, #0x80
	mov	pwm, a
	mov	tm2b, a		; pwm duty cycle 50%
	mov	a, #(( 2<<4 | 3<<2 | 1<<1 | 0<<0 ))
	mov	tm2c, a		; timer2: IHRC, PA4, PWM, not inverted
	mov	a, #(( 0<<7 | 1<<5 | 0<<0 ))
	mov	tm2s, a		; 8bit, /4 prescaler, divide by (0+1)

	;timer16 setup
	mov	a, #(( 0<<0 | 1<<3 | 4<<5 ))	; ovf@bit8, clk/4, ihrc
	mov	t16m, a
	mov	a, #(1<<2)		; enable timer16 int, disable all others
	mov	inten, a

	; misc setup:
	set1	eoscr, #0	; disable bandgap and lvr
	set0	gpcc, #7	; disable comparator

	engint
	goto loop

	
interrupt:
	; we only have timer16 interrupt enabled, so we don't have to check
	; which one triggered.

	; increment pwm duty cycle:
	set1	pa, #3	;debug
	mov a, pwm
	add a, #4
	mov tm2b, a
	mov pwm, a

	; blow up the ivr, so it shows up on the oscilloscope more easily:
	mov a, #0x3f
x:	dzsn a
	goto x

	;clear t16int:
	set0 intrq, #(1<<2)
	set0	pa, #3	;debug
	reti


loop:
	stopexe
	goto loop
