diff --git a/examples/Nano33BLESenseFirmware/Nano33BLESenseFirmware.ino b/examples/Nano33BLESenseFirmware/Nano33BLESenseFirmware.ino index 8375a67..3cdd20e 100644 --- a/examples/Nano33BLESenseFirmware/Nano33BLESenseFirmware.ino +++ b/examples/Nano33BLESenseFirmware/Nano33BLESenseFirmware.ino @@ -12,6 +12,8 @@ const int VERSION = 0x00000001; const float TEMPERATURE_CALIBRATION = -5.0; #define SCIENCE_KIT_UUID(val) ("555a0002-" val "-467a-9538-01f0652c74e8") +#define RESISTANCE_PIN A0 +#define VOLTAGE_BUFFER_SIZE 16 //#define DEBUG 0 @@ -26,8 +28,12 @@ BLEFloatCharacteristic humidityCharacteristic (SCIENCE_KIT_UUID("001 BLEUnsignedIntCharacteristic proximityCharacteristic (SCIENCE_KIT_UUID("0017"), BLENotify); BLECharacteristic colorCharacteristic (SCIENCE_KIT_UUID("0018"), BLENotify, 4 * sizeof(int)); BLEUnsignedShortCharacteristic soundPressureCharacteristic(SCIENCE_KIT_UUID("0019"), BLENotify); +BLEFloatCharacteristic resistanceCharacteristic (SCIENCE_KIT_UUID("0020"), BLENotify); +byte voltageBufferIndex = 0; +bool voltageBufferFilled = false; short soundSampleBuffer[256]; +short voltageSampleBuffer[VOLTAGE_BUFFER_SIZE]; void onPDMdata() { // query the number of bytes available @@ -45,6 +51,23 @@ uint16_t getSoundAverage() { return sqrt(avg); } +void readVoltage() { + voltageSampleBuffer[voltageBufferIndex] = analogRead(RESISTANCE_PIN); + if (!voltageBufferFilled && voltageBufferIndex == VOLTAGE_BUFFER_SIZE - 1) { + voltageBufferFilled = true; + } + voltageBufferIndex = (++voltageBufferIndex) % VOLTAGE_BUFFER_SIZE; +} + +uint16_t getVoltageAverage() { + uint16_t avg = 0; + byte upperBound = voltageBufferFilled ? VOLTAGE_BUFFER_SIZE : voltageBufferIndex; + for (int i = 0; i < upperBound; i++) { + avg += voltageSampleBuffer[i]; + } + return avg / upperBound; +} + // String to calculate the local and device name String name; unsigned long lastNotify = 0; @@ -75,6 +98,8 @@ void setup() { delay(2000); + pinMode(RESISTANCE_PIN, INPUT); // Used for reading resistance + if (!APDS.begin()) { printSerialMsg("Failed to initialized APDS!"); blinkLoop(); @@ -142,6 +167,7 @@ void setup() { service.addCharacteristic(proximityCharacteristic); service.addCharacteristic(colorCharacteristic); service.addCharacteristic(soundPressureCharacteristic); + service.addCharacteristic(resistanceCharacteristic); versionCharacteristic.setValue(VERSION); @@ -213,4 +239,11 @@ void updateSubscribedCharacteristics() { float pressure = BARO.readPressure(); pressureCharacteristic.writeValue(pressure); } + + if(resistanceCharacteristic.subscribed()){ + readVoltage(); + uint16_t measuredValue = getVoltageAverage(); + float voltageRatio = 1024.0f / measuredValue; + resistanceCharacteristic.writeValue(voltageRatio); + } }