OPENLABS

프로젝트:: 초음파 센서

토픽 OPENLABS > 마이크로프로세서 > [2016] 아두이노 초급

 

초음파 센서 사용하기

 

int TrigPin = 12;
int EchoPin = 13;

void setup(){
  Serial.begin(9600);
  pinMode(TrigPin, OUTPUT);
  pinMode(EchoPin, INPUT);
}

void loop(){
  Serial.print("Distance : ");
  Serial.print(distance());
  Serial.println(" cm");
}

unsigned long distance(){
  unsigned long d;
  
  digitalWrite(TrigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(TrigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin, LOW);
  
  d = pulseIn(EchoPin, HIGH)*0.034/2;
  
  return d;
}

초음파 센서와 서보 결합

#include <Servo.h>

Servo myservo;
int increase = 1;
int min_angle = 15;
int max_angle = 165;
int pos = min_angle;

int TrigPin = 12;
int EchoPin = 13;

void setup(){
  Serial.begin(9600);
  myservo.attach(6);
  pinMode(TrigPin, OUTPUT);
  pinMode(EchoPin, INPUT);
}

void loop(){
  myservo.write(pos);
  Serial.print(pos);
  Serial.print(",");
  Serial.print(distance());
  Serial.print(".");

  pos += increase;
  if(pos <= min_angle || pos >= max_angle)
    increase *= -1;

  delay(30);
}

unsigned long distance(){
  unsigned long d;
  
  digitalWrite(TrigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(TrigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin, LOW);
  
  d = pulseIn(EchoPin, HIGH)*0.034/2;
  
  return d;
}

댓글

댓글 본문
  1. JustStudy
    아주 소중한 강의 고맙습니다.