Sonic_Servo

sonic_sensor

#include <Servo.h>
const int pingPin = 7;
const int servoPin = 9;
Servo servo;
int angle;

void setup(){
Serial.begin(9600);
servo.attach(servoPin);
}

void loop(){
long duration, cm, cm2;

pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);

pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

cm = microsecondsToCentimeters(duration);

if(cm<40){
cm2 = 40 – cm;

angle = map(cm2, 0, 40, 0, 254);
servo.write(angle);
// analogWrite(servoPin, moveValue);
}
else{
analogWrite(servoPin, 0);
}

// int reading = analogRead(pingPin);
// int angle = reading / 6;
// servo.write(angle);

Serial.print(cm);
Serial.print(“cm”);
Serial.println();
Serial.print(“angle :”);
Serial.print(angle);

Serial.println();

delay(20);

}

long microsecondsToCentimeters(long microseconds){
return microseconds / 29/ 2;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s