Hello, I’m having trouble with my code. My goal is to have the motor do nothing when nothing is pressed. When I push button1 it starts a continuous loop and stops at any moment when button2 is pressed. It then waits for button1 to be pressed again to start the loop over.
In the loop: the motor will slowly turn clockwise for .2seconds, delays for .5seconds, continuously rotates until the IR module receives a voltage (detects an object), the motor stops for 3 seconds, then repeats. I have the IR spit out numbers constantly to help me calibrate the sensor.
The trouble I’m having is when the arduino receives power, it automatically starts the loop and nothing can cancel it.
// Pin assignments
const int dirPin = 2;
const int stepPin = 3;
const int buttonPin1 = 5;
const int buttonPin2 = 7;
const int irPin = 6;
// Motor variables
const int motorSpeed = 200; // Steps per second
const int motorDelay = 2000; // Motor delay in milliseconds
// Flags to track the state of loop1 and button2
bool loop1Active = false;
bool button2Pressed = false;
void setup() {
// Initialize pins
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(buttonPin1, INPUT_PULLUP);
pinMode(buttonPin2, INPUT_PULLUP);
pinMode(irPin, INPUT_PULLUP);
// Set initial motor direction
digitalWrite(dirPin, HIGH);
// Start serial communication
Serial.begin(9600);
}
void loop() {
// Check if button1 is pressed to start loop1
if (digitalRead(buttonPin1) == LOW) {
// Button1 pressed, start loop1
loop1Active = true;
// Delay for 1 second
delay(1000);
}
if (loop1Active) {
// Turn motor clockwise slowly for 0.2 seconds
for (int i = 0; i < motorSpeed; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(motorDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(motorDelay);
}
// Delay for 0.5 seconds
delay(500);
// Continuously turn motor clockwise slowly until IR output is 1
while (digitalRead(irPin) == HIGH) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(motorDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(motorDelay);
}
// Check if button2 is pressed
if (digitalRead(buttonPin2) == LOW) {
// Button2 pressed, stop loop1
loop1Active = false;
button2Pressed = true;
}
// Check if IR output is 1
if (digitalRead(irPin) == HIGH) {
// IR detected, stop the motor
digitalWrite(stepPin, LOW);
}
} else {
// Read IR sensor value
int irValue = digitalRead(irPin);
// Check if IR output is 1
if (irValue == HIGH) {
// IR detected, stop the motor
digitalWrite(stepPin, LOW);
}
}
// Print IR sensor value to Serial monitor
int irValue = digitalRead(irPin);
Serial.print("IR Sensor: ");
Serial.println(irValue);
// Check if button2 was pressed during loop1
if (button