반응형

ESP32 Dev Module은 블루투스 장치를 기본 내장하고 있다. 

 

내장된 블루투스는 라이브러리를 통하여 블루투스 2.0 클래식 또는 블루투스 4.0 BLE로 구분하여 사용 가능하다. 하지만 아두이노 IDE 사용환경에서는 ESP32의 블루투스 연결시 PIN CODE 연결옵션을 아직까지 공식 지원하지는 않는다. 

 

우선 ESP32 블루투스 2.0 클래식 라이브러리를 살펴보도록 하겠다. 

 

ESP32 보드가 선택된 상태에서 파일 -> 예제 -> BluetoothSerial -> SerialToSerialBT를 선택하자.

 

 

아두이노 시리얼통신 기본코드와 매우 흡사함을 알 수 있다. 

아두이노의 "softwarSerial.h" 라이브러리 대신 "BluetoothSerial.h" 라이브러리를 사용하고 아두이노의 softwarSerial 클래스 객체선언 대신 BluetoothSerial 객체선언을 사용하여 블루투스 클래스 객체선언 방식도 같다. 단지 ESP32에는 software 시리얼이 없고 hardware 시리얼을 3개 지원하므로 전송속도를 115200으로 맞춰 더욱 빠른 통신을 할 수 있다. 

 

아두이노에서는 hardware 시리얼 1개(baud rate 115200 까지)만을 지원하므로 추가로 시리얼 포트를 사용하기 위해서는 softwarSerial.h 라이브러리를 사용하여 프로그램으로 에뮬레이팅한 시리얼을 사용해야 했으며, 그로인해 통신속도 제약이 발생하여 시리얼 통신을 안정적으로 하기 위해서는 baud rate를 9600으로 맞춰 사용해야야만 했다. 또한, 시리얼 포트의 2개 이상 사용은 거의 불가능 했다 .   

 

아두이노 IDE 환경의 ESP32 블루투스 2.0 라이브러리는 아두이노 softwareSerial 라이브러리의 형식을 그대로 채용하여 아두이노 softwareSerial 라이브러리에 익숙한 사용자들이 쉽게 사용하도록 하였다

 

//This example code is in the Public Domain (or CC0 licensed, at your option.)

//By Evandro Copercini - 2018

//

//This example creates a bridge between Serial and Classical Bluetooth (SPP)

//and also demonstrate that SerialBT have the same functionalities of a normal Serial

 

#include "BluetoothSerial.h"

 

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)

#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it

#endif

 

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);

 

}

 

주석 내용을 살펴보자.

 

//This example creates a bridge between Serial and Classical Bluetooth (SPP)

//and also demonstrate that SerialBT have the same functionalities of a normal Serial

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)

#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it

#endif

 

보통 시리얼과 같은 기능을 갖고 있다고 하였고 Classical Bluetooth (SPP)과 시리얼간의 연결을 만든다고 하였다.  

* SPP (Serial Port Profile) : RS-232 시리얼 통신용 블루투스 2.0 클래식 프로파일

 

 

또한, 만약 CONFIG_BT_ENABLED가 아니면 "Bluetooth is not enabled! Please run `make menuconfig` to and enable it" 라고 메세지가 표시 되게 되어 있다. 

 

이 메세지에 언급된 menuconfig는 아두이노 IDE 사용 환경에서는 접근이 불가하고 ESP-IDF 환경에서만 접근이 가능한 항목이다. 

 


 

ESP32의 menuconfig에 관해 찾아 보던중 아두이노 IDE용 ESP32 CORE는 ESP-IDF 환경에서 아두이노 IDE에 사용할 수 있도록 ESP32의 기본 옵션들을 프리 컴파일 시켜 제작된다는 것을 알게 되었고, 그 기본 옵션들은 ESP-IDF 환경에서 menuconfig를 불러와 설정하게 된다. 따라서 아두이노 IDE에서는 기본 옵션들이 고정되어 있어서 설정된 옵션들의 값을 확인 할 수는 있으나 설정 값의 변경은 현재까지 불가능하다.  

 

ESP32 아두이노 CORE의 기본설정 항목중 블루투스관련 설정항목들이 있으며, 그중에 블루투스 2.0 연결 방법이 SSP 방식으로 고정되어 있음을 확인 할 수 있다. 

 

* 블루투스 연결시 PIN CODE를 이용한 페어링을 Legacy Pairing이라 하고 PIN CODE 없이 연결하는 방식을 Secure Simple pairing(SSP)라 한다. 

 

ESP-IDF 환경 menuconfig의 설정이 아래와 같이 되어야 PIN CODE를 이용한 Legacy Pairing이 되는것 같다.

"CONFIG_BT_SSP_ENABLED=y"  -> Simple pairing(SSP) 

"CONFIG_BT_SSP_ENABLED="  -> Legacy Pairing

'y' 문자의 유무에 따라 설정이 정해진다. 

 

참조사이트 https://github.com/espressif/arduino-esp32/pull/2765

 

SSP(Secure Simple Pairing) 옵션이 활성화 되지 않은 ESP32 아두이노 코어가 아두이노 IDE에 설치된 상태에서 아래 코드를 BluetoothSerial.cpp와 BluetoothSerial.h에 추가 해주면 ESP32 블루투스 2.0 연결시 PIN CODE를 확인한다고 한다. 

 

BluetoothSerial.cpp에 추가할 코드

