Hello everyone,
I have been messing around with a 400 Step Stepper motor. I am trying to allow my code to read input from the serial input and from that input manipulate my stepper motor.
When I test the function by manually writing a value for the steps in the program and run it, it works as it should. However when I try to add in to read from serial input the function does not work properly. I am assuming it has something to do with reading from the serial port. I need it to read only when a new value is input. May someone please help me.
#define DIR_PIN 2
#define STEP_PIN 3
float in;
void setup() {
Serial.begin(9600);
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
}
void loop(){
if(Serial.available() > 0){
in = Serial.read();
//rotate a specific number of degrees
// rotateDeg(360, 1);
//delay(1000);
// rotateDeg(in, .5); //reverse
//delay(1000);
//rotate a specific number of microsteps (8 microsteps per step)
//a 400 step stepper would take 3200 micro steps for one full revolution
rotate(in, .5);
delay(1000);
Serial.println(in);
}
}
void rotate(int steps, float speed){
//rotate a specific number of microsteps (8 microsteps per step) - (negitive for reverse movement)
//speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger
int dir = (steps > 0)? HIGH:LOW;
steps = abs(steps);
digitalWrite(DIR_PIN,dir);
float usDelay = (1/speed) * 70;
for(int i=0; i < steps; i++){
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(usDelay);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(usDelay);
}
}
void rotateDeg(float deg, float speed){
//rotate a specific number of degrees (negitive for reverse movement)
//speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger
int dir = (deg > 0)? HIGH:LOW;
digitalWrite(DIR_PIN,dir);
int steps = abs(deg)*(1/.1125); //For 400 steps
float usDelay = (1/speed) * 70;
for(int i=0; i < steps; i++){
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(usDelay);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(usDelay);
}
}