; ************************************
; * Interface a stepping motor
; * By PEK '2000
; *
; * Send the follow values to motor
; * 100 times/s:
; *
; * 1001
; * 0011
; * 0110
; * 1100
; * 1001 and so on.....
; *
; * Press D0 resp. D1 to choose
; * direction and run the motor.
; *
; * Use a 4 MHz crystal!!!
; ************************************


.include "8515def.inc"


; ************************************
; * Register and Constant Definitions             
; ************************************
.def	temp	=R16
.def	motor	=R17


; ************************************
; * Start of Code                    
; ************************************
.cseg
.org 0
	rjmp	Start
.org 4
	rjmp	Timer			; Timer1 CompareA Handler


Start:
	ldi	temp,low(RAMEND)
	out	SPL,temp		; Set stack pointer to last internal RAM location
	ldi	temp,high(RAMEND)
	out	SPH,temp

	ldi	temp,0x00
	out	DDRD,temp		; Port D as input
	ldi	temp,0xFF
	out	PORTD,temp		; Enable Pull-Up

	ldi	temp,0xFF
	out	DDRC,temp		; Port C as output
	ldi	motor,0b10011001
	out	PORTC,motor		; Initial value on motor

	ldi	temp,0
	out	TCCR1A,temp		; Disable Compare Output Mode and PWM
	ldi	temp,0x0B
	out	TCCR1B,temp		; Enable CTC1 and CK/64
	ldi	temp,0x40	
	out	TIMSK,temp		; Enable T/C Output CompareA Match Interrupt
	ldi	temp,2
	out	OCR1AH,temp		; 16-bit Counter compare value (10 msek at 4 MHz (CK/64))
	ldi	temp,113		; (113 + 2*256)*64
	out	OCR1AL,temp

	sei				; Enable global interrupts


Loop:
	rjmp	Loop


Timer:
	ldi	temp,0x00		; Save some power if motor
	out	PORTC,temp		; not running.
	sbis	PIND,0
	rcall	Move_Right
	sbis	PIND,1
	rcall	Move_Left
	reti


; ************************************
; * Move stepping motor to the left
; ************************************
Move_Left:
	lsl	motor			; Shift left to next motor-value
	brcc	Move_Left_Q
	ori	motor,0b00000001
Move_Left_Q:
	out	PORTC,motor		; Send value to motor
	ret

; ************************************
; * Move stepping motor to the right
; ************************************
Move_Right:
	lsr	motor			; Shift right to next motor-value
	brcc	Move_Right_Q
	ori	motor,0b10000000
Move_Right_Q:
	out	PORTC,motor		; Send value to motor
	ret
