Hello!
I am very new to Arduino and trying to write a program that uses a Sainsmart ultrasonic sensor to detect distance and when the distance is shorter than 11 cm, then a servo will turn 180 degrees, and then back to 0 degrees after a one second delay, followed by a minute delay (or ideally, the program would shut down at that point).
I have combined code from a servo example and also from a ping example.
The inputs and outputs read fine. My problem is, if the sensor reads 11 cm or greater, I want the servo to do nothing at all, and just delay .1 seconds. If the sensor reads 10 cm or less, I want the servo to move 180 degrees and then back to the original position and stop the loop, or at least wait one minute at that point.
Here is the code I have put together so far. Any help would be appreciated.
#include <Servo.h>
// Pin number constants
const int triggerPin = 5;
const int echoPin = 6;
Servo servo1;
void setup() {
// initialize serial communication:
Serial.begin(9600);
servo1.attach(9);
}
void loop()
{
int position;
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, feet, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(5);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
if (cm >= 11)
delay(100);
if (cm < 11)
servo1.write(180);
delay(1000);
servo1.write(0);
delay(60000);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
moderator update: added code tags - # button above the smileys