sandeepmistry / arduino-BLEPeripheral

An Arduino library for creating custom BLE peripherals with Nordic Semiconductor's nRF8001 or nR51822.
MIT License
462 stars 179 forks source link

Advertising Battery levels on iBeacon #246

Open Autobot86 opened 5 years ago

Autobot86 commented 5 years ago

How to add BLE batteryService to Beacon code

include

include

include

if !defined(NRF51) && !defined(NRF52) && !defined(RFduino)

error "This example only works with nRF51 boards"

endif

// int GI_Bat_Pin = A4; // Board pin p0.30 float temperature, pressure, altitude, VBAT;

BLEPeripheral blePeripheral ; iBeacon beacon; BLECentral central = blePeripheral.central(); uint16_t level = 0; uint8_t lastBattLevelReading = 0;

char* Data = "a196c876-de8c-4c47-1234-d7afd5ae7127"; unsigned short major = 10035; unsigned short minor = 47647; unsigned short measuredPower = -55;

BLEService batteryService = BLEService("180F"); BLEUnsignedCharCharacteristic battlevelCharacteristic = BLEUnsignedCharCharacteristic("2A19", BLERead | BLENotify); // battery level is uint8_t BLEDescriptor battlevelDescriptor = BLEDescriptor("2901", "Battery Level 0 - 100"); void setup() { Serial.begin(115200); pinMode(GI_Bat_Pin, INPUT); analogReadResolution(12); BLE_channel_selection(); beacon.setAdvertisingInterval(2000); beacon.begin(Data, major, minor, level);

if (blePeripheral.setTxPower(4)) Serial.println("Set TX power"); blePeripheral.setAdvertisedServiceUuid(batteryService.uuid()); blePeripheral.addAttribute(batteryService);

}

void loop() { beacon.loop(); level = analogRead(GI_Bat_Pin); // sample ADC to get battery voltage level VBAT = (127.0f / 100.0f) 3.30f ((float)level) / 4095.0f; // convert to the LiPo battery voltage Serial.print("VBAT = "); Serial.println(VBAT, 2); uint8_t battlevel = map(level, 0, 4095, 0, 100); // map battery level from 0 - 100 % battlevelCharacteristic.setValue((uint8_t)battlevel); // set the battery level characteristic value

delay(1000); }