Hey guys i need help with my code.
Im trying to make the stepper motor constantly rotate clockwise and then counterclockwise until the ultrasonic sensor detects an object at 20cm or less; once it hits < 20 I want the motor to stop and the passive buzzer to beep, then after a short delay to continue moving again clockwise to counterclockwise.
For some reason as soon as i add the stepper motor code the monitor that detects the sensor is delayed. Right now the motor moves when it detects something it stops, plays the beeps but wont continue moving again as the serial monitor just stop detecting anything
#include "SR04.h"
#include "pitches.h"
#include <Stepper.h>
#define TRIG_PIN 12
#define ECHO_PIN 11
SR04 sr04 = SR04(ECHO_PIN,TRIG_PIN);
long a;
int melody[] = { //beep 8 times when <20
NOTE_DS3, NOTE_DS3, NOTE_DS3, NOTE_DS3, NOTE_DS3, NOTE_DS3, NOTE_DS3, NOTE_DS3};
int duration = 50; //how long each beep sound is
const int stepsPerRevolution = 950; // when the motor changes rotation
const int rolePerMinute = 15; // Adjustable range of 28BYJ-48 stepper is 0~17 rpm
// initialize the stepper library on pins 2 through 5:
Stepper myStepper(stepsPerRevolution, 2, 4, 3, 5);
void setup() {
myStepper.setSpeed(rolePerMinute);
Serial.begin(9600);
delay(1000);
}
void loop() {
myStepper.step(stepsPerRevolution); //rotates clockwise
myStepper.step(-stepsPerRevolution); //totates counter clockwise
a=sr04.Distance(); //detects distance on serial monitor
Serial.print(a); //prints the distance
Serial.println("cm");
delay(200);
if (a < 20) {
for (int thisNote = 0; thisNote < 8; thisNote++) {
tone(8, melody[thisNote], duration); //plays the melody when <20
delay(100);
}
myStepper.setSpeed(0); //stops the motor when <20
}
else {
myStepper.setSpeed(rolePerMinute); //replays the rotating motor loop when >20
}
delay(200);
}

