;MDrv1  SPice10213 simple speed control example

;This program illustrates simple speed control
;and dynamic braking of a small DC motor using the SPice10213
;on and MS12. It has a forward/reverse button and a stop/start button.

;Forward/reverse is active only while the motor is stopped.

;Stop/starts initial starts the speed ramping up. Once running,
;it triggers a sudden stop.

;The motor will be started at an initial PWM setting. This will be a function of
;the motor ... below some threshold it doesn't rotate at all.
InitialPWM	EQU	50

;The motor will ramp up to the PWM value MaxPWM
MaxPWM		EQU		200

iStopStart	iEQU		16		;The Stop/Start button
iFwdRev		iEQU		14		;The Forward/Reverse button

oDirection	oEQU		12		;The direction relay

;------- RAM allocation ------------------
PWM		mEQU		0


;------ 
;Start of program
		setu		0,1		;set spice connector pin 4 as DO
		setu		4,4		;set spice connector pin 8 as PWM output
		SpiceConfigU

Idle:			;Back here when motor is stopped
		ResetK					:clear any pending buttons
IdleLoop:		;Sit and wait for a button (command)

		GoIfInK		iStopStart,StartUp	;Test for start command
		InputK		iFwdRev			;Test for reversal
		GoIfF		IdleLoop		
		InputO		oDirection		;Reverse the direction relay
		NOT
		Output		oDirection
		GoTo		IdleLoop

;Here to start the motor
StartUp:
		LoadX		InitialPWM		;Initial speed
RampLoop:
		Push					;Duplicate
		GoIfXEQ		MaxPWM,Running		;Test if at max speed
		IncX					;Increment the speed value
		Push					;Duplicate
		AnOutJ					;Update motor drive
		GoIfInK		iStopStart,Stop		;Test for stop
		Pause		2			;20mS delay
		GoTo		RampLoop

Running:		;Here when running at max speed
		WaitOnK		iStopStart		;Wait for stop command
Stop:
		LoadX		0
		AnOutJ					;Turn off PWM output
		InputO		oDirection		;Reverse the direction relay ..
		NOT					; .. for ...
		Output		oDirection		;... dynamic braking
		Pause		10			;Time for motor to stop
		InputO		oDirection		;Restore the direction relay
		NOT
		Output		oDirection
		GoTo		Idle		
		