;
; program to make a h bridge out of a tiny13
;
; 
; definitions
;
.include "tn13def.inc"
.def temp = R16	; temporary storage
.def temp1 = R17 ; temporary storage
.def temp2 = R18 ; temporary storage
.def direction = R19 

;.equ pwmpin = PB4 ;upper
;.equ dirpin = PB3  
.equ pwmpin = PB3 ;lower
.equ dirpin = PB4 
.equ leftFets = PB2
.equ rightFetP = PB1
.equ rightFetN = PB0
;.equ safetypin = PB0

.cseg
.org 0
rjmp reset


;
; main program
;
reset:	   
	;
	; initialization
	;
	ldi temp, low(RAMEND)
	out SPL, temp ; set stack pointer to top of RAM
	ldi temp, (1<<CLKPCE)
	ldi temp1, ((0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0))
	out CLKPR, temp ; write CLKPCE to change clock prescaler
	out CLKPR, temp1 ; set clock to 9.6MHz/1

	in temp, MCUCR ;disable pullups
	ori temp, PUD
	out MCUCR, temp
	
	;cbi PORTB, forwardpin ; set to off
	;sbi DDRB, forwardpin ; enable as output
	;cbi PORTB, backpinN ; 
	;sbi DDRB, backpinN ; turn off lower back
	
	cbi PORTB, leftFets
	sbi DDRB, leftFets
	
	cbi PORTB, rightFetN
	sbi DDRB, rightFetN

	cbi PORTB, rightFetP
	;sbi DDRB, rightFetP

	;sbi DDRB, safetypin ; enable the fet area
	;sbi PORTB, safetypin
	
	;cbi DDRB, backpin
	;sbi DDRB, forwardpin
	
	LOOP:
		;rjmp LOOP
		ldi direction, 0
		sbic PINB, dirpin
			ldi direction, 1
		cpi direction, 0
		brne FORWARD
			;backwards - upper right and lower left should be on
			;sbi DDRB, forwardpin ;brind down the forwards
			cbi PORTB, rightFetN ; set lower right to ground, disabling
			cbi DDRB, leftFets ; dis-engage output of this pin, left fets go up via pullup, P off N on 
			sbis PINB, pwmpin
				;sbi DDRB, backpin ; do this if we should be OFF (based on pwm)
				cbi DDRB, rightFetP ; dis-engage output of this pin, voltage for P pulled up and off
			sbic PINB, pwmpin
				;cbi DDRB, backpin ; do this if we should be ON (based on pwm)
				sbi DDRB, rightFetP ; engage output of this pin, voltage for P pulled down and it turns on
			rjmp LOOP
		FORWARD:
			;sbi DDRB, backpin ;brind down the backwards
			cbi DDRB, rightFetP ;disable pin, fet pulled to +v and off
			sbi DDRB, leftFets ;pull left fets down, enabling P disabling N
			sbis PINB, pwmpin
				;sbi DDRB, forwardpin ;do this if we should be OFF
				cbi PORTB, rightFetN
			sbic PINB, pwmpin
				;cbi DDRB, forwardpin ;do this if we should be ON
				sbi PORTB, rightFetN
			rjmp LOOP