 TITLE  "SunFlower"        	; sunflower robot
 List P=12F675, R=DEC
 INCLUDE "p12F675.inc"

; data segment
 CBLOCK 0x20                   
 del  						; variable used for delays 
 n1, n2						; sensor values
 ENDC

; code segment
 __CONFIG _BODEN_OFF & _CPD_OFF & _CP_OFF & _MCLRE_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT
; __CONFIG b'110000100'		; binary version of config 
  ORG 0                   	; start program at the beginning of mem
	goto	start
  ORG 4
start
	bcf		STATUS, RP0 	; activale BANK 0
	clrf	GPIO			; initialize GPIO
	clrf 	INTCON			; disable all interrupts
	movlw	0x07
	movwf	CMCON			; comparator OFF
	clrf	ADCON0			; ADC OFF
  	bsf    	STATUS, RP0    	; change to BANK 1
	clrf	ANSEL ^ 0x80 	; turn off ADC
	clrf	PIE1 ^ 0x80		; disable external interrupts
	clrf	IOC 			; disable interrupt on change	
	clrf	WPU
	bsf		OPTION_REG ^0x80, 7 	; disable pull-ups 
	movlw	b'001100'		
	movwf	TRISIO ^ 0x80	; enable GP<3,2> for input
  	bcf    	STATUS, RP0    	; back to BANK 0

loop
	call 	measure			; get n1 and n2

	movlw	b'011110'
	andwf	GPIO, f 		; motor stop

	movf	n2, w			; w = n1 - n2
	subwf	n1, w			
	btfss	STATUS, C
	 sublw	0				; w = |n1 - n2|
	sublw	15				; w = 15 - w
	btfsc	STATUS, C		
	 goto 	L3				; diff is small - continue

	movf	n2, w
	subwf	n1, w
	btfss	STATUS, C
	 goto 	L1	
	movlw	b'000001'
	 goto 	L2
L1	movlw	b'100000'
L2	iorwf	GPIO, f	

L3	movlw	50				; 50 msec delay
	movwf	del
	call	delay
  	goto 	loop			; endless loop


; procedures
delay						; a delay for del milliseconds
	movlw 	200
	
	sublw	1				; this loop takes 5us*200 = 1ms
	sublw	0				; for PIC12F675 @ 4 Mhz
	btfss	STATUS, Z
	 goto 	$-3

	decfsz	del, f
	 goto 	delay
	return

measure						; read light sensors
	clrf	n1	
	movlw	b'010000'		
	iorwf	GPIO, f			; take cap high
		
M1	incf	n1, f			; start the first light measurement
 	movlw	255
	subwf	n1, w
	btfsc	STATUS, Z
	 goto	M2
	btfsc	GPIO, 3			; is input low ?
	 goto	M1				; back to loop

M2	movlw	b'101101'
	andwf	GPIO, f			; discharge the cap
	clrf	n2
	movlw	b'000010'
	iorwf	GPIO, f			; take cap high
	
M3	incf	n2, f			; start the second measurement
 	movlw	255
	subwf	n2, w
	btfsc	STATUS, Z
	 goto	M4
	btfsc	GPIO, 2			; is input low ?
	 goto	M3				; back to loop

M4	movlw	b'101101'
	andwf	GPIO, f			; discharge the cap	
	return

 END
