I am trying to create a circuit that will turn my motor when I clap. When the first limit switch is low, and there is only one clap, a solenoid pin is supposed to be engaged (currently an LED), but when I clap once without pressing the limit switch, my LED turns on.
Also, I can't seem to get my code to work properly with the limit switches, to control my motor.
I am not sure what is wrong, can someone help?
I have an Arduino Uno with the following code:
#define sound_Sensor 2
#define EN1 9
#define IN1 8
#define IN2 7
#define solenoid_pin 6
#define LimSwitch1 4
#define LimSwitch2 3
int lastSoundValue;
int soundValue;
long lastNoiseTime = 0;
long currentNoiseTime = 0;
int solenoidPinStatus = LOW;
int status_motor = LOW;
int clap_interval = 200;
int claps = 0;
int pos1 = 1;
int pos2 = 1;
void setup() {
pinMode(sound_Sensor, INPUT);
pinMode(EN1, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(solenoid_pin, OUTPUT);
pinMode(LimSwitch1, INPUT);
pinMode(LimSwitch2, INPUT);
}
void loop() {
soundValue = digitalRead(sound_Sensor);
currentNoiseTime = millis();
if (soundValue == 1 && lastSoundValue == 0 && (currentNoiseTime > lastNoiseTime + 200))
{
if (claps == 0) // allow first to register without much condition
{
claps = 1;
lastNoiseTime = currentNoiseTime;
}
else
{
if (currentNoiseTime > lastNoiseTime + clap_interval)
{
claps++;
lastNoiseTime = currentNoiseTime;
}
}
Serial.print(claps);
}
else
{
if (currentNoiseTime > (lastNoiseTime + 3 * clap_interval)) // no claps for a longer duration time to print and/or reset clap
{
if (claps > 0)
{
while(status_motor == LOW){
if (digitalRead(LimSwitch1) == LOW && claps == 1)
{
solenoidPinStatus = HIGH;
digitalWrite(solenoid_pin, HIGH);
}
if (digitalRead(LimSwitch1) == LOW)
{
pos1 = 2;
status_motor = HIGH;
digitalWrite(IN1, HIGH); //Turns on Motor
digitalWrite(IN2, LOW);
analogWrite(EN1, 200); //Set Speed of Motor
}
else if (digitalRead(LimSwitch2) == LOW)
{
pos2 = 2;
status_motor = HIGH;
digitalWrite(IN1, HIGH); //Turns on Motor99++
digitalWrite(IN2, LOW);
analogWrite(EN1, 200); //Set Speed of Motor
}
}
while(status_motor == HIGH){
if (pos1 == 2 && digitalRead(LimSwitch2) == LOW)
{
status_motor = LOW;
digitalWrite(IN1, LOW); //Turns on Motor
digitalWrite(IN2, LOW);
pos1 = 1;
}
else if (pos2 == 2 && digitalRead(LimSwitch1) == LOW)
{
status_motor = LOW;
digitalWrite(IN1, LOW); //Turns on Motor
digitalWrite(IN2, LOW);
pos2 = 1;
}
}
}
claps = 0; ///reset
}
}
// if (solenoidPinStatus == HIGH && status_motor == LOW && digitalRead(LimSwitch1) == LOW)
// {
// solenoidPinStatus = LOW;
// digitalWrite(solenoid_pin, LOW);
// }
lastSoundValue = soundValue;
}
Sorry my wire diagram may not be the easiest to look at...