I am an artist creating an interactive sculpture and this is what I want to happen. When the viewer waves their hand within a specific distance range, an HC SR04 ultra sonic sensor triggers a 28byj-48 stepper motor, which turns 1.5 rotations clockwise, waits 2 seconds, then turns 1.5 rotations counter clockwise then stops. In the sketch listed below, the motor just runs continuously clockwise and when the sensor is triggered, the motor turns counter clockwise, then clockwise continuously (doesn't stop). The motor is not started by the sensor, just the direction is changed. How do I change the sketch to do what I want? Thanks for the help.
#define IN1 8
#define IN2 9
#define IN3 10
#define IN4 11
#define STEPS_PER_ROTATION 4096
const int pingPin = 12;
const int echoPin = 13;
unsigned int duration, inches;
void setup()
{
pinMode(12,OUTPUT);
pinMode(13,INPUT);
Serial.begin(9600);
Serial.println("File From Distance Test");
}
void ping() {
digitalWrite(pingPin, LOW); // Ensure pin is low
delayMicroseconds(2);
digitalWrite(pingPin, HIGH); // Start ranging
delayMicroseconds(5); // with 5 microsecond burst
digitalWrite(pingPin, LOW); // End ranging
duration = pulseIn(echoPin, HIGH); // Read echo pulse
inches = duration / 74 / 2; // Convert to inches
Serial.println(inches); // Display result
if ((inches>2) && (inches<18))
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
delay(100);
}
void loop() {
delay(50);
ping();
if ((inches>2) && (inches<18))
rotate(1.5);
delay(2000);
rotate(-1.5);
delay(2000);
}
void rotate(float rotations) {
rotate_steps(rotations * STEPS_PER_ROTATION);
}
int phase = 0;
byte phases[] = { 1, 3, 2, 6, 4, 12, 8, 9 };
void rotate_steps(int steps)
{
int dir = (steps > 0) - (steps < 0);
steps *= dir;
long laststep;
for (int i = 0; i < steps;) {
long now = micros();
if (now - laststep < 1000) continue;
laststep = now;
stepper_writepins(phases[phase]);
phase = (8 + phase + dir) % 8;
i++;
}
stepper_writepins(0);
}
void stepper_writepins(int bitmap) {
digitalWrite(IN1, bitmap & 8 ? HIGH : LOW);
digitalWrite(IN2, bitmap & 4 ? HIGH : LOW);
digitalWrite(IN3, bitmap & 2 ? HIGH : LOW);
digitalWrite(IN4, bitmap & 1 ? HIGH : LOW);
}