bool BluetoothSerial::pinCode( char* pswd)

{

    if(strlen(pswd)==4){

        esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_FIXED;

        esp_bt_pin_code_t pin_code;

        pin_code[0] = pswd[0];

        pin_code[1] = pswd[1] ;

        pin_code[2] = pswd[2];

        pin_code[3] = pswd[3];

        esp_bt_gap_set_pin(pin_type, 4, pin_code);

        return true;

    }

    else

        return false;

 

}

 

BluetoothSerial.h에 추가할 코드

#include "esp_gap_bt_api.h"   

 

bool pinCode(char* pswd);

 

참조사이트 https://github.com/espressif/arduino-esp32/pull/2765/files

 

앞에서도 언급했지만 상기의 SSP 설정은 아두이노 IDE 환경에서는 할 수가 없다. ESP-IDF 환경에서 할 수있다는데 찾아보니 관련 프로그램을 설치하고 세팅하라고 한다. 귀찮다......

 

관련 자료를 좀더 검색하다보니 SSP 설정이 된 블루투스 관련 파일 libbt.a을 제공하는 글을 확인하게 되었고 적용하여 보니 잘 작동이 된다. 

참조사이트 https://github.com/espressif/arduino-esp32/issues/2320

 

disable_ssp.zip
3.77MB

 

첨부된 파일을 다운받아 압축을 풀고 폴더내 있는 libbt.a파일을 복사한뒤 아래의 그림을 참조하여 해당 폴더로 이동한다. 

 

 

아두이노 환경설정에서 표시부분을 클릭한 후 \packages\esp32\hardware\esp32\1.0.2\tools\sdk\lib 폴더로 이동한다. 

 

 

 

 


 

필자의 현재 ESP32 아두이노 코어의 버전은 1.02이고 \packages\esp32\hardware\esp32\1.0.2\tools\sdk\lib 폴더에 설치되어 있는 libbt.a파일의 크기가 12,796kb이다. 하지만 첨부파일의 libbt.a파일의 크기가 12,505kb임을 확인 하였다. 파일 크기의 차이가 상당하여 코어가 업데이트 되기 전에 만들어진 파일일 가능성이 있어 대체하기 전에 원본파일은 백업해 둘것을 권장한다. 

필자는 libbt라는 폴더를 생성하여 원본 파일을 백업해 놓았다. 

 

 

 

그다음 packages\esp32\hardware\esp32\1.0.2\libraries\BluetoothSerial\src폴더로 이동하여 아래파일을 대체해 준다.

 

BluetoothSerial.h
0.00MB

 

BluetoothSerial.cpp
0.01MB

 

 

 

라이브러리를 변경할 경우에는 반드시 아두이노 IDE를 종료시킨후 재실행 시켜야 변경사항이 반영된다. 

 

아래 첨부된 스케치 파일 처럼 기본 예제에 SerialBT.pinCode("3456"); 형식으로 pin code를 설정하면 블루투스 연결시 핀코드 입력창이 뜨게 된다. 

 

SerialToSerialBT_pin_code.ino
0.00MB

  

#include "BluetoothSerial.h"

 

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)

#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it

#endif

 

BluetoothSerial SerialBT;

 

void setup() {

  Serial.begin(115200);

  SerialBT.begin("ESP32test"); //Bluetooth device name

  SerialBT.pinCode("3456");    // pin code 설정

  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.cpp 와 BluetoothSerial.h 파일의 수정없이 스케치에 직접 필요한 코드를 입력하여 구현한 것이다. 

 

원하는 방법을 이용하면 되겠다.

 

BluetoothSerial.cpp 와 BluetoothSerial.h 파일의 수정없이 적용할 수 있는 코드를 좀더 단순화 시켜 보았다. 

 

SerialToSerialBT_pin_code_modify.ino
0.00MB

 

#include "BluetoothSerial.h"

#include "esp_gap_bt_api.h"  // pin code 관련 라이브러리

 

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!");

  esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_FIXED; // pin code 관련 코드

  esp_bt_pin_code_t pin_code = "1234";                           // pin code 설정

  esp_bt_gap_set_pin(pin_type, 4, pin_code);

}

 

void loop() {

  if (Serial.available()) {

    SerialBT.write(Serial.read());

  }

  if (SerialBT.available()) {

    Serial.write(SerialBT.read());

  }

  delay(20);

 

}

 

 

아래는 ESP32 원격제어 코드에 ESP32 블루투스 시리얼 라이브러리를 적용한 것이다. 

 

 

 

 

esp32_BT_uart_full_pin_code.ino
0.01MB

 

 

관련 글

[arduino] - 아두이노 - 안드로이드를 이용한 무선 원격제어 그리고 시리얼 통신 - 1편

[arduino] - 아두이노 - 안드로이드를 이용한 무선 원격제어 그리고 시리얼 통신 - 2편

[arduino] - 아두이노 - 안드로이드를 이용한 무선 원격제어 그리고 시리얼 통신 - 3편

[arduino] - 아두이노 - 안드로이드를 이용한 무선 원격제어 그리고 시리얼 통신 - 4편

[arduino] - 아두이노 - 안드로이드를 이용한 무선 원격제어 그리고 시리얼 통신 - 5편

 

arduino bluetooth controller PWM - 아두이노 원격제어 안드로이드 앱 버전 3.5 다운로드

arduino bluetooth controller PWM 매뉴얼

 

 

+ Recent posts