A few weeks ago I was looking for a code that turned ON a DC motor when a sound reaches over a certain threshold, otherwise the DC motor would be OFF.
I compiled my own code, and thought I would share in case someone out there is looking for the same thing:
/*
DC Motor Controlled by Mic
by Jess Fügler
June 2009
When the microphone recieves a sound over the programmed threshold, the motor will turn on.
*/
// Set the pin numbers:
int knockSensor = 0; // Mic in Analog 0
byte val = 0; // variable to store the value read from the sensor pin
int motor1Pin = 3; // H-bridge leg 1 (pin 2, 1A)
int motor2Pin = 4; // H-bridge leg 2 (pin 7, 2A)
int speedPin = 9; // H-bridge enable pin
int ledPin = 13; // LED
int THRESHOLD = 15; // the threshold the sound must surpass to turn on motor
int statePin = LOW;
void setup() {
// initialize the knock sensor as an input:
pinMode(knockSensor, INPUT);
// set all the other pins you're using as outputs:
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(speedPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop(){
// to turn motor on:
// digitalWrite(speedPin, HIGH);
// read delay value from analog input (microphone)
val = analogRead(knockSensor); // read the sensor and store it in the variable "val"
// if the sound is over THRESHOLD, motor will turn on:
// if value is over threshold, turn motor on:
if (val >= THRESHOLD) {
digitalWrite(motor1Pin, HIGH); //set leg 1 of the H-bridge low
digitalWrite(motor2Pin, LOW); //set leg 2 of the H-bridge high
digitalWrite(speedPin, HIGH);
}
// if the sound is under the THRESHOLD, motor will turn off:
else {
digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low
digitalWrite(speedPin, HIGH);
}
}
If you use it, or modify it, I would love to see what you're working on!