don't know what's causing it... i made a simple bar gate that opens on the condition that the ultrasonic sensor detects something and a button is pressed. it works as intended when i plug it into my laptop but it starts glitching out and doing it's thing. here's the code:
const int triggerPin = 7;
const int echoPin = 8;
const int butpin = 12;
const int led = 13;
int pos = 0;
bool valid = false;
#include <Servo.h>
Servo myservo;
void setup() {
// initialize serial communication:
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(butpin, INPUT_PULLUP);
myservo.attach(4);
pos = 0;
}
void loop() {
// establish variables for duration of the ping, and the distance result
// in inches and centimeters:
long duration, 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:
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(5);
digitalWrite(triggerPin, LOW);
// The same pin is used to read the signal from the PING))): a HIGH pulse
// whose duration is the time (in microseconds) from the sending of the ping
// to the reception of its echo off of an object.
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
if(digitalRead(butpin) == LOW && cm <= 50){
digitalWrite(led, HIGH);
valid = true;
}
else{
digitalWrite(led, LOW);
valid = false;
}
if(valid == true){
for (pos = 0; pos <= 90; pos += 1){
myservo.write(pos);
delay(15);
}
for (pos = 90; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(15);
}
}
}
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;
}
