I've just started using Arduino and I need to make a code to simulate the behavior of a lizard, meaning that if you come close to it, it moves away from you.
I'm using a "Arduino duemilanove" that my university lend me, I was told that it was an alternative version of Arduino Uno.
Both of the servos says "Tower Pro, mg996r, digihi-speed"
Looking different codes I made one which I think is correct. Also, I checked for each servo motor (I'm using two) and the proximity sensor running codes for everyone of them alone, if they worked well and they did but with this code, they supposed to move when you are closer than a meter but they don't stop spinning.
If anyone could help me with this, it would be great.
Here is the code:
#define Servo1 9
#define Servo2 11
#define trigPin 10
#define echoPin A0
#include <Servo.h>
Servo servo1;
Servo servo2;
int pos = 0; // variable to store the servo position
void setup() {
Serial.begin (9600);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
pinMode(Servo1, OUTPUT);
pinMode(Servo2, OUTPUT);
servo1.attach(9);
servo2.attach(11);
}
void loop(){
long duracion, distancia; // variables
/* Hacer el disparo */
digitalWrite(10, LOW);
delayMicroseconds(2);
digitalWrite(10, HIGH); // Flanco ascendente
delayMicroseconds(10); // Duracion del pulso
digitalWrite(10, LOW); // Flanco descendente
/* Recepcion del eco de respuesta */
duracion = pulseIn(A0, HIGH);
/* Calculo de la distancia efectiva */
distancia = (duracion/2) / 29.1;
if (distancia<100){
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
servo1.write(pos); // tell servo to go to position in variable 'pos'
servo2.write(pos);
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
servo1.write(pos); // tell servo to go to position in variable 'pos'
servo2.write(pos);
delay(15); // waits 15ms for the servo to reach the position
}
}
else{
}
}
179 x 2 x 15 ms = 5.4 seconds
, which means every time distance is less than 1 meter, your servos will move during 5.4 seconds. Also note thatpulseIn
will return 0 if the sensor does not detect any obstacle within its range 5the range depends on the sensor you use, but it is typically 3 to 4 meters). – jfpoilpret Jun 9 '14 at 6:52