SWDesk/App
[Kotlin] Nano33 IoT 기기와 데이터 통신하기
inhae
2023. 2. 20. 18:21
[MainActivity]
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import java.io.IOException
import java.util.*
val deviceAddress = "00:00:00:00:00:00" // Replace with the address of your nano33iot device
val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // UUID for serial communication
var bluetoothSocket: BluetoothSocket? = null
val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
// Check if device supports Bluetooth
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
} else {
// Device supports Bluetooth
// Check if Bluetooth is enabled on device
if (!bluetoothAdapter.isEnabled) {
// Request to enable Bluetooth
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
// Get the Bluetooth device by its address
val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice(deviceAddress)
// Connect to the device using a Bluetooth socket
try {
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid)
bluetoothSocket.connect()
} catch (e: IOException) {
// Connection failed
}
// Send a message to the device
val outputStream = bluetoothSocket.outputStream
val message = "Hello from Android phone"
val bytes = message.toByteArray()
outputStream.write(bytes)
// Receive a message from the device
val inputStream = bluetoothSocket.inputStream
val buffer = ByteArray(1024)
val numBytes = inputStream.read(buffer)
val receivedMessage = String(buffer, 0, numBytes)
}
// Close the Bluetooth socket when finished
try {
bluetoothSocket?.close()
} catch (e: IOException) {
// Error occurred while closing the socket
}
[Nano33 IoT] by Arduino-IDE
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
BLECharacteristic *pCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;
String receivedMessage = "";
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
}
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
void setup() {
Serial.begin(9600);
BLEDevice::init("nano33iot");
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
pCharacteristic->setValue("Hello from nano33iot");
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0
반응형