ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Purdue Project] ArduinoBLE library를 사용하여 react-native app과 블루투스 통신
    Purdue Record 2022. 3. 12. 02:32

    react-native app과 블루투스 통신으로 데이터를 주고 받기 위해 ArduinoBLE library를 선택했다. 해당 라이브러리 reference를 읽어보았는데 우리가 선택한 arduino 보드인 arduino nano 33 iot를 지원한다고 해서 이 라이브러리로 진행했다. 하지만 reference가 빈약해서 힘들었다...

    https://www.arduino.cc/en/Reference/ArduinoBLE

     

    Arduino - ArduinoBLE

    Note: this page is no longer being maintained. For up to date documentation on this library, visit the new ArduinoBLE library page. --- This library supports all the Arduino boards that have the hardware enabled for BLE and Bluetooth® 4.0 and above; these

    www.arduino.cc

     

    스마트폰의 bluetooth와 연결하여 arduino에 연결된 심박, 산소포화도 센서의 데이터를 App으로 넘겨줘야했고 arduino에 연결된 진동모터 진동을 위한 시그널을 App으로부터 받아와야했다. ArduinoBLE 라이브러리의 예제 중에 Peripheral CallbackLED 예제를 사용하여 해당 틀 안에서 코드를 변경했다. 이 예제를 선택한 이유는 arduino는 지속적으로 데이터를 제공하기 때문에 Server인 Peripheral device가 되어야했고, App은 데이터를 제공 받기 때문에 Client, central device가 되어야했다. 따라서 server에 해당하는 적절한 예제여서 선택했다.


    ArduinoBLE 라이브러리 클래스 or 함수 설명

    • BLECharacteristic
      • 자료형 별로 BLECharacteristic 클래스가 준비됨
      • 매개변수로는 UUID, 속성, BLECharacteristic의 경우 문자열 데이터 전송을 위한 배열 크기
      • UUID의 경우 미리 정의된 번호가 있는 16bit UUID를 사용해도 되고 128비트 랜덤 UUID를 사용해도 됨
    • BLE.advertise()
      • arduino 장치를 주변 장치에 광고해 알리는 함수
      • 이를 통해 주변 장치는 arduino와 연결이 가능해짐
    • BLE.pool()
      • BLE 이벤트 발생 확인 함수
      • BLE connect, disconnect, characteristic written, read를 감지함

     


    코드

    예제는 블루투스 통신 시 write, read test를 위한 코드로 data는 임의로 설정했다. 10부터 시작하는 data를 5씩 증가시키면서 string으로 보내는 형식이다. 

    #include <ArduinoBLE.h>
    #include <stdio.h>
    #include <stdlib.h>
    BLEService ledService("2a1c"); // create service
    // create switch characteristic and allow remote device to read and write
    BLECharacteristic switchCharacteristic("2a1c", BLERead | BLEWrite | BLENotify, 20);
    
    void setup() {
      Serial.begin(9600);
      while (!Serial);
    
      // begin initialization
      if (!BLE.begin()) {
        Serial.println("starting BLE failed!");
    
        while (1);
      }
      Serial.println(BLE.address());
      BLE.setDeviceName("Yahoho arduino");
      // set the local name peripheral advertises
      BLE.setLocalName("TestBLE");
      // set the UUID for the service this peripheral advertises
      BLE.setAdvertisedServiceUuid(ledService.uuid());
    
      // add the characteristic to the service
      ledService.addCharacteristic(switchCharacteristic);
    
      // add service
      BLE.addService(ledService);
      switchCharacteristic.subscribe();
      // assign event handlers for connected, disconnected to peripheral
      BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
      BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
    
      // assign event handlers for characteristic
      switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
      switchCharacteristic.setEventHandler(BLERead, switchCharacteristicRead);
      // set an initial value for the characteristic
    
      // start advertising
      Serial.println(BLE.advertise());
      Serial.print("characteristic count:");
      Serial.print(ledService.characteristicCount());
      Serial.println();
      Serial.println(("Mirae's Arduino : Bluetooth device active, waiting for connections..."));
    }
    
    void loop() {
      // poll for BLE events
      static int num = 10;
      BLE.poll();
    
      BLEDevice central = BLE.central();
      
      if (central.connected()) {
        char nnum[20];
        itoa(num, nnum, 10);
    
        Serial.println(num);
        if (switchCharacteristic.subscribed()) {
          switchCharacteristic.writeValue(nnum);
          delay(3000);
        }
        num += 5;
      }
    }
    
    void blePeripheralConnectHandler(BLEDevice central) {
      // central connected event handler
      Serial.print("Connected event, central: ");
      Serial.println(central.address());
    }
    
    void blePeripheralDisconnectHandler(BLEDevice central) {
      // central disconnected event handler
      Serial.print("Disconnected event, central: ");
      Serial.println(central.address());
    }
    void switchCharacteristicRead(BLEDevice central, BLECharacteristic characteristic) {
      // characteristic wrote new value to central
      Serial.print("Characteristic event, read: ");
      //  Serial.println(switchCharacteristic.value());
    }
    void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) {
      // central wrote new value to characteristic
      if (switchCharacteristic.value() == 48) { // 48 is zero
        Serial.print("Characteristic event, written 0: ");
        Serial.print(switchCharacteristic.value());
        Serial.println();
      }
      else{ // 49 is one
        Serial.print("Characteristic event, written 1: ");
        Serial.print(switchCharacteristic.value());
        Serial.println();
      }
    }

     

    댓글

Designed by Tistory.