Hello everyone
I am currently in the process of a school project, and I need some help.
My basic components are; a stepper motor, an ultrasonic sensor, and a breadboard.
I am not completely new to using an Arduino board, but not exactly experienced either. My assignment basically boils down to making a motor move if the distance to an object changes. I have tried a lot of things now, but none of them seemed to work.
The current code I have worked out is this:
#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() {
 dist();
//This function vill show the distance (ctrl + M).
 accel();
//This function was supposed to turen the only motor when the
//distance changes
}
void dist(){
Â
 long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 4){
Serial.println("STOP");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
}
void accel(){
Â
 long duration, distance, dist1, dist2;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
dist1 = (duration/2) / 29.1;
dist2 = dist1 - ((pulseIn(echoPin, HIGH)/2) / 29.1);
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);
 }
}
}
Can anybody tell me what I am doing wrong?