This is what I have right now. But when the door is closed it reads less than 22 cm but sometimes a 0 as well. I understand that it is a misread but would like the door only to open when it is above 25 cm.
#include <Servo.h>
#include <NewPing.h>
/-----( Declare Constants and Pin Numbers )-----/
#define TRIGGER_PIN 2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 3 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define DOOR_OPEN 90 // Angle for Open Door
#define SERVO_PIN 11 // Servo plugs into Pin 11
/-----( Declare objects )-----/
Servo myservo; // create servo object to control a servo
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
/-----( Declare Variables )-----/
int pos; // variable to store the servo position
unsigned int uS;
unsigned int DistanceCm;
int DoorIsOpen;
void setup() /****** SETUP: RUNS ONCE ******/
{
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
myservo.attach(SERVO_PIN); // attaches the servo on pin 11 to the servo object
DoorIsOpen = 0;
myservo.write(10); //Door Start Position
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
delay(500); // Wait 500ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
DistanceCm = (uS / US_ROUNDTRIP_CM);
Serial.print(DistanceCm);
Serial.println("cm");
if (DistanceCm == 0 ) DistanceCm = 88; // Fix if bad reading
if (DistanceCm <= 22 and !DoorIsOpen)
{
Serial.println("???");
OpenDoor();
delay(1000);
}
if ((DistanceCm >= 25) && (DoorIsOpen))
{
Serial.println("!!!");
CloseDoor();
delay(1000);
}
}//--(end main loop )---
/-----( Declare User-written Functions )-----/
int OpenDoor()
{
for (pos = 10; pos <= DOOR_OPEN; pos += 5) // goes from 10 degrees to 160 degrees
delay(100);
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(69); // Wait 500ms between pings
}
DoorIsOpen = 1;
}
int CloseDoor()
{
for (pos = DOOR_OPEN; pos >= 10; pos -= 5) // goes from 160 degrees to 10 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(69);
}
DoorIsOpen = 0;
}