xingcontrol/stepper.c
2019-10-18 22:08:59 +02:00

100 lines
2.0 KiB
C
Executable File

//stepper motor functions
#define F_CPU 16000000UL
#include <avr/io.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "usart.h"
// QOL macros
#define setb(port,pin) port |= 1<<pin //set bit
#define clrb(port,pin) port &= ~(1<<pin) //clear bit
#define negb(port,pin) port ^= 1<<pin //negate bit
int steps;
int current_step;
int i;
char tmp[100];
void motor_hold(void){
PORTB = 0b00001010; //energize opposite windings to prevent movement.
};
void motor_free(void){
PORTB = 0x00; //do not power any winding making the rotor free to rotate (no holding torque!)
};
int motor_step(int steps){
if(steps > 0){
//move clockwise
for(i = 0;i <= steps;i++){
current_step = i % 4; //perform required part of rotation -- provides full resolution of 1.8deg per step
/*
//debug info
sprintf(tmp,"current_step %d\r\n",current_step);
USART_putstring(tmp);
*/
//energize windings in required order -- delay controls speed
switch(current_step){
case 0:
PORTB = 0b00001010;
_delay_ms(5);
break;
case 1:
PORTB = 0b00001100;
_delay_ms(5);
break;
case 2:
PORTB = 0b00010100;
_delay_ms(5);
break;
case 3:
PORTB = 0b00010010;
_delay_ms(5);
break;
};
};
}
if(steps < 0){
//step counterclockwise when negative value is entered
for(i = steps;i <= 0;i++){
//mod is negative when calculated from negative number for some reason, this takes care of that
current_step = (i % 4) * -1;
/*
//debug info
sprintf(tmp,"current_step %d\r\n",current_step);
USART_putstring(tmp);
*/
switch(current_step){
case 0:
PORTB = 0b00001010;
_delay_ms(5);
break;
case 1:
PORTB = 0b00001100;
_delay_ms(5);
break;
case 2:
PORTB = 0b00010100;
_delay_ms(5);
break;
case 3:
PORTB = 0b00010010;
_delay_ms(5);
break;
};
};
}
else {
motor_hold();
};
return i; //return number of steps made -- not in use atm
};