Stepper Contol



//////////////////////////
// stepper motor pins:
// PORTA 4, 5, 6, 7
// stop button pins:
// PORTB 5, 6
// direction switch pin:
// PORTB 4
//////////////////////////

#include <avr/io.h>
#define F_CPU 1000000UL
#include <util/delay.h>
#include <math.h>

#define STPORT PORTA
#define STPIN1 PORTA4
#define STPIN2 PORTA5
#define STPIN3 PORTA6
#define STPIN4 PORTA7

#define LED PORTA2

#define DIR PORTB4
#define BUTTON1 PORTB5
#define BUTTON2 PORTB6

int button_pressed(int n, unsigned int time);
void delay_ms(unsigned int n);
void odelay_ms (unsigned int n);
void change(char a, char b, char c, char d);

int main (void) {
	
	//set portA pins 4 to 7 as out
	DDRA |= 0xFF;
	STPORT |= 0x00;
	
	//set buttons to input
	DDRB |= 0x00;
	
	//enable internal pull up resistor
	PORTB |= (1<<BUTTON2) | (1<<BUTTON1) | (1<<DIR);
	
	//led to high, ie off
	PORTB |= (1<<LED);
	
	//turn on a to d conversion
	ADCSR |= (1<<ADEN);
	
	//prescale 8 so we get 125000Hz sampling
	ADCSR |= (1<<ADPS1) | (1<<ADPS0);
	
	//set analog input to ADC0 (PA0) 
	ADMUX = 0x00;

	unsigned int input = 0;
	char stop1 = 0;
	char stop2 = 0;
	char dir = 0;
	
	for (; ;) {
		
		ADCSR |= (1<<ADSC); // start conversion
		while (ADCSR & (1<<ADSC)); //wait until it is finished
		
		// Get ADC the result, both bytes
		input = ADCL;
		input += (ADCH << 8);
		
		
		dir = 0;
		if(bit_is_clear(PINB, DIR)) {
			dir = 1;			
		}
		
		//these are for the directions
		stop1 = 0;
		stop2 = 0;
		
		if (dir == 0) {
			if(button_pressed(BUTTON1, 50)) {
				stop2 = 1;
			}
		}
		else {
			if (button_pressed(BUTTON2, 50)) {
				stop1 = 1;
			}
		}

		
		if (dir) {
			if (!stop1) {
				change(1, 0, 1, 0);
				delay_ms(input);
				change(0, 1, 1, 0);
				delay_ms(input);
				change(0, 1, 0, 1);
				delay_ms(input);
				change(1, 0, 0, 1);
				delay_ms(input);
				PORTA |= (1<<LED);
			}
		}
		else {
			if (!stop2) {
				change(1, 0, 0, 1);
				delay_ms(input);
				change(0, 1, 0, 1);
				delay_ms(input);
				change(0, 1, 1, 0);
				delay_ms(input);
				change(1, 0, 1, 0);
				delay_ms(input);
				PORTA &= ~(1<<LED);
			}
		}
		
	}
		
	return 0;
}

int button_pressed(int n, unsigned int time) {
	if (bit_is_clear(PINB, n)) {
		odelay_ms(time);
		if (bit_is_clear(PINB, n)) {
			return 1;
		}
	}
	return 0;
}

void delay_ms (unsigned int n) {
	unsigned int m = n;
	unsigned int o = n;
	while (n) {
		while (m) {
			while (o) {
				_delay_ms(0.03);
				o--;
			}
			m--;
		}
		n--;
	}
}

void odelay_ms (unsigned int n) {
	while (n) {
		_delay_ms(0.96);
		n--;
	}

}

void change (char a, char b, char c, char d) {

	if (a == 0) STPORT |= (1<<STPIN1);
	else STPORT &=	~(1<<STPIN1);
	if (b == 0) STPORT |= (1<<STPIN2);
	else STPORT &=	~(1<<STPIN2);
	if (c == 0) STPORT |= (1<<STPIN3);
	else STPORT &=	~(1<<STPIN3);
	if (d == 0) STPORT |= (1<<STPIN4);
	else STPORT &=  ~(1<<STPIN4);
	
}