;Program: DCMOTOR1.BAS

;This program utilizes the VERSATECH TICKit to vary and control the 
;speed of a DC motor using UNITRODE L293D Driver. If pin_D6 is an 
;active low then the motor is slowed down, and if pin_D5 is an active
;low then the motor speeds up.

;TICKit ---------------------------------> L293D (Driver)
;pin_D7 (term 38) -----------------------> (term 15 )
;
;Copyright, Locksley Haynes, Morgan State University, Oct 11, '97
;
DEF tic62_b       ;define the device in use
LIB fbasic.lib    ;define library for basic routines                   

DEF dc_control pin_D7   ;output to the motor
DEF slow_pin   pin_D6   ;input to slow down motor
DEF fast_pin   pin_D5   ;input to speed up motor

;Function pulse_width_modulate send the output to the driver to control
;the motor.
FUNC none pulse_width_modulate
   PARAM word duty 
   LOCAL word accum 0w
   LOCAL word n 0w
   LOCAL word carry 0w
BEGIN
   WHILE <(n, 256w) 
      =(accum, +(accum, duty))
      =(carry, and(accum, 0x0100w))
      
      IF <>( carry, 0w)
         pin_high( dc_control )
      ELSE
         pin_low( dc_control )
      ENDIF

      =(accum, and(accum, 0x00ffw)) 
      ++( n )
   LOOP
ENDFUN

;***********************Main function**************************
FUNC none main()
  LOCAL word duty_cycle 128w
  LOCAL byte speed_up 0b
  LOCAL byte slow_down 0b
BEGIN
  pin_low(dc_control)  ;start with the motor off
  
  REP
    =(speed_up, and(pin_in(fast_pin), 1b))  ;get pin input
    =(slow_down, and(pin_in(slow_pin), 1b)) ;get pin input

    IF ==(speed_up, 0b)       ;if speed_up pin is active low, 
      
      =(duty_cycle, +(duty_cycle, 4w))  ;then speed up
    
    ELSEIF ==(slow_down, 0b)  ;if slow_down pin is active low
      
      IF >=(duty_cycle, 20w)  ;slow down, but not too salow
        =(duty_cycle, -(duty_cycle, 4w)) 
      ENDIF
    
    ENDIF
      
    pulse_width_modulate(duty_cycle)  ;run the motor
  
  LOOP

ENDFUN

;****************************************************************