//server #include #include #include #include #include #include // BLE Server name (the other ESP32 name running the server sketch) #define bleServerName "XIAOESP32C6_BLE" // Phototransistor pin const int phototransistorPin = D2; // Pin D2 (GPIO2) BLECharacteristic *pCharacteristic; bool deviceConnected = false; int light_val = 0; class MyServerCallbacks : public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; } }; void setup() { // Start the serial communication Serial.begin(115200); // Set the phototransistor pin as input pinMode(phototransistorPin, INPUT); // Initialize BLE BLEDevice::init(bleServerName); BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); BLEService *pService = pServer->createService(BLEUUID((uint16_t)0x181A)); // Environmental Sensing pCharacteristic = pService->createCharacteristic( BLEUUID((uint16_t)0x2A59), // Analog Output BLECharacteristic::PROPERTY_NOTIFY ); pCharacteristic->addDescriptor(new BLE2902()); pService->start(); BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); pAdvertising->addServiceUUID(pService->getUUID()); pAdvertising->setScanResponse(true); pAdvertising->setMinPreferred(0x0); pAdvertising->setMinPreferred(0x1F); BLEDevice::startAdvertising(); Serial.println("Starting BLE Server..."); } void loop() { if (deviceConnected) { // Read the light value from the phototransistor light_val = analogRead(phototransistorPin); light_val = map(light_val,100,3300,255,0); // Send the value via BLE notification pCharacteristic->setValue(light_val); pCharacteristic->notify(); // Display the light value in the Serial Monitor Serial.print("Light Value: "); Serial.println(light_val); Serial.println("Sending data via BLE..."); delay(1000); // Bluetooth stack will go into congestion if too many packets are sent } }