Hello, my friend and I are creating a box that opens when you approach it. We are using a servo motor to open it and an ultrasonic sensor to detect when you get near. This is our first project so we don't know what's wrong with the code. The code is down below.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
Serial.begin(9600);
pinMode(9, OUTPUT);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
int distanceThreshold = 0;
int cm = 0;
int inches = 0;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void loop()
{
0.01723 * readUltrasonicDistance(0, 0);
distanceThreshold = 50;
cm = 0.01723 * readUltrasonicDistance(7, 6);
inches = (cm / 2.54);
Serial.print(cm);
Serial.print("cm,");
Serial.print(inches);
Serial.print("in");
if (cm > distanceThreshold) {
for (pos = 90; pos <= 0; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
}
}
if (cm <= distanceThreshold && cm > distanceThreshold - 40) {
for (pos = 0; pos <= 90; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
}
}
delay(100); // Wait for 100 millisecond(s)
}