아두이노프로세싱 프로그래밍

캡스톤 디자인: 초음파 센서 RC카 장애물 회피 알고리듬

coding art 2019. 11. 21. 21:57
728x90

아두이노 제작해 보는 RC카를 단계 별로 살펴보면 처음에 간단한 셀프 주행일 것이다. 즉 전진 후진 좌회전 우회전 기능을 부여하면 좁은 공간 안에서 단조롭게 셀프 주행이 가능해진다. 이어서 HC-06 블루투스 보드를 추가하게 되면 블루투스에 의한 무선 조종이 가능해진다. 물론 스마트 폰 앱을 앱인벤터로 코드를 작성하여 사용하게 된다. 이러한 내용의 아두이노 RC카 제작 사례를 여러 차례 블로그에 게재했었다. 본 블로그 하단의 검색 창에서 RC카 또는 꿈의 대학으로 검색해 보면 그 과정을 쉽게 찾아 볼 수 있을 것이다.

  

 

 

한편 인공지능 즉 AI를 사용하지 않으면서도 간단한 알고리듬 적용에 의하여 앞에서 나타나는 장애물을 피해갈 수 있는 RC카를 제작해 보고자 한다. 장애물과의 충돌을 피할 수 있는 능력은 박쥐 사례에서 흔히 찾아 볼 수 있으므로 유사하게 초음파 센서를 사용해서 전 근접된 거리에 장애물이 있으면 일단 속도를 낮춰 멈춘 후 어느 정도 후진 후 우회전이든 좌회전하여 전진 주행 시키도록 하는 것이다.

 

위 그림에서 보듯이 한쪽 방향으로 방향을 변경하여 진행 후에는 장애물을 우회는 하지만 통과하는 것이 아니므로 우회전 후에 측정한 거리 값과 우회전 이전에 측정한 장애물과의 거리 값과 차이를 계산하여 + 이면 장애물을 통과 한 상태이므로 약하게 좌회전 시켜 전진 시켜야 할 것이다.

 

다음의 동영상에서 알고리듬이 작동하는지 관찰해 보자.

 

 

https://youtu.be/E1k1OabTZ4Y

 

 

//RCCAR_ULTRASONIC_03

#include <AFMotor.h>
#define ECHO 2
#define TRIG 13

AF_DCMotor motor1(3); 
AF_DCMotor motor2(4); 
int mspd = 150;
char command;

void setup() {   
  Serial.begin(9600); 
  pinMode(TRIG,OUTPUT); 
  pinMode(ECHO,INPUT); 
  Stop();
  delay(1000);
  forward();
  delay(500);
}

void loop()  {
 digitalWrite(TRIG,HIGH);   //send Pulse
 delayMicroseconds(10);
 digitalWrite(TRIG,LOW);  
 int us = pulseIn(ECHO,HIGH);    //get return time 
 int cm = us/58;
 Serial.print("cm : ");
 Serial.println(cm);

 if( cm < 25 ) {
  Stop();
  delay(500);
  back();
  delay(1000);
  right();
  delay(1000);
 }
  forward();delay(1000);
}

void forward()  {
  motor1.setSpeed(mspd); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(mspd); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
}

void back()  {
  motor1.setSpeed(mspd); 
  motor1.run(BACKWARD); //rotate the motor counterclockwise
  motor2.setSpeed(mspd); 
  motor2.run(BACKWARD); //rotate the motor counterclockwise
}

void left()  {
  motor1.setSpeed(mspd); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(0);
  motor2.run(RELEASE); //turn motor2 off
}

void right()  {
  motor1.setSpeed(0);
  motor1.run(RELEASE); //turn motor1 off
  motor2.setSpeed(mspd); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
}

void Stop()  {
  motor1.setSpeed(0);
  motor1.run(RELEASE); //turn motor1 off
  motor2.setSpeed(0);
  motor2.run(RELEASE); //turn motor2 off
}

//끝