Hi, I previously use the switch to turn a LED on, base on the distance measured from the SR04 sensor and when press the button again it turns off the LED regardless of the distance.
I am replacing the LED with the motor and change the digitalWrite to AnalogWrite(motor, 50) to slow down the speed of the motor.
However, as soon as I hook up the motor, it spins at max speed right away without me doing anything else. Am I allow to do this? or would I have to do something when using the dc motor instead of the LED?
#define trigPin 12
#define echoPin 11
#define on_button 9
#define motorPin 8
int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value of "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(on_button, INPUT);
pinMode(motorPin, OUTPUT);
}
void loop(){
val = digitalRead(on_button); // read input value and store it
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
delay(10);
}
old_val = val; // val is now old, store it
long distance, duration;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (state == 1 && distance > 3) {
analogWrite(motorPin, 50); // turn motor ON
} else {
analogWrite(motorPin, LOW);
}
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
https://fbcdn-sphotos-d-a.akamaihd.net/ … cd63a9bf71
I followed this to hook up the motor: (sry i dont know how to make a schematic like this for the above set up)
http://oi59.tinypic.com/2jb0cjl.jpg
Thanks a lot for your help.