Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Goal is to create an arduino program that turns on a stepper motor with a sound sensor and it rotate continuously until a magnet sensor

Goal is to create an arduino program that turns on a stepper motor with a sound sensor and it rotate continuously until a magnet sensor is activated and it shuts off. Then once the sound sensor is activated again it goes into the reverse direction until it approaches the other magnet.
Why isn't my code working?
Code:
#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
unsigned long lastStepTime =0; // Time of last step
unsigned long debounceDelay =50; // Debounce delay in milliseconds
void setup(){
pinMode(soundPin, INPUT);
pinMode(magnetPin1, INPUT_PULLUP);
pinMode(magnetPin2, INPUT_PULLUP);
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) && digitalRead(magnetPin1)){
// Sound detected, not at stopping position, and not at initial position
moveForward();
} else if (soundVal >500 && !digitalRead(magnetPin1) && digitalRead(magnetPin2)){
// Sound detected, not at initial position, and at stopping position
moveBackward();
}
}
void moveForward(){
while (digitalRead(magnetPin2)){// Keep moving until stopping position is reached
if (millis()- lastStepTime >= debounceDelay){
myStepper.step(1);
lastStepTime = millis();
}
}
}
void moveBackward(){
while (digitalRead(magnetPin1)){// Keep moving until initial position is reached
if (millis()- lastStepTime >= debounceDelay){
myStepper.step(-1);
lastStepTime = millis();
}
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Joe Celkos Data And Databases Concepts In Practice

Authors: Joe Celko

1st Edition

1558604324, 978-1558604322

More Books

Students also viewed these Databases questions