Question: I have the following arduino code to program a car to move when it gets signalled by a sound sensor and stops when it reaches

I have the following arduino code to program a car to move when it gets signalled by a sound sensor and stops when it reaches a magnet sensor. The car should move foward when signalled by sound sensor then stop when it reaches magnet sensor in front. Then when signalled again by the sound sensor it should move backeards to the magnet sensor that was at its original position. What am I missing? What should I improve?
Code I have to far:
#include
const int soundPin =2; // Analog pin for microphone sensor
const int magnetPin1=3; // Digital pin for initial position magnet
const int magnetPin2=4; // Digital pin for stopping position magnet
const int stepsPerRevolution =2048; // Steps per revolution for 28BYJ-48 stepper motor
Stepper myStepper(stepsPerRevolution,8,9,10,11); // Define stepper motor pins
int speed =100; // Stepper motor speed
void setup(){
pinMode(soundPin, INPUT);
pinMode(magnetPin1, INPUT);
pinMode(magnetPin2, INPUT);
myStepper.setSpeed(speed);
}
void loop(){
int soundVal = analogRead(soundPin); // Read microphone sensor value
// Check for sound and magnet sensor states
if (soundVal >500 && !digitalRead(magnetPin2)){// Sound detected and not at stopping position
moveForward();
} else if (soundVal >500 && digitalRead(magnetPin2)){// Sound detected and at stopping position
moveBackward();
} else {
myStepper.stop(); // Stop motor if no sound or at initial position
}
}
void moveForward(){
myStepper.step(stepsPerRevolution); // Move forward one revolution
delay(2000); // Delay for 2 seconds
}
void moveBackward(){
myStepper.step(-stepsPerRevolution); // Move backward one revolution
delay(2000); // Delay for 2 seconds
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!