블루투스
본문 바로가기
카테고리 없음

블루투스

by 하고싶은거하는여자 2024. 10. 27.
728x90
반응형

저전력 근거리용

 

와이파이: 훨씬 많은 전력을 사용

블루투스 :

 

iot 기기 : 일반적으로 블루투스 많이 사용

 - 정보가 빨리 와야 할 이유는 없다

 

도로가 범위 한정되어 있는데

특정 주파수 채널을 쪼개서 사용중인데

블루투스 이어폰 사람들 많은 곳에 가면 끊킨다

연결이 100%  잘된다 보장 불가

가격대비 성능은 좋다

 

기존 블루투스 : 클래식 블루투스

 - 저 여기 있어요 라고 소리치는 

 - 기계가 주체가 된다

 

 

o ble :  검색 불가,

 - 특정 타겟만 가능

 - 맵핑에 의해 연결된다

 - 일반 블루투스로는 ble 못 찾는다

 - 날 찾는 애가 있나?

 - 저전력, 낮은 속도, 블루투스 보다 주파수 짧다

 - 비콘 고유 아이디를 찾아서 출결 처리 되는것 (ex. 내일배움 출결)

 - 비콘을 쏘고 주먹만한 사이즈가 벽에 붙어있다 (배터리 x 상시전원 연결필요 x)

 -서비스가 주체가 된다

 

 

o 시리얼 블루투스 터미널 APP

 - 앱에서 텍스트 전송 시 아두이노에서 줄바꿈으로 나타난다

 - 이 앱을 추천

 

 

<블루투스 앱과 연동 코드>

// 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
// Note: Pairing is authenticated automatically by this device

#include "BluetoothSerial.h"

String device_name = "★★★★★";

// Check if Bluetooth is available
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

// Check Serial Port Profile
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Port Profile for Bluetooth is not available or not enabled. It is only available for the ESP32 chip.
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin(device_name);  //Bluetooth device name
  //SerialBT.deleteAllBondedDevices(); // Uncomment this to delete paired devices; Must be called after begin
  Serial.printf("The device with name \"%s\" is started.\nNow you can pair it with Bluetooth!\n", device_name.c_str());
}

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

 

*아두이노 예제로 실행 했을 시에는 항상 저장 안함으로 해야 함

 

 

------------------------------------

 

LED 애노드 타입

 

항상 확인하고 다음단계 넘어가라

 

 

-----------------------------------------

 

 

UUID를 활용해서 블루투스 LED 모듈 제어

https://www.uuidgenerator.net/

 

Online UUID Generator Tool

Online UUID Generator Your Version 4 UUID: 52e1a794-367d-4dd6-befd-fbef5e3f17b5 Copy Refresh page to generate another.

www.uuidgenerator.net

 

 

 

Callback 함수

 

애노드 타입 

255면 불이 꺼진다

값을 정수로 저장하고

출력할때는 255를 빼야 값이 나온다

 

0일때 불이 켜지는 led이다

점으로 쪼개고 쪼갠값을 정수로

정수값으로 led 켜겠다

 

 

*esp32는 와이파이를 더 많이 사용한다

 

---------------------------------------------------------------

 

 

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" // 서비스 UUID 정의
#define RGB_CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" // RGB 특성 UUID
#define NOTIFY_CHARACTERISTIC_UUID "d501d731-f0f9-4121-a7f6-2c0f959f1583" // Notify 특성 UUID

// RED, GREEN, BLUE LED에 사용될 핀 번호 정의
#define RED_PIN 4
#define GREEN_PIN 15
#define BLUE_PIN 2

// RGB 값을 저장할 변수 초기화
int redValue = 0;
int greenValue = 0;
int blueValue = 0;

BLECharacteristic *pRGBCharacteristic = NULL; // BLE 특성 객체
BLECharacteristic *pNotifyCharacteristic = NULL; // Notify 특성 객체

// 콜백 클래스 정의
class MyCallbacks : public BLECharacteristicCallbacks {
  // 특성의 값을 읽어와 RGB 값을 파싱하고 LED를 제어
  void onWrite(BLECharacteristic *pRGBCharacteristic) {
    String value = pRGBCharacteristic->getValue();
    if (value.length() > 0) {
      int delimiterPos1 = value.indexOf('.');
      int delimiterPos2 = value.lastIndexOf('.');

      if (delimiterPos1 != std::string::npos && delimiterPos2 != std::string::npos && delimiterPos2 < value.length() - 1) {
        redValue = value.substring(0, delimiterPos1).toInt();
        greenValue = value.substring(delimiterPos1 + 1, delimiterPos2).toInt();
        blueValue = value.substring(delimiterPos2 + 1).toInt();

        analogWrite(RED_PIN, 255 - redValue);
        analogWrite(GREEN_PIN, 255 - greenValue);
        analogWrite(BLUE_PIN, 255 - blueValue);
      }
    }
  }
};

void setup() {
  Serial.begin(115200);
  Serial.println("Starting ESP32 BLE!");

  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);

  // BLE 초기화하고 이름을 "RGB LED Control Server"로 설정
  BLEDevice::init("aa-RGB LED Control Server");
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // RGB 특성 생성 및 설정
  pRGBCharacteristic = pService->createCharacteristic(
    RGB_CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_WRITE
  );
  pRGBCharacteristic->setCallbacks(new MyCallbacks());

  // Notify 특성 생성 및 설정
  pNotifyCharacteristic = pService->createCharacteristic(
    NOTIFY_CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_NOTIFY
  );
  pNotifyCharacteristic->setValue("#000000");
  pNotifyCharacteristic->addDescriptor(new BLE2902()); // BLE Descriptor 생성

  pService->start();
  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}

void loop() {
  char hexValue[8];
  sprintf(hexValue, "#%02X%02X%02X", redValue, greenValue, blueValue);
  pNotifyCharacteristic->setValue(hexValue);
  pNotifyCharacteristic->notify(); // Notify를 통해 값을 전달

  delay(100); // 알림 간격 조절
}

 

 

 

 

 

 

728x90
반응형

댓글