Bluetooth 4.0 (이하 BLE) 모듈을 이용해 Tech DIY를 하시는 분들이라면 보통 HM-10, HM-11 모듈을 많이 사용하실겁니다. 일반적인 통신 모듈의 용도로 사용하기에는 HM-10, HM-11 모듈이 부족함이 없긴 하지만, (좀 더 고난이도의) 펌웨어 수정을 하고 싶거나 BLE 스펙의 Profile-Service-Characteristic 구조를 입맛에 맞게 변경하고 싶을 때는 제약사항이 많습니다. 이런 경우는 nRF51822 BLE 모듈이 더 적절합니다. nRF51822 BLE 모듈은 AT 커맨드를 통해 BLE 모듈의 설정을 훨씬 상세하게 변경할 수 있고 펌웨어를 입맛에 맞게 수정해서 올릴 수도 있기 때문입니다.

nRF51822 BLE 모듈

nRF51822 BLE 모듈은 Nordic의 nRF51822 칩셋에 기반한 BLE 통신 모듈입니다. 일반적으로 자주 사용되는건 TI – CC2541 칩셋을 사용한 HM-10 모듈이지만 nRF51822 BLE 모듈은 그보다 훨씬 세밀하게 모듈의 설정을 변경해서 테스트 할 수 있습니다. BLE 모듈을 좀 더 심도있게 조작하고 싶을 때 사용하면 좋은 모듈입니다. nRF51822 BLE 모듈은 AT command를 이용해 모듈의 설정을 바꿀 수도 있고 펌웨어 자체를 수정해서 업데이트 할 수도 있습니다.

해외 구매를 통해 구할 수 있는 nRF51822 BLE 모듈은 종류가 많습니다. 그리고 각 모듈들의 핀 배치가 모두 제각각이라 구매전에 면밀히 체크가 필요합니다. 따라서 미리 필요한 하드웨어적 조건이 모두 갖춰진 nRF51822 BLE evaluation kit 을 추천합니다. 가격이 상대적으로 비싸고 덩치가 크지만 디버깅/개발이 용이하도록 환경이 미리 갖춰진 세트입니다. 개발용 세트를 이용해 먼저 테스트 해보고 나중에 필요한 모듈만 구입하는게 좋습니다. 하지만 처음에 이 모듈을 바로 사용하기란 조금 버거울 수 있습니다. 좀 더 문서가 잘 갖춰진 테스트용 모듈이 필요할 것입니다.

nrf51822_eval_kit

nRF51822 BLE 모듈만 검색하면 아래와 같이 생긴 모듈들이 나옵니다. nRF51822 BLE evaluation kit 으로 어느정도 테스트가 끝난 뒤 이런 모듈들을 사서 활용하시면 되겠습니다.

9df3d01e08849d170a7dba6fc667e0e3.image.164x123 aba4c522b25c8ecc46501ddfe41ed96c.image.164x123

adafruit_products_2479_iso_ORIG

nrf51822

아래 스펙은 그 중 Adafruit Bluefruit LE UART friend 모듈의 스펙입니다. 다른 모듈들도 대개 비슷한 사양일 것입니다.

Specification

  • ARM Cortex M0 core running at 16MHz
  • 256KB flash memory
  • 32KB SRAM
  • Peak current draw <20mA (radio actively transmitting/receiving)
  • Transport: UART @ 9600 baud with HW flow control (CTS+RTS required)
  • 5V-safe inputs (Arduino Uno friendly, etc.)
  • On-board 3.3V voltage regulation
  • Bootloader with support for safe OTA firmware updates
  • Easy AT command set to get up and running quickly

nRF51822 모듈에 관련된 해외 자료 중  그나마 상세히 소개되어 있는 것이 Adafruit Bluefruit LE 모듈입니다. 위 Evaluation kit과 같은 nRF51xxx 칩을 사용하므로 일단은 이 모듈을 가지고 여러가지 테스트를 해 보는 것이 가장 쉬운 방법입니다. 여기서는 이 모듈을 기준으로 설명하겠습니다.

adafruit_products_2479_iso_ORIG

주의!!!  : 아직 모듈이 입수되지 않아 100% 테스트 된 자료는 아닙니다. Adafruit Bluefruit LE 모듈이 아닌 경우 종류에 따라 내용과 맞지 않을 수 있습니다.

연결 방법

