아두이노 - 블루투스 예제

2021. 4. 29. 15:24전공공부/전자전기전공

<그림 1> ESP32

앞으로 실습할 블루투스 예제는 ESP32 model중 NODEMCU- 32S를 사용할 예정이다. ESP32 모델은 블루투스와 wifi를 아두이노 우노와달리 간편하게 사용할 수 있다는 점에서 유리하다.

이를 바탕으로 공부해 보겠다.

 

m.blog.naver.com/chandong83/222024806861

 

아두이노 ESP32 환경 설정 - 윈도 편

약 1년 반전에 ESP32를 다뤄본 적이 있는 것 같다. 기억하기엔 당시 업체 데모 개발 건이 있어서 환경을...

blog.naver.com

이 블로그를 들어가면 ESP32 관련 라이브러리나 환경설정할 수 있다.

 

이를 바탕으로 블루투스 예제에 들어가보면

#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

 다음과 같다. 

 

"BluetoothSerial.h"의 라이브러리를 사용하고 

밑의 문장 BluetoothSerial SerialBT는 우리가 할당할 디바이스를 할당할 string을 제공한다. 즉 블루투스 사용할 기기를 SerialBT라 명명한다. 

이후 setup 함수에서 115200bps로 속도를 맞췄고 블루투스 이름은 ESP32test로 설정했다. 

 

그 뒤 loop함수에서

첫번쨰 if는 esp32에서 읽을 byte가 있다면 블루투스기기에 준 정보를 시리얼모니터에 write한다

두번쨰 if는 마찬가지로 블루투스기기에서 읽을 바이트가 존재한다면 시리얼모니터에서 쓴 정보를 기기에서 읽을 수 있다.

esp32와 블루투스 기기(스마트폰)간에 원활한 소통을 위해선 Arduino bluetooth controller 앱을 사용하면 된다. 페어를 한 이후에 terminal mode로 서로 정보를 쓰고 읽는 것이 가능하다.

<그림 2> Arduino bluetooth controller