'b0 = standby current		b3 = pins config for gain
'b4 = adc reading		b7 = "ON" threshhold		b8 = "OFF" threshhold

'bits 0 - 3 gain control	bit 4 slave relay		bit 5  yellow/green leds 	bit 6 slave led		bit 7 discharge
	
initialise:

	pins = %10001110						'set gain at lowest. Turn on yellow led
	pause 3000							'wait until voltages stabilise
	readadc 0,b0
	if b0 > 225	then fail					'standby current is too high
gaintest:

	b2 = 1							

	for b1 = 1 to 4						'test standby current for optimum gain

		b3 = 15 - b2					'b3 has pin configuration for gain
		pins = b3						'set gain
		b2 = 2 * b2						
		pause 1000						'wait for voltages to settle
		readadc 0,b0					'read standby current value
		if b0 >= 20 then main				'usable standby reading was attained so exit

	next b1 							'gain was insufficient so try next available
	
maxgain:

	pins = 15							'gain still insufficient so try max gain
	pause 1000
	readadc 0,b0						'get latest standby current value

main:

	'on arriving here the gain has been optimally set. b0 contains the standby current value

	high 5							'change led to green

	b7 = b0 + 20						'set threshhold level for "ON" condition
		
loop1:								'loop here until master device is turned on
	
	readadc 0,b4
	if b4 > b7 then main2					'master device has been turned on. jump to on routine
	b7 = b4 + 20						'update "ON" threshhold
	pause 3000
	goto loop1

main2:

	high 4							'turn on slave relay
	high 6							'turn on red led							
	pause 3000
	readadc 0,b5						'read ON current
	b8 = b5 - 20						'set OFF threshhold

loop2:	'on arriving here the master has been switced on with b5 holding the value of the ON current

	readadc 0,b4						'get latest current value
	if b4 < b8 then						'master device has been turned off
		low 4							'turn off relay
		low 6							'turn off red led
		high 7						'discharge C6
		pause 1000
		low 7
		pause 3000
		goto loop1
	endif
	b8 = b4 - 20						'update OFF threshhold
	pause 3000
	goto loop2 

fail:									'standby current too large

	pins = 14

loop9:								'alternately flash leds to indicate fail
	toggle 5
	pause 500
	goto loop9