And I have definitely misunderstood something
You certainly have.
I gave you function that returns a distance, and you called the function, but threw away the distance.
#define trigPin 4
#define echoPin 5
#include <Stepper.h>
const int stepsPerRevolution = 400; //number of steps per
//revolution for your motor
// initialize the stepper library on the motor shield
Stepper myStepper(stepsPerRevolution, 12,13);
// give the motor control pins names:
const int pwmA = 3;
const int pwmB = 11;
const int brakeA = 9;
const int brakeB = 8;
const int dirA = 12;
const int dirB = 13;
const int STOP = 0;
int x = 0;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pwmA, OUTPUT);
pinMode(pwmB, OUTPUT);
pinMode(brakeA, OUTPUT);
pinMode(brakeB, OUTPUT);
digitalWrite(pwmA, HIGH);
digitalWrite(pwmB, HIGH);
digitalWrite(brakeA, LOW);
digitalWrite(brakeB, LOW);
// initialize the serial port:
Serial.begin(9600);
// set the motor speed (for multiple steps only):
myStepper.setSpeed(75);
}
void loop() {
accel();
}
unsigned long dist()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
return (pulseIn(echoPin, HIGH) / 2) / 29.1;
}
void accel(){
unsigned long distance = dist ();
// some considerable time later (to allow all the echoes to die-away)
unsigned long dist2 = dist ();
Serial.print (F("distance = "));
Serial.println (distance);
Serial.print (F("dist2 = "));
Serial.println (dist2);
if (dist1 < 20){
if (dist2 < 0){
myStepper.setSpeed(75);
myStepper.step(-4);
}
else if (dist2 == 0){
myStepper.setSpeed(STOP);
}
else {
myStepper.setSpeed(75);
myStepper.step(4);
}
}
else {
if (dist2 < 0){
myStepper.setSpeed(75);
myStepper.step(4);
}
else if (dist2 == 0){
myStepper.setSpeed(STOP);
}
else {
myStepper.setSpeed(75);
myStepper.step(-4);
}
}
}