초음파센서로 거리에 따라 진동을 주려고 하는데요, 초음파센서에 움직임이 감지되는 경우 진동이 울리는데 10초 이상 감지될 경우 진동을 멈추게 하는 것이 궁금합니다.
도움 부탁드려요!
코딩입니다
#define TRIG 9
#define ECHO 8
int VIBE = 3;
#define trig 6
#define echo 7
int vibe = 10;
unsigned long pasttime = 0;
unsigned long nowtime = millis();
int VIBEState = 0;
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(VIBE, OUTPUT);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(vibe, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
duration = pulseIn (ECHO, HIGH);
distance = duration * 17 / 1000;
long duration2, distance2;
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration2 = pulseIn (echo, HIGH);
distance2 = duration2 * 17 / 1000;
Serial.println(duration );
Serial.print("\nDIstance : ");
Serial.print(distance);
Serial.println(" Cm");
delay(50);
Serial.println(duration2 );
Serial.print("\nDIstance : ");
Serial.print(distance2);
Serial.println(" Cm");
delay(50);
if (distance <= 50) {
analogWrite(VIBE, 255);
}
else if ((distance > 50) && (distance <= 100)) {
if (pasttime - nowtime >= 500) {
pasttime = nowtime;
if (VIBEState == 0) {
analogWrite(VIBEState, 255);
}
else VIBEState = 0; {
analogWrite(VIBE, VIBEState);
}
}
}
else {
analogWrite(VIBE, 0);
}
if (distance2 <= 50) {
analogWrite(vibe, 255);
}
else if ((distance2 > 50) && (distance2 <= 100)) {
analogWrite(vibe, 255);
delay (500);
analogWrite(vibe, 0);
delay (500);
}
else {
analogWrite(vibe, 0);
}
}
|