정보나눔

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

초음파 센서 lcd 출력 버튼 제어에 대하여 질문 드립니다.
김영준 | 2016-06-11

안녕하세요! 다름이 아니라

초음파 센서를 사용하여 값을 측정 후 lcd에 출력 까지 하였습니다.

버튼을 이용하여 한번 누르면 측정이 되고 누르지 않던가 한번더 눌렀을 경우 다시 측정이 안되는

방법을 사용하려고 합니다.

소스에서 해봤지만 무엇이 잘못된것 인지 잘 모르겠습니다.

도와주신다면 정말 감사합니다.

lcd는 i2c 라이브 러리를 사용하였고 초음파 센서용 newping 이라는 라이브 러리를 사용하였습니다.

버튼 제어가 가능한 후에는 특정 거리에서 led가 작동하게 끔 만들고자 합니다.

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

#include <NewPing.h>

#define TRIG_PIN 12
#define ECHO_PIN 10
#define MAX_DISTANCE 200

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

unsigned int pingSpeed = 50, distance;
unsigned long pingTimer, prev;

int state = LOW;
int Button1 = 3;

LiquidCrystal_I2C lcd(0x20,16,2);

void echoCheck();

void setup() {
  pinMode(Button1, INPUT);
  lcd.init(); 
  lcd.backlight();
  Serial.begin(9600);
  pingTimer = prev = millis();
}

void loop() {
  unsigned long curr;
  state = digitalRead(Button1);
  
  if(state == HIGH);
  {    
  if (millis() >= pingTimer) 
  {
    pingTimer += pingSpeed;
    sonar.ping_timer(echoCheck);
  }
  curr = millis();
  if (curr - prev > 500)
  {
    prev = curr;
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("distance:");
    lcd.setCursor(0,1);
    lcd.print("   ");
    lcd.setCursor(0,1);
    lcd.print(distance);
    lcd.setCursor(3,1);
    lcd.print("cm");
    
    Serial.println(distance);
  }
}
}

   
void echoCheck(){
  if(sonar.check_timer())
  {
    distance = sonar.ping_result / US_ROUNDTRIP_CM;
  }
}

 

프로필사진

Klant 2016-06-16 17:02:54

안녕하세요! 김영준님!

우선은 제가 버튼 하나로 로직을 짜봤습니다. 

초음파 센서로 거리를 측정하고 lcd에 출력하는 것은 해당 블럭에 넣어주시면 될 것 같구요. 

버튼을 통해 on, off 기능을 구현하기 위해 flag를 사용하였고, on이였을 때 millis 함수를 통해 시간을 측정 후 일정 시간이 지나면 off로 전환됩니다. 

아래 코드 참고하세요. 

boolean buttonStatus;
int oneTimeFlag;
int button = 12;

unsigned long previousMillis = 0;
const int interval = 5000;

void setup() {
  // put your setup code here, to run once:
  pinMode(button, INPUT_PULLUP);
  Serial.begin(9600);

}

void loop() {

  unsigned long currentMillis = millis();
  
  // put your main code here, to run repeatedly:
  if (digitalRead(button) == LOW) {
    if (oneTimeFlag == 0) {
      oneTimeFlag = 1;
      buttonStatus = !buttonStatus;
    }
  }
  else {
    oneTimeFlag = 0;
  }

  Serial.println(buttonStatus);

  if (buttonStatus == 0) {   
    Serial.println("Ultrasonic On    :");
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      buttonStatus = !buttonStatus;
    }
  }

  else {
    Serial.println("Ultrasonic Off");
  }
}

이전글   |    GY-521 MPU 6050 이용해서 각도 출력.. 2016-06-10
다음글   |    추가 질문 드립니다.. 2016-06-11