모듈에 따라 차이는 있지만 대개 VCC(or VIN), GND, RX, TX 핀은 공통으로 가지고 있습니다. 이 핀만 연결해도 PC 또는 아두이노와 서로 데이터를 주고 받는 것이 가능합니다.

  • VCC(VIN) : 모듈에 전원 공급용(+). 대부분 3.3V 전용이지만 Adafruit Bluefruit LE 모듈의 경우는 3~16V 입력 가능
  • GND : 그라운드 핀(-)
  • TX (or TXO) : UART 전송용 핀 (BLE 모듈 –> MCU or PC). 3.3V 전압레벨이 필요. Adafruit Bluefruit LE 모듈의 경우는 레벨 쉬프터가 내장되어 있으므로 3~5V 가능.
  • RX(or RXI) : UART 수신용 핀 (BLE 모듈<- – MCU or PC). 3.3V 전압레벨이 필요. Adafruit Bluefruit LE 모듈의 경우는 레벨 쉬프터가 내장되어 있으므로 3~5V 가능.
  • CTS : 하드웨어 flow control 핀. 기본 pull up 설정이 되어 있으므로 이 핀에 GND를 넣어주면 Adafruit Bluefruit LE 모듈이 TXO 핀으로 데이터를 보내도 된다고 인식함. (Adafruit Bluefruit LE 모듈 한정)
  • RTS : 이핀에 GND를 걸어주면 MCU에서 BLE 모듈로 데이터를 보낼 준비가 됐다고 BLE 모듈이 인식함 (Adafruit Bluefruit LE 모듈 한정)
  • MOD : 이 핀이 High 상태일 때는 Command 모드로 설정됨. Low 상태일 때는 Data 모드로 설정됨. (Adafruit Bluefruit LE 모듈 한정이며, 일반적인 용도에서는 사용할 필요 없음)
  • DFU : 이 핀에 GND를 연결한 상태로 전원을 입력하면 펌웨어 업데이트 모드가 됨. 전원이 켜진 이후에는 이 핀을 통해 factory reset 을 실행할 수 있음. (5초 이상 GND 연결 유지. Adafruit Bluefruit LE 모듈 한정이며, 일반적인 용도에서는 사용할 필요 없음)

아두이노와의 연결은 아래처럼 하면 됩니다. (UART 버전일 경우)

  • TXO to Pin 10
  • RXI to Pin 9
  • VIN to 5V
  • GND to GND
  • (모듈 종류에 따라 틀리지만 위 핀들은 필수!! 아래는 선택사항)
  • MOD to Pin 12
  • CTS to Pin 11 (하드웨어 시리얼을 사용하거나 이 핀의 기능을 사용하지 않을 때는 GND로 연결해야함!!)
  • RTS to Pin 8

만약 모듈이 SPI를 지원하는 모듈이라면 아래 링크를 참고해서 연결하세요.

https://learn.adafruit.com/introducing-the-adafruit-bluefruit-spi-breakout/wiring

라이브러리 다운로드 및 공장 초기화(Factory Reset)

먼저 Adafruit에서 제작한 nRF51xxx용 라이브러리를 다운로드 받아 설치해줍니다.

이상의 작업을 마쳤으면 먼저 공장 초기화 하는 방법을 알아보죠. 3가지 방법이 있습니다.

  • DFU 핀을 5초 이상 GND로 유지하면 공장 초기화가 됩니다.
  • SW적으로도 할 수 있는데 라이브러리에 포함된 예제 중 [File > Examples > Adafruit_BluefruitLE_nRF51] 폴더에서 factoryreset 예제를 실행하면 됩니다.
  • AT 커맨드를 보내서 수행할 수 있습니다.  (AT+FACTORYRESET)

펌웨어 업데이트

Adafruit Bluefruit LE 모듈의 경우는 안드로이드 앱을 통해 무선으로 펌웨어 업데이트가 가능합니다. 아래 앱을 받아서 해보세요.

다른 모듈을 사용하고 있는 경우는 관련 자료를 참고해서 펌웨어 업데이트를 하시기 바랍니다.

Serial 통신 초기화

아두이노에서 Adafruit 라이브러리를 이용해 BLE 모듈에 연결하기 위해서는 초기화 코드를 수정해 줘야 합니다. 예제코드를 불러와서 아래 부분을 자신의 설정에 맞게 수정해주세요. 아래 방법은 SoftwareSerial을 이용해 아두이노와 BLE 모듈을 연결하는 방법입니다.

#define BLUEFRUIT_SWUART_RXD_PIN        9    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN        10   // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN          11   // Required for software serial!
//#define BLUEFRUIT_HWSERIAL_NAME           Serial1


SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
 
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,
                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);

하드웨어 시리얼 (아두이노의 D0, D1번 핀)을 이용해 연결해야 하는 경우라면 초기화 코드도 변경되어야 합니다. 아래 코드를 이용하세요.

Adafruit_BluefruitLE_UART ble(BLUEFRUIT_HWSERIAL_NAME, BLUEFRUIT_UART_MODE_PIN);

SPI 통신을 이용해 연결하는 경우라면 아래 코드를 이용.

/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

Data 모드와 Command 모드

Data 모드는 MCU(아두이노)와 Remote(PC 또는 폰)에서 받은 데이터를 상대방으로 전달해주는 간단한 역할을 합니다. 즉, 일반적인 블루투스 통신이 가능하도록 해주는 모드입니다. 만약 블루투스 모듈이 아두이노와 TX/RX/CTS 핀으로 연결되어 있고, 동시에 폰과 Adafruit 앱을 통해 페어링 되어 있다면 양쪽이 서로 채팅이 가능합니다.

이 때 특별한 문자열을 아두이노 또는 연결된 앱에서 전송하면 모드를 변경할 수 있습니다. [+++\n] 문자열이 그런 역할을 해줍니다. 이 문자열이 블루투스 모듈로 전달될 때 마다 Data 모드와 Command 모드가 번갈아 설정됩니다.

Command(커맨드) 모드에서는 AT Command를 이용해서 모듈의 설정을 변경할 수 있습니다. 커맨드 모드에서 AT 커맨드를 블루투스 모듈로 전송하면 그에대한 응답을 보내주는데 응답으로 오는 데이터 양이 너무 많은 경우 CTS 핀을 high 상태로 바꿔주면 됩니다. 아두이노가 응답을 받을 준비가 되었을 때 다시 CTS 핀을 low 상태로 해주면 됩니다. CTS 핀이 low 상태일 때만 블루투스의 TXO 핀이 활성화 됩니다.

AT Command

본격적으로 AT Command를 이용해 BLE 모듈 설정을 변경하기 전에 위에 기재된 과정들을 모두 마치셔야 합니다. 특히 아래 3개의 핀은 정확하게 연결되어 있어야 합니다.

#define BLUEFRUIT_SWUART_RXD_PIN        9    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN        10   // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN          11   // Required for software serial!

아래 핀이 연결되어 있으며 하드웨어적으로 BLE 모듈의 모드를 변경할 수 있습니다. 만약 아래 핀 설정을 사용하지 않는다면 AT Command를 이용해 모드를 바꿔줘야 합니다.

#define BLUEFRUIT_UART_MODE_PIN         12   // Optional but recommended, set to -1 if unused

Adafruit 라이브러리에 포함된 예제 중 [File > Examples > Adafruit_BluefruitLE_nRF51]  폴더에 있는 atcommand 예제를 불러옵니다.

adafruit_products_Screen_Shot_2015-04-30_at_23.10.01

예제를 업로드하고 [Tools > Serial Monitor] 시리얼 모니터를 실행하세요. 그리고 우측 하단에 있는 baud rate 설정을 9600 –> 115200으로 변경하세요.

이제 ATI 를 입력해보세요. 그럼 블루투스 모듈의 기본 정보가 주르륵 나올껍니다. 여기까지 문제 없다면 이제 각종 AT 커맨드를 이용해서 블루투스 모듈의 설정을 바꿀 수 있습니다. 사용 가능한 AT 커맨드는 AT+HELP 로 보실 수 있습니다.

특정 AT 커맨드가 사용 가능한 커맨드인지 확인하고 싶을 때는 “=?” 문자를 뒤에 붙이면 됩니다. 그럼 사용 가능한 커맨드인지 응답으로 알려줍니다.

AT+BLESTARTADV=?
OK\r\n
AT+MISSINGCMD=?
ERROR\r\n

특정한 값을 대입해서 넣고 싶을 때는 “=xxx” 형식으로 적어주면 됩니다.

AT+BLEPOWERLEVEL=-8
OK\r\n

현재 설정된 값을 알고 싶을 때는 “?” 물음표를 뒤에 붙여주세요.

AT+BLEPOWERLEVEL?
-4\r\n
OK\r\n

아래는 주요한 AT 커맨드 리스트입니다.

  • AT : 정상 동작하고 있는지 체크. 문제 없으면 OK를 응답해줌
  • ATI : 블루투스 모듈의 기본 정보를 보여줌
  • ATZ : 블루투스 모듈 리셋 커맨드
  • ATE : 입력한 값을 다시 보여주는 기능 on/off.
    ATE=0 (에코기능 off), ATE=1 (에코기능 on)
  • AT+FACTORYRESET : 공장 초기화
  • AT+DFU : DFU(펌웨어 업데이트 모드) 진입. iOS, Android 앱으로 무선 업데이트 가능
  • AT+HWADC : 특정 핀의 ADC(아날로그 디지털 컨버전) 값을 출력. 특정 핀으로 들어온 아날로그 값을 읽음.
    AT+HWADC=0
    178
    OK
  • AT+HWGPIOMODE : 특정 핀의 모드를 설정
    1 번째 파라미터 – 핀 넘버
    2 번째 파라미터 – 설정할 값 (0 = Input, 1 = Output, 2 = Input with pullup enabled, 3 = Input with pulldown enabled)
    AT+HWGPIOMODE=14,1 (14번 핀을 OUTPUT 모드로 설정)
    AT+HWPGIOMODE=14 (14번 핀의 현재 모드를 읽어옴)
  • AT+HWGPIO : 특정 핀의 값을 설정 혹은 읽어옴
    1 번째 파라미터 – 핀 넘버
    2 번째 파라미터 – 설정할 값 (0: low/GND, 1:high/VCC)
# Set pin 14 HIGH
AT+HWGPIO=14,1
OK
  
# Set pin 14 LOW
AT+HWGPIO=14,0
OK
  
# Read the current state of pin 14
AT+HWGPIO=14
0
OK
  
# Try to update a pin that is not set as an output
AT+HWGPIOMODE=14,0
OK
AT+HWGPIO=14,1
ERROR
  • AT+HWI2CSCAN : I2C로 연결된 장치들을 검색하고 발견된 장치의 I2C 어드레스를 출력
  • AT+HWVBAT : 메인 전원의 전압 레벨을 milli volt 단위로 출력
  • AT+HWRANDOM : 32bit 숫자를 랜덤으로 생성
  • AT+HWMODELED : 모듈에 탑재된 MODE LED의 동작을 변경
    disable or DISABLE or 0 – Disable the MODE LED entirely to save power
    mode or MODE or 1 – Default behaviour, indicates the current operating mode
    hwuart or HWUART or 2 – Toggles the LED on any activity on the HW UART bus (TX or RX)
    bleuart or BLEUART or 3 – Toggles the LED on any activity on the BLE UART Service (TX or RX characteristic)
    spi or SPI or 4 – Toggles the LED on any SPI activity
    manual or MANUAL or 5 – Manually sets the state of the MODE LED via a second comma-separated parameter, which can be on, off, or toggle.
  • AT+BLEBEACON : 비컨 동작 설정. 아래 5가지 값을 변경 가능
    Bluetooth Manufacturer ID (uint16_t)
    128-bit UUID
    Major Value (uint16_t)
    Minor Value (uint16_t)
    RSSI @ 1m (int8_t)
# Enable Apple iBeacon emulation
# Manufacturer ID = 0x004C
AT+BLEBEACON=0x004C,01-12-23-34-45-56-67-78-89-9A-AB-BC-CD-DE-EF-F0,0x0000,0x0000,-59
OK
# Reset to change the advertising data
ATZ
OK
  
# Enable Nordic Beacon emulation
# Manufacturer ID = 0x0059
AT+BLEBEACON=0x0059,01-12-23-34-45-56-67-78-89-9A-AB-BC-CD-DE-EF-F0,0x0000,0x0000,-59
OK
# Reset to change the advertising data
ATZ
OK
  • AT+BLEURIBEACON : UriBeacon advertising packet 설정하고 UriBeacon 으로 동작시킴. 설정가능한 Uri 길이가 있으므로 가급적 단축 URL을 생성해서 사용 권장.
AT+BLEURIBEACON=http://www.adafruit.com/blog
OK
 
# Reset to change the advertising data
ATZ
OK

UriBeacon의 경우 아래 앱을 이용해서 테스트 가능합니다.

  • AT+BLEPOWERLEVEL : 전송 파워 레벨을 변경
    사용 가능한 값 (-40, -20, -16, -12, -8, -4, 0, 4)
# Get the current TX power level (in dBm)
AT+BLEPOWERLEVEL
0
OK
  
# Set the TX power level to 4dBm (maximum value)
AT+BLEPOWERLEVEL=4
OK
  
# Set the TX power level to -12dBm (better battery life)
AT+BLEPOWERLEVEL=-12
OK
  
# Set the TX power level to an invalid value
AT+BLEPOWERLEVEL=-3
ERROR
  • AT+BLEGETADDRTYPE : 48bit BLE 장치 address 타입을 가져옴. 일반적으로 1로 설정되어 있으며 random을 의미함. 제조사가 설정한 값이라는 의미. 0인 경우는 public을 의미함
  • AT+BLEGETADDR : 48bit BLE 장치 address  출력
  • AT+BLEGETPEERADDR : 무선으로 연결된 장치의 address 출력
  • AT+BLEGETRSSI : RSSI value (Received Signal Strength Indicator, in dBm) 출력. 두 장치간 신호 강도, 데이터 전송의 신뢰도를 평가하는데 사용. 낮을수록 좋음
# Connected to an external device
AT+BLEGETRSSI
-46
OK
  
# Not connected to an external device
AT+BLEGETRSSI
0
OK
  • AT+BLEUARTTX : 커맨드 모드일 때 특정 문자열을 무선으로 전송. AT 커맨드는 256자 제한이 있으므로 메시지는 240자 이내로 제한. 상세내용은 링크 참고.
# Send a string when connected to another device
AT+BLEUARTTX=THIS IS A TEST
OK
  
# Send a string when not connected
AT+BLEUARTTX=THIS IS A TEST
ERROR
  • AT+BLEUARTRX : 커맨드 모드일 때 무선으로 수신한 데이터를 출력.
# Command results when data is available
AT+BLEUARTRX
Sent from Android
OK
  
# Command results when no data is available
AT+BLEUARTRX
OK
  • AT+BLEUARTFIFO : BLE UART TX, RX FIFO의 여유 공간을 출력. TX-RX 버퍼 여유 공간. TX, RX 파라이터를 통해 각각의 여유공간 체크 가능
AT+BLEUARTFIFO
1024,1024
OK
 
AT+BLEUARTFIFO=TX
1024
OK
 
AT+BLEUARTFIFO=RX
1024
OK
  • AT+BLEHIDEN : GATT over HID (GoH) 기능 활성화. 블루투스 입력 장치로 사용 가능하게 해줌 (1 = enable, 0 = disable). 설정 후 반드시 리셋 필요함.
# Enable GATT over HID support on the Bluefruit LE module
AT+BLEHIDEN=1
OK
  
# Reset so that the changes take effect
ATZ
OK
  • AT+BLEKEYBOARDEN : GATT over HID (GoH) – 키보드 지원 활성화. iOS, Android 기기의 키보드 에뮬레이트가 가능. (1 = enable, 0 = disable)
# Enable BLE keyboard support then reset
AT+BLEKEYBOARDEN=1
OK
ATZ
OK
  
# Disable BLE keyboard support then reset
AT+BLEKEYBOARDEN=0
OK
ATZ
OK
  •  AT+BLEKEYBOARD : 키보드 지원 활성화 상태일 때 특정 문자열을 키 입력된 것 처럼 보내줌. 특수문자 사용 가능
    \r – Carriage Return
    \n – Line Feed
    \b – Backspace
    \t – Tab
    \\ – Backslash
    As of version 0.6.7 you can also use the following escape code when sending a single character (‘AT+BLEKEYBOARD=?’ has another meaning for the AT parser):
    \? – Question mark
# Send a URI with a new line ending to execute in Chrome, etc.
AT+BLEKEYBOARD=http://www.adafruit.com\r\n
OK
  
# Send a single question mark (special use case, 0.6.7+)
AT+BLEKEYBOARD=\?
OK
  • AT+BLEKEYBOARDCODE : 키보드 지원 활성화 상태일 때 특정 키 코드를 보내줌.
    Byte 0: Modifier
    Byte 1: Reserved (should always be 00)
    Bytes 2..7: Hexadecimal values for ASCII-encoded characters (if no character is used you can enter ’00’ or leave trailing characters empty)Bit 0 (0x01): Left Control
    Bit 1 (0x02): Left Shift
    Bit 2 (0x04): Left Alt
    Bit 3 (0x08): Left Window
    Bit 4 (0x10): Right Control
    Bit 5 (0x20): Right Shift
    Bit 6 (0x40): Right Alt
    Bit 7 (0x80): Right WindowAT+BLEKEYBOARDCODE 커맨드로 키 코드를 보내준 다음에 반드시 AT+BLEKEYBOARDCODE=00-00 을 보내줘서 키가 release 됐음을 알려줘야 함.
# send 'abc' with shift key --> 'ABC'
AT+BLEKEYBOARDCODE=01-00-04-05-06-00-00
OK
# Indicate that the keys were released (mandatory!)
AT+BLEKEYBOARDCODE=00-00
OK
  • AT+EDDYSTONEENABLE : Eddystone(비컨 스펙의 일종) 활성화. 관련된 커맨드 사용하기 전에 반드시 이 커맨드를 실행해줘야 함. (1 = enable, 0 = disable)
# Enable Eddystone support
AT+EDDYSTONEENABLE=1
OK
 
# Check the current Eddystone status on the module
AT+EDDYSTONEENABLE
1
OK
  • AT+EDDYSTONEURL : Eddystone-URL 프로토콜을 위한 URL을 세팅
# Set the Eddystone URL to adafruit
AT+EDDYSTONEURL=http://www.adafruit.com
OK
  
# Set the Eddystone URL to adafruit and advertise it even when connected
AT+EDDYSTONEURL=http://www.adafruit.com,1
OK
  • AT+EDDYSTONECONFIGEN : 특정 시간동안 Eddystone URL 설정 서비스를 활성화. 이 커맨드를 실행하고 원격으로 연결된 PC 또는 폰에서 URL을 변경할 수 있음.
# Start advertising the Eddystone config service for 5 minutes (300s)
AT+EDDYSTONECONFIGEN=300
OK
  • AT+BLEHIDMOUSEMOVE : HID 마우스 동작 값, 휠 스크롤 값을 전송. 파라미터는 8-bit values (-128 to +127). + 값은 오른쪽 아래 방향.
    Parameters: X Ticks (+/-), Y Ticks (+/-), Scroll Wheel (+/-), Pan Wheel (+/-)
# Move the mouse 100 ticks right and 100 ticks down
AT+BLEHIDMOUSEMOVE=100,100
OK
  
# Scroll down 20 pixels or lines (depending on context)
AT+BLEHIDMOUSEMOVE=,,20,
OK
  
# Pan (horizontal scroll) to the right (exact behaviour depends on OS)
AT+BLEHIDMOUSEMOVE=0,0,0,100
  • AT+BLEHIDMOUSEBUTTON : HID 마우스 버튼 입력을 전송
    Parameters: Button Mask String [L][R][M][B][F], Action [PRESS][CLICK][DOUBLECLICK][HOLD]
    L = Left Button
    R = Right Button
    M = Middle Button
    B = Back Button
    F = Forward Button
    If the second parameter (Action) is “HOLD”, an optional third parameter can be passed specifying how long the button should be held in milliseconds.
# Double click the left mouse button
AT+BLEHIDMOUSEBUTTON=L,doubleclick
OK
 
# Press the left mouse button down, move the mouse, then release L
# This is required to perform 'drag' then stop type operations
AT+BLEHIDMOUSEBUTTON=L
OK
AT+BLEHIDMOUSEMOVE=-100,50
OK
AT+BLEHIDMOUSEBUTTON=0
OK
  
# Hold the backward mouse button for 200 milliseconds (OS dependent)
AT+BLEHIDMOUSEBUTTON=B,hold,200
OK
  •  AT+BLEHIDCONTROLKEY : 볼륨, 화면 밝기, 곡 선택 등 미디어 컨트롤 명령어를 전송, 사용가능한 코드 값은 링크에서 확인.
    Parameters: The HID control key to send, followed by an optional delay in ms to hold the button. The control key string can be one of the following values:
    # System Controls (works on most systems)
    BRIGHTNESS+, BRIGHTNESS-
    # Media Controls (works on most systems)
    PLAYPAUSE, MEDIANEXT, MEDIAPREVIOUS, MEDIASTOP
    # Sound Controls (works on most systems)
    VOLUME, MUTE, BASS, TREBLE, BASS_BOOST, VOLUME+, VOLUME-, BASS+, BASS-, TREBLE+, TREBLE-
    # Application Launchers (Windows 10 only so far)
    EMAILREADER, CALCULATOR, FILEBROWSER
    # Browser/File Explorer Controls (Firefox on Windows/Android only)
    SEARCH, HOME, BACK, FORWARD, STOP, REFRESH, BOOKMARKS
# Toggle the sound on the bonded central device
AT+BLEHIDCONTROLKEY=MUTE
OK
 
# Hold the VOLUME+ key for 500ms
AT+BLEHIDCONTROLKEY=VOLUME+,500
OK
 
# Send a raw 16-bit Consumer Key Code (0x006F = Brightness+)
AT+BLEHIDCONTROLKEY=0x006F
OK
  • AT+GAPGETCONN : 현재 접속 상태를 출력 (1 if we are connected, otherwise 0)
  • AT+GAPDISCONNECT : 접속을 끊음
  • AT+GAPDEVNAME : 장치 이름을 출력, 설정. 설정 후 리셋 필요
# Read the current device name
AT+GAPDEVNAME
UART
OK
  
# Update the device name to 'BLEFriend'
AT+GAPDEVNAME=BLEFriend
OK
# Reset to take effect
ATZ
OK
  • AT+GAPDELBONDS : 연결 정보(bonding information)를 삭제
  • AT+GAPINTERVALS : advertising, connection 간격을 설정. 실제 페어링 과정에 영향을 크게 미치므로 변경시 주의 요망.
    Minimum connection interval (in milliseconds)
    Maximum connection interval (in milliseconds)
    Advertising interval (in milliseconds)
    Advertising timeout (in milliseconds)
# Read the current GAP intervals
AT+GAPINTERVALS
20,100,100,30
  
# Update all values
AT+GAPINTERVALS=20,200,200,30
OK
  
# Update only the advertising interval
AT+GAPINTERVALS=,,150,
OK
  • AT+GAPSTARTADV : 연결 상태가 아닌 경우 advertising packet을 전송
# Command results when advertising data is not being sent
AT+GAPSTARTADV
OK
  
# Command results when we are already advertising
AT+GAPSTARTADV
ERROR
  
# Command results when we are connected to another device
AT+GAPSTARTADV
ERROR
# Advertise as Discoverable and BLE only with 16-bit UUIDs 0x180D and 0x180A
AT+GAPSETADVDATA=02-01-06-05-02-0d-18-0a-18
OK
  • 아래 GATT 커맨드는 custom GATT service, characteristic 을 만들 때 사용. 대부분의 GATT 커맨드는 적용을 위해서 reset이 필요함.
  • AT+GATTCLEAR : custom service, characteristic 정보를 삭제
  • AT+GATTADDSERVICE : custom service 생성
    Parameters: This command accepts a set of comma-separated key-value pairs that are used to define the service properties. The following key-value pairs can be used:
    UUID: The 16-bit UUID to use for this service. 16-bit values should be in hexadecimal format (0x1234).
    UUID128: The 128-bit UUID to use for this service. 128-bit values should be in the following format: 00-11-22-33-44-55-66-77-88-99-AA-BB-CC-DD-EE-FF
# Clear any previous custom services/characteristics
AT+GATTCLEAR
OK
 
# Add a battery service (UUID = 0x180F) to the peripheral
AT+GATTADDSERVICE=UUID=0x180F
1
OK
  
# Add a battery measurement characteristic (UUID = 0x2A19), notify enabled
AT+GATTADDCHAR=UUID=0x2A19,PROPERTIES=0x10,MIN_LEN=1,VALUE=100
1
OK
# Clear any previous custom services/characteristics
AT+GATTCLEAR
OK
 
# Add a custom service to the peripheral
AT+GATTADDSERVICE=UUID128=00-11-00-11-44-55-66-77-88-99-AA-BB-CC-DD-EE-FF
1
OK
 
# Add a custom characteristic to the above service (making sure that there
# is no conflict between the 16-bit UUID and bytes 3+4 of the 128-bit service UUID)
AT+GATTADDCHAR=UUID=0x0002,PROPERTIES=0x02,MIN_LEN=1,VALUE=100
1
OK
  • AT+GATTADDCHAR : custom characteristic 을 마지막에 추가한 service에 붙여서 추가. 따라서 반드시 AT+GATTADDSERVICE 커맨드로 서비스를 추가한 뒤 사용해야 함. 상세한 내용은 링크 참고.
    Parameters: This command accepts a set of comma-separated key-value pairs that are used to define the characteristic properties. The following key-value pais can be used:
    UUID: The 16-bit UUID to use for the characteristic (which will be insert in the 3rd and 4th bytes of the parent services 128-bit UUID). This value should be entered in hexadecimal format (ex. ‘UUID=0x1234’). This value must be unique, and should not conflict with bytes 3+4 of the parent service’s 128-bit UUID.
    PROPERTIES: The 8-bit characteristic properties field, as defined by the Bluetooth SIG. The following values can be used:
    0x02 – Read
    0x04 – Write Without Response
    0x08 – Write
    0x10 – Notify
    0x20 – Indicate
    MIN_LEN: The minimum size of the values for this characteristic (in bytes, min = 1, max = 20, default = 1)
    MAX_LEN: The maximum size of the values for the characteristic (in bytes, min = 1, max = 20, default = 1)
    VALUE: The initial value to assign to this characteristic (within the limits of ‘MIN_LEN’ and ‘MAX_LEN’). Value can be an integer (“-100”, “27”), a hexadecimal value (“0xABCD”), a byte array (“aa-bb-cc-dd”) or a string (“GATT!”).
# Clear any previous custom services/characteristics
AT+GATTCLEAR
OK
 
# Add a battery service (UUID = 0x180F) to the peripheral
AT+GATTADDSERVICE=UUID=0x180F
1
OK
  
# Add a battery measurement characteristic (UUID = 0x2A19), notify enabled
AT+GATTADDCHAR=UUID=0x2A19,PROPERTIES=0x10,MIN_LEN=1,VALUE=100
1
OK
# Clear any previous custom services/characteristics
AT+GATTCLEAR
OK
 
# Add a custom service to the peripheral
AT+GATTADDSERVICE=UUID128=00-11-00-11-44-55-66-77-88-99-AA-BB-CC-DD-EE-FF
1
OK
 
# Add a custom characteristic to the above service (making sure that there
# is no conflict between the 16-bit UUID and bytes 3+4 of the 128-bit service UUID)
AT+GATTADDCHAR=UUID=0x0002,PROPERTIES=0x02,MIN_LEN=1,VALUE=100
1
OK
# Add a custom characteristic to the above service using a
# custom 128-bit UUID
AT+GATTADDCHAR=UUID128=00-11-22-33-44-55-66-77-88-99-AA-BB-CC-DD-EE-FF,PROPERTIES=0x02,MIN_LEN=1,VALUE=100
1
OK
  • AT+GATTCHAR : GATT characteristic의 값을 가져오거나 설정함. AT+GATTADDCHAR 로 설정했을 때 출력되는 인덱스 ID가 필요.
    Parameters: This function takes one or two comma-separated functions (one parameter = read, two parameters = write).
    The first parameter is the characteristic index value, as returned from the AT+GATTADDCHAR function. This parameter is always required, and if no second parameter is entered the current value of this characteristic will be returned.
    The second (optional) parameter is the new value to assign to this characteristic (within the MIN_SIZE and MAX_SIZE limits defined when creating it).
# Clear any previous custom services/characteristics
AT+GATTCLEAR
OK
 
# Add a battery service (UUID = 0x180F) to the peripheral
AT+GATTADDSERVICE=UUID=0x180F
1
OK
  
# Add a battery measurement characteristic (UUID = 0x2A19), notify enabled
AT+GATTADDCHAR=UUID=0x2A19,PROPERTIES=0x10,MIN_LEN=1,VALUE=100
1
OK
 
# Read the battery measurement characteristic (index ID = 1)
AT+GATTCHAR=1
0x64
OK
 
# Update the battery measurement characteristic to 32 (hex 0x20)
AT+GATTCHAR=1,32
OK
 
# Verify the previous write attempt
AT+GATTCHAR=1
0x20
OK
  • AT+GATTLIST : custom GATT service, characteristic을 모두 출력
# Clear any previous custom services/characteristics
AT+GATTCLEAR
OK
 
# Add a battery service (UUID = 0x180F) to the peripheral
AT+GATTADDSERVICE=UUID=0x180F
1
OK
  
# Add a battery measurement characteristic (UUID = 0x2A19), notify enabled
AT+GATTADDCHAR=UUID=0x2A19,PROPERTIES=0x10,MIN_LEN=1,VALUE=100
1
OK
  
# Add a custom service to the peripheral
AT+GATTADDSERVICE=UUID128=00-11-00-11-44-55-66-77-88-99-AA-BB-CC-DD-EE-FF
2
OK
 
# Add a custom characteristic to the above service (making sure that there
# is no conflict between the 16-bit UUID and bytes 3+4 of the 128-bit service UUID)
AT+GATTADDCHAR=UUID=0x0002,PROPERTIES=0x02,MIN_LEN=1,VALUE=100
2
OK
 
# Get a list of all custom GATT services and characteristics on the device
AT+GATTLIST
ID=01,UUID=0x180F
  ID=01,UUID=0x2A19,PROPERTIES=0x10,MIN_LEN=1,MAX_LEN=1,VALUE=0x64
ID=02,UUID=0x11, UUID128=00-11-00-11-44-55-66-77-88-99-AA-BB-CC-DD-EE-FF
  ID=02,UUID=0x02,PROPERTIES=0x02,MIN_LEN=1,MAX_LEN=1,VALUE=0x64
OK
  • AT+DBGMEMRD : 메모리 특정 주소의 상태를 출력
    Parameters: The following comma-separated parameters can be used with this command:
    The starting address to read memory from (in hexadecimal form, with or without the leading ‘0x’)
    The word size (can be 1, 2, 4 or 8)
    The number of words to read
  •  AT+DBGNVMREAD : 비휘발성 메모리에 저장된 설정 정보를 출력
  • AT+DBGSTACKSIZE : 스택 사이즈 출력
  • AT+DBGSTACKDUMP : 스택의 데이터 출력

UART Service

Adafruit Bluefruit LE 모듈은 대부분의 BLE 모듈처럼 별다른 설정 변경 없이도 UART로 연결된(TX, RX 핀으로) MCU와 무선으로 연결된 장치(PC, 폰)가 서로 통신할 수 있도록 해줍니다. 이걸 UART service라고 부르며 블루투스 모듈 내부에 이를 지원하기 위한 GATT/Service/Characteristic 설정이 들어가 있습니다. 아무런 설정 변경없이 휴대폰과 블루투스 모듈을 페어링해서 통신할 준비가 갖춰지면 아래와 같은 설정을 사용하는 상태가 됩니다.

Base UUID: 6E400001-B5A3-F393-­E0A9-­E50E24DCCA9E

Name
TX
RX
Mandatory
Yes
Yes
UUID
0x0002
0x0003
Type
U8[20]
U8[20]
R
X
W

X

N
X
I

R = Read; W = Write; N = Notify; I = Indicate

TX (0x0002)

  • 블루투스 모듈이 연결된 장치(PC, 폰)에 데이터를 보낼 때 사용하는 characteristic 입니다. Notify 항목이 활성화 되어 있으므로 TX 채널로 보낼 데이터가 있을 때 신호를 보내줍니다.

RX (0x0003)

  • 연결된 장치에서 블루투스 모듈로 데이터를 보내줄 때 사용하는 characteristic 입니다. PC, 폰과 같은 장치에서 데이터를 쓰는데 사용합니다.

버전 정보

현재 Adafruit Bluefruit LE 모듈용 펌웨어 최신 버전은 0.6.7(beta) 입니다. 버전별로 사용 가능한 AT 커맨드가 틀리므로 링크에서 확인하세요.

기타 유용한 SW

Bluefruit LE Connect (Android)

Bluefruit LE Connect (iOS)

Bluefruit LE Python Wrapper

앞서 보시다시피 굉장히 세부적인 설정을 조절할 수 있게 해주는 모듈이 nRF51822 입니다. 제대로 이 모듈을 활용하기 위해서는 모듈에 대한 지식 뿐 아니라 BLE 표준에 대한 지식도 상당량 요구됩니다. 블루투스 표준에 대한 기초 내용과 BLE 표준에 대한 내용은 링크를 참고하세요.

nRF51822 Eval Kit 과 펌웨어를 직접 개발/수정해서 업데이트 하는 방법은 추후 상세히 다루도록 하겠습니다.

주의!!!  : 아직 모듈이 입수되지 않아 100% 테스트 된 자료는 아닙니다. Adafruit Bluefruit LE 모듈이 아닌 경우 종류에 따라 내용과 맞지 않을 수 있습니다.

참고자료