Skip to content

Instantly share code, notes, and snippets.

@hidenba
Created July 18, 2016 22:24
Show Gist options
  • Save hidenba/a89621dca8afed996264437c7ce90b32 to your computer and use it in GitHub Desktop.
Save hidenba/a89621dca8afed996264437c7ce90b32 to your computer and use it in GitHub Desktop.
ArduinoのanalogINをBLEで使う
#include <CurieBLE.h>
const int ledPin = 13; // set ledPin to use on-board LED
BLEPeripheral blePeripheral; // create peripheral instance
BLEService alcoholService("29B10000-E8F2-537E-4F6C-D104768A1214"); // create service
BLEShortCharacteristic alcoholChar("29B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite | BLENotify);
const int termLedPin = 13;
const int alcoholSensorPin = 0;
void setup() {
Serial.begin(9600);
while (!Serial) {}
Serial.println("start setup");
pinMode(ledPin, OUTPUT); // use the LED on pin 13 as an output
blePeripheral.setLocalName("LED_ALC");
blePeripheral.setAdvertisedServiceUuid(alcoholService.uuid());
blePeripheral.addAttribute(alcoholService);
blePeripheral.addAttribute(alcoholChar);
blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
alcoholChar.setEventHandler(BLEWritten, alcoholCharacteristicWritten);
alcoholChar.setValue(0);
blePeripheral.begin();
Serial.println(("Bluetooth device active, waiting for connections..."));
}
void loop() {
blePeripheral.poll();
}
void blePeripheralConnectHandler(BLECentral& central) {
// central connected event handler
Serial.print("Connected event, central: ");
Serial.println(central.address());
}
void blePeripheralDisconnectHandler(BLECentral& central) {
// central disconnected event handler
Serial.print("Disconnected event, central: ");
Serial.println(central.address());
}
void alcoholCharacteristicWritten(BLECentral& central, BLECharacteristic& characteristic) {
digitalWrite(termLedPin, HIGH);
int values[10];
int arrayIndex = 0;
int tmpValue=0;
for(int i = 0; i < 10; i++) {
int value = analogRead(alcoholSensorPin);
Serial.println(value);
if (i==0){
values[arrayIndex] = value;
arrayIndex++;
} else if(tmpValue != value) {
values[arrayIndex] = value;
arrayIndex++;
}
tmpValue = value;
delay(500);
}
qsort(values, 10, sizeof(int), comp);
int uniqValues[arrayIndex];
int index=0;
for(int i=9; i>(9-arrayIndex); i--){
uniqValues[index] = values[i];
index++;
}
digitalWrite(termLedPin, LOW);
int memValue = 1024 - uniqValues[arrayIndex/2];
alcoholChar.setValue(memValue);
Serial.print("=============");
Serial.print(memValue);
Serial.println("=============");
}
int comp( const void *c1, const void *c2 )
{
int tmp1 = *(int *)c1;
int tmp2 = *(int *)c2;
if( tmp1 < tmp2 ) return -1;
if( tmp1 == tmp2 ) return 0;
if( tmp1 > tmp2 ) return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment