brunch

You can make anything
by writing

C.S.Lewis

by 알프레드 Mar 15. 2018

RC탱크 만들기 6

아두이노 스케치 작성


이제 모터 드라이버와 블루투스 모듈을 제어하는 아두이노 스케치를 작성해 보려 합니다.


기본적으로 모터 A는 5,6번 모터 B는 8,9번 핀으로 연결하여 DC 모터 드라이버로 제어합니다.

2,3번은 블루투스와 통신하는 데 사용하겠습니다.


모터 제어는 'S' 멈춤, 'F' : 앞으로  , 'B' : 뒤로 라고 정하였고요.

setMotor 함수로 각 모터의 제어를 할 수 있는 함수를 만들었습니다.


블루투스에서 보내는 신호는 정지는 S , 전후좌우(F, B, L, R) 및 대각선(W, X, Y, Z) 네 방향입니다.  

기본적으로 블루투스에서 보내는 제어 명령은 제어의 변화가 생길 때만 전송한다는 가정으로 작성된 스케치입니다. 


W F X

L S R

Y B Z


loop에서 블루투스에서 위의 코드 중 하나를 받으면

케이스 문으로 분기해서

setMotor로 A, B모터를 각각 제어해서 조정기 코드를 완성했습니다.


완성된 소스코드는 아래와 같습니다.


#include <SoftwareSerial.h>


//

SoftwareSerial BTSerial(2, 3); //Connect HC-06 TX, RX


char motor_dir = 'S';


void setup()  

{  

  //set pinmode

  pinMode(8, OUTPUT);

  pinMode(9, OUTPUT);

  pinMode(5, OUTPUT);

  pinMode(6, OUTPUT);

  // BlueTooth 

  BTSerial.begin(9600);

  //stop the motor

  setMotor('A', 'S');

  setMotor('B', 'S');

}


void loop()

{

  if(BTSerial.available()) {

     motor_dir = BTSerial.read();

     switch(motor_dir){

      case 'F': 

              setMotor('A', 'F');

              setMotor('B', 'F');

              break;

      case 'S':

              setMotor('A', 'S');

              setMotor('B', 'S');

              break;

      case 'B':

              setMotor('A', 'B');

              setMotor('B', 'B');

              break;

      case 'L':

              setMotor('A', 'B');

              setMotor('B', 'F');

              break;

      case 'R':

              setMotor('A', 'F');

              setMotor('B', 'B');

              break;

      case 'W':

              setMotor('A', 'S');

              setMotor('B', 'F');

              break;

      case 'X':

              setMotor('A', 'F');

              setMotor('B', 'S');

              break;

      case 'Y':

              setMotor('A', 'S');

              setMotor('B', 'B');

              break;

      case 'Z':

              setMotor('A', 'B');

              setMotor('B', 'S');

              break;

     }

 }

}


void setMotor(char motor, char cmd) {

    int pinA = motor=='A'? 5 : 8; 

    int pinB = motor=='A'? 6 : 9;

    switch(cmd) {

       case 'S' : 

           digitalWrite(pinA, LOW);

           digitalWrite(pinB, LOW);

           break;

       case 'F' : 

           digitalWrite(pinA, HIGH);

           digitalWrite(pinB, LOW);

           break;

       case 'B' : 

           digitalWrite(pinA, LOW);

           digitalWrite(pinB, HIGH);

           break;

    } 

}


이제 완성이 가까워지고 있네요.

다음 글에서는 RC탱크 조정을 위해 블루투스로 제어신호를 보내는 어플에 대한 글을 적도록 하겠습니다.


매거진의 이전글 RC탱크 만들기 5
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari