Parts:
Stepper Motor (1.8 degrees per step)
GP2D15 IR Sensor
I am trying to write a program that rotates the stepper motor 360 degrees from 10 cm to 80 cm (the effective range on our IR Sensor). If you start at 10 cm and move 80 cm away from the IR sensor, the stepper motor should have rotated a full 360 degrees. The catch is, though, that if you stop moving away from the sensor, the motor will stop spinning. Then, if you start to move closer to the IR sensor it will reverse directions and rotate the other way until it returns to its original position at 10 degrees.
I have the IR sensor working properly, with a distance equation and everything. I also have the code to get the stepper motor to spin 360 degrees using 1/8th of a step. The problem I am having is getting them to work together to spin 360 degrees, reverse, and stop.
This is the code we have currently:
int step_pin = 3;
int dir_pin = 2;
float IRsens;
float voltage;
float distance;
float dist_new;
float dist_old;
float dir;
void setup()
{
Serial.begin(9600);
pinMode(3,OUTPUT);
pinMode(2,OUTPUT);
}
void loop()
{
//delay(500);
for(int i=0; i <=1600 ; i++)
{
IRsens = analogRead(0);
voltage = IRsens * 5/1023;
distance = 106.02*exp(-1.117*voltage);
dist_new = distance;
dir = (dist_new - dist_old);
Serial.print("Distance cm = ");
Serial.println(distance);
Serial.print("Distance cm = ");
Serial.println(dist_new);
Serial.print("Distance cm = ");
Serial.println(dist_old);
Serial.print("Direction = ");
Serial.println(dir);
Serial.println(" ");
delay(1000);
if (dir > 0)
{
digitalWrite(dir_pin, HIGH);
digitalWrite(step_pin, LOW);
delay(10);
digitalWrite(step_pin, HIGH);
delay(10);
}
if (dir < 0)
{
digitalWrite(dir_pin, LOW);
digitalWrite(step_pin, LOW);
delay(10);
digitalWrite(step_pin, HIGH);
delay(10);
}
if (dir == 0)
{
digitalWrite(dir_pin, LOW);
digitalWrite(step_pin, LOW);
delay(10);
digitalWrite(step_pin, LOW);
delay(10);
}
dist_old = dist_new;
}
}