// https://rootsaid.com/arduino-ble-example/ // Modified C. Chazot - March 2021 // Characteristic info. // https://www.arduino.cc/en/Reference/ArduinoBLEBLECharacteristicBLECharacteristic #include #include // Device name const char* nameOfPeripheral = "Arduino BLE 33"; const char* uuidOfService = "00001101-0000-1000-8000-00805f9b34fb"; const char* uuidOfTxString = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"; // UART // BLE Service BLEService UARTService(uuidOfService); // RX / TX Characteristics BLEStringCharacteristic txString(uuidOfTxString, BLERead | BLENotify | BLEBroadcast, 20); void setup() { // Start serial. Serial.begin(9600); // Ensure serial port is ready. while (!Serial); if (!HTS.begin()) { Serial.println("Failed to initialize humidity temperature sensor!"); while (1); } // Prepare LED pins. pinMode(LED_BUILTIN, OUTPUT); pinMode(LEDR, OUTPUT); pinMode(LEDG, OUTPUT); // Start BLE. startBLE(); // Create BLE service and characteristics. BLE.setLocalName(nameOfPeripheral); BLE.setAdvertisedService(UARTService); UARTService.addCharacteristic(txString); BLE.addService(UARTService); // Bluetooth LE connection handlers. BLE.setEventHandler(BLEConnected, onBLEConnected); BLE.setEventHandler(BLEDisconnected, onBLEDisconnected); // Let's tell devices about us. BLE.advertise(); // Print out full UUID and MAC address. Serial.println("Peripheral advertising info: "); Serial.print("Name: "); Serial.println(nameOfPeripheral); Serial.print("MAC: "); Serial.println(BLE.address()); Serial.print("Service UUID: "); Serial.println(UARTService.uuid()); Serial.print("UART UUID: "); Serial.println(uuidOfTxString); Serial.println("Bluetooth device active, waiting for connections..."); } void loop() { BLEDevice central = BLE.central(); delay(200); if (central) { // Only send data if we are connected to a central device. while (central.connected()) { delay(200); float humidity = HTS.readHumidity(); char temp_byte = 0; int temp_int = 0; // print each of the sensor values Serial.print("Humidity = "); Serial.print(humidity); Serial.println(" %"); // print an empty line Serial.println(); connectedLight(); // temperature = HTS.readTemperature(); temp_int = (int) humidity; // for (int i = 0; i < samplesRead; i++) { txString.writeValue("Humidity:"+String(humidity)); // } // } } } else { disconnectedLight(); } } // BLUETOOTH void startBLE() { if (!BLE.begin()) { Serial.println("starting BLE failed!"); while (1); } } void onBLEConnected(BLEDevice central) { Serial.print("Connected event, central: "); Serial.println(central.address()); connectedLight(); } void onBLEDisconnected(BLEDevice central) { Serial.print("Disconnected event, central: "); Serial.println(central.address()); disconnectedLight(); } // LEDS void connectedLight() { digitalWrite(LEDR, LOW); digitalWrite(LEDG, HIGH); } void disconnectedLight() { digitalWrite(LEDR, HIGH); digitalWrite(LEDG, LOW); }