' PortalMono Copyright Cyrob 2015
' CP0068 Firmware

' Release History
' 13/11/2015	V1.0 		Phildem		Creation

' IO abstraction
symbol In_Bt 		= pinC.3	'Ctl Button activ Low
symbol Out_Buzz		= C.4		'Sound Buzzer  activ High
symbol Out_Cmd1		= C.1		'Portal Command 1 activ High
symbol Out_Cmd2		= C.2		'Portal Command 2  activ High
symbol Out_On 		= C.0		'System Off  activ High

' States
symbol kStateAbort 	= 4		' Abort
symbol kStateOpenAll 	= 1		' Open Both Door
symbol kStateOpen1 	= 2		' Open Door 1
symbol kStateOpenTemp 	= 3		' Open Door 1 and close it

' Misc Constant
symbol kStateBeep 	= 200		' State Beep Tempo
symbol kTickVal	 	= 50		' Value of tick in mS
symbol kStateDelay 	= 30		' 40 Number of ticks between state change
symbol kButtonRel		= 1		' Bt Released
symbol kConfirmDelay 	= 80		' 100 Number of ticks waiting confirm
symbol kCloseDelay 	= 140		' 150 Number of ticks waiting close 
symbol kPulseBuzz	 	= 40000	' Buzz Pulse duration (16bit)
symbol kPulsePortal	= 65500	' Buzz Pulse duration (16bit)

'Variables
symbol m_State 		= b0		' State 
symbol m_Lv			= b1		' Local loop variable
symbol m_Wait		= b2		' Bt Wait in Tick
symbol m_ConfDelay	= b3		' Bt Wait in Tick
symbol m_Bip		= b4		' confirm mode Bip period in tick

'Program
main:
output Out_Buzz		' Init Outputs
output Out_Cmd1
output Out_Cmd2
output Out_On

high Out_On			' Lock Power On

m_State 	= kStateAbort	' Init Var
m_ConfDelay = kConfirmDelay

'-------------------------------------------------------
SwLoop:

'Indicate state
for m_Lv = 1 to m_State
	High Out_Buzz
	Pause kStateBeep
	Low Out_Buzz
	Pause kStateBeep
next m_Lv

'Look if Bt Released
m_Wait=0
WaitBt:
Pause kTickVal
if In_Bt=kButtonRel then Doit
inc m_Wait
if m_Wait<kStateDelay then WaitBt

'Change state
inc m_State
if m_State>kStateAbort then
	m_State=kStateOpenAll
end if

goto SwLoop			' no press so loop
'-------------------------------------------------------

DoIt:

Pause 20		' Debounce		 

'Cancel if needed
if m_State = kStateAbort then
	
ByeBye:

	Low Out_On		' Cancel Bye
	Pause kStateBeep
	goto main			' Just for test
end if

'Wait for exec or cancel
ConfirmLoop:

m_Wait=0
m_Bip=0

WaitCancel:
Pause kTickVal

inc m_Bip

if m_Bip=8 then
	pulsout Out_Buzz,kPulseBuzz
	m_Bip=0
endif

if In_Bt<>kButtonRel then ByeBye
inc m_Wait
if m_Wait<m_ConfDelay then WaitCancel

'Open All ------------------------------------
if m_State = kStateOpenAll then
	pulsout Out_Cmd1,kPulsePortal
	goto ByeBye
endif

'Open One  ------------------------------------
if m_State = kStateOpen1 then
	pulsout Out_Cmd2,kPulsePortal
	goto ByeBye
endif

'Open and close  ------------------------------------
if m_State = kStateOpenTemp then
	pulsout Out_Cmd2,kPulsePortal
	m_State = kStateOpen1
	m_ConfDelay = kCloseDelay
	goto DoIt
endif

goto main