Arduino Sketch code - measure the distance and operate relay2015. 1. 26. 01:27
아두이노 스케치 코드 - Distance를 측정하여 전기를 Switch하는 아두이노 만들기
int trigerpin =5;
int echopin =7;
int Relay = 3;
void setup()
{
Serial.begin(9600);
pinMode(trigerpin,OUTPUT); // 센서 Trig 핀 신호를 보내는 역활을 한다.
pinMode(echopin,INPUT); // 센서 Echo 핀 신호를 받는다.
pinMode(Relay, OUTPUT); // relay 핀 신호를 보낸다.
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
void loop()
{
long duration, cm;
digitalWrite(trigerpin,HIGH); // 센서에 Trig 신호 입력
delayMicroseconds(10); // 10us 정도 유지 펄스신호를 10us동안 유지한 펄스를 보낸다.
digitalWrite(trigerpin,LOW); // Trig 신호 off
duration = pulseIn(echopin,HIGH); // Echo pin: HIGH->Low 간격을 측정 지속시간
cm = microsecondsToCentimeters(duration); // 거리(cm)로 변환
if(cm<46)
{
digitalWrite(Relay, HIGH); // 46cm이하에서 켜짐
}else{ // 나머지에서 110 이상켜짐 나머지는 꺼짐
if(cm>110)
{
digitalWrite(Relay, HIGH); //가끔 실제거리보다 크게 측정되는값이 입력된다. 이값을 켜짐으로 인식시켰다.
}
else{
digitalWrite(Relay, LOW);
}
}
Serial.print(cm);
Serial.print("cm"); //시리얼 포트에 표시한다.
Serial.println();
delay(1800); // 1.8초 지속 후 다시 측정
}
2015년 1월 수정본 - 거리 측정데이터 값이 가끔 오류가 나온다. 갑자기 큰 거리값이 읽힌다. 이걸 보정하는 것을 넣었다.
int trigerpin =5;
int echopin =7;
int Relay = 3;
void setup()
{
Serial.begin(9600);
pinMode(trigerpin,OUTPUT); // 센서 Trig 핀
pinMode(echopin,INPUT); // 센서 Echo 핀
pinMode(Relay, OUTPUT); // relay 핀
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
void loop()
{
long duration, cm;
digitalWrite(trigerpin,HIGH); // 센서에 Trig 신호 입력
delayMicroseconds(10); // 10us 정도 유지
digitalWrite(trigerpin,LOW); // Trig 신호 off
duration = pulseIn(echopin,HIGH); // Echo pin: HIGH->Low 간격을 측정
cm = microsecondsToCentimeters(duration); // 거리(cm)로 변환
if(cm<46)
{
digitalWrite(Relay, HIGH); // 46cm이하 켜짐
}else{ // 나머지에서 110cm 이상켜짐 오류때문에넣었다.
if(cm>110)
{
digitalWrite(Relay, HIGH);
}
else{ //남머징엣서 껒짐
digitalWrite(Relay, LOW);
}
}
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(1800); // 1.5초 대기 후 다시 측정
}
'Hardware Info. > Arduino' 카테고리의 다른 글
pow( base, exponent ) - 함수 (0) | 2015.02.21 |
---|---|
Switch Button component principle (0) | 2015.01.26 |
작동 동영상(play video) (0) | 2015.01.26 |
케이스 디자인(Case Design) (0) | 2015.01.26 |
Distance를 측정하여 전기를 Switch하는 아두이노 만들기 (0) | 2015.01.26 |