정보나눔

오픈소스하드웨어 프로젝트에 대한 다양한 정보를 나누는 공간입니다.

초음파 센서 시간 질문 드립니다.
탁탁 | 2018-05-30

초음파센서로 30cm 이하일때 모터가 돌도록 하는 코드를 짜고 있는데요.

현재 아래에 작성된 코드는 센서가 30cm 이하를 인식하자 마자 몇초간 돌게 코드를 짰습니다.

그리고 버튼을 누르면(택트) 반대방향으로 몇초간 돌고 30cm 이상일때는 정지하도록 되어있는 상태입니다.

 

저는 센서가 30cm이하를 인식하자 마자 바로 모터를 돌리는게 아니라 30cm 이하인 상태가 몇초동안 지속되어 인식되었을때 모터를 돌리게 하고싶습니다.

 

한번더 정리해서 말씀드리면 아래에 if문에서 30cm 이하일때 인식이 몇초이상 지속되어야 모터가 돌게 하고싶습니다. 어떻게 해야하나요 ㅜㅜ

 

#include <Servo.h>

int trig = 2;
int echo = 3;
long duration, cm;
int button = 4;

Servo servo;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600); // 시리얼 통신 초기화
  pinMode(trig, OUTPUT); // 센서 Trig 핀
  pinMode(echo, INPUT); // 센서 Echo 핀
  pinMode(button, INPUT);
  servo.attach(9); // 서보모터
}
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;
}
void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trig, HIGH); // 센서에 Trig 신호 입력
  delayMicroseconds(10); // 10us 정도 유지
  digitalWrite(trig, LOW); // Trig 신호 off
  boolean state = digitalRead(button); // 버튼 상태
  duration = pulseIn(echo, HIGH); // Echo pin: HIGH->Low 간격을 측정
  cm = microsecondsToCentimeters(duration); // 거리(cm)로 변환

  Serial.print("distance : ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  Serial.print("button : ");
  Serial.print(state);
  Serial.println();

 
  delay(300); // 100ms 지연

 

 if(cm<30) {
  delay(3000);
  {servo.write(0);
    delay(2000);
    Serial.print("down");
    Serial.println();;
    }
 }

  else if(state == true) {
    servo.write(180);
    delay(2000);
    Serial.print("up");
    Serial.println();
    }
  else {
    servo.write(90);
    Serial.print("stop");
    Serial.println();
    }
   
}

이전글   |    아두이노와 센서2개의 I2C 통신 문의 2018-05-29
다음글   |    ds1302모듈로 시계만들기 질문 2018-05-30