Nick Zhou / ST_BLE_IDB0XA1

Dependencies:   BLE_API X_NUCLEO_IDB0XA1 X_NUCLEO_IKS01A1 mbed-src-ST-demo

Fork of BLE_HeartRate_IDB0XA1 by ST

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2015 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #include "mbed.h"
00018 #include "ble/BLE.h"
00019 #include "ble/services/HeartRateService.h"
00020 #include "x_nucleo_iks01a1.h"
00021 
00022 Serial pc(SERIAL_TX, SERIAL_RX);
00023 
00024 DigitalOut led1(LED1, 1);
00025 
00026 /* Instantiate the expansion board */
00027 static X_NUCLEO_IKS01A1 *mems_expansion_board = X_NUCLEO_IKS01A1::Instance(D14, D15);
00028 
00029 /* Retrieve the composing elements of the expansion board */
00030 static GyroSensor *gyroscope = mems_expansion_board->GetGyroscope();
00031 static MotionSensor *accelerometer = mems_expansion_board->GetAccelerometer();
00032 static MagneticSensor *magnetometer = mems_expansion_board->magnetometer;
00033 static HumiditySensor *humidity_sensor = mems_expansion_board->ht_sensor;
00034 static PressureSensor *pressure_sensor = mems_expansion_board->pt_sensor;
00035 static TempSensor *temp_sensor1 = mems_expansion_board->ht_sensor;
00036 static TempSensor *temp_sensor2 = mems_expansion_board->pt_sensor;
00037 
00038 /* Helper function for printing floats & doubles */
00039 static char *printDouble(char* str, double v, int decimalDigits=2)
00040 {
00041   int i = 1;
00042   int intPart, fractPart;
00043   int len;
00044   char *ptr;
00045 
00046   /* prepare decimal digits multiplicator */
00047   for (;decimalDigits!=0; i*=10, decimalDigits--);
00048 
00049   /* calculate integer & fractinal parts */
00050   intPart = (int)v;
00051   fractPart = (int)((v-(double)(int)v)*i);
00052 
00053   /* fill in integer part */
00054   sprintf(str, "%i.", intPart);
00055 
00056   /* prepare fill in of fractional part */
00057   len = strlen(str);
00058   ptr = &str[len];
00059 
00060   /* fill in leading fractional zeros */
00061   for (i/=10;i>1; i/=10, ptr++) {
00062     if(fractPart >= i) break;
00063     *ptr = '0';
00064   }
00065 
00066   /* fill in (rest of) fractional part */
00067   sprintf(ptr, "%i", fractPart);
00068 
00069   return str;
00070 }
00071 
00072 const static char     DEVICE_NAME[]        = "HRM1";
00073 static const uint16_t uuid16_list[]        = {GattService::UUID_HEART_RATE_SERVICE};
00074 
00075 static volatile bool  triggerSensorPolling = false;
00076 
00077 void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
00078 {
00079     (void)params;
00080     BLE::Instance().gap().startAdvertising(); // restart advertising
00081 }
00082 
00083 void periodicCallback(void)
00084 {
00085     led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */
00086     /* Note that the periodicCallback() executes in interrupt context, so it is safer to do
00087      * heavy-weight sensor polling from the main thread. */
00088     triggerSensorPolling = true;
00089 }
00090 
00091 void onBleInitError(BLE &ble, ble_error_t error)
00092 {
00093     (void)ble;
00094     (void)error;
00095    /* Initialization error handling should go here */
00096 }
00097 
00098 void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
00099 {
00100     BLE&        ble   = params->ble;
00101     ble_error_t error = params->error;
00102 
00103   uint8_t id;
00104   float value1, value2;
00105   char buffer1[32], buffer2[32];
00106   int32_t axes[3];
00107 
00108     
00109     pc.printf("1\n");
00110     if (error != BLE_ERROR_NONE) {
00111         onBleInitError(ble, error);
00112         return;
00113     }
00114     pc.printf("2\n");
00115     if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
00116         return;
00117     }
00118     pc.printf("3\n");
00119     ble.gap().onDisconnection(disconnectionCallback);
00120 
00121     /* Setup primary service. */
00122     uint8_t hrmCounter = 100; // init HRM to 100bps
00123     HeartRateService hrService(ble, hrmCounter, HeartRateService::LOCATION_FINGER);
00124     pc.printf("4\n");
00125     /* Setup advertising. */
00126     ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
00127     ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
00128     ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_HEART_RATE_SENSOR);
00129     ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
00130     ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
00131     ble.gap().setAdvertisingInterval(1000); /* 1000ms */
00132     ble.gap().startAdvertising();
00133     pc.printf("5\n");
00134     
00135   humidity_sensor->ReadID(&id);
00136   pc.printf("HTS221  humidity & temperature    = 0x%X\r\n", id);
00137   pressure_sensor->ReadID(&id);
00138   pc.printf("LPS25H  pressure & temperature    = 0x%X\r\n", id);
00139   magnetometer->ReadID(&id);
00140   pc.printf("LIS3MDL magnetometer              = 0x%X\r\n", id);
00141   gyroscope->ReadID(&id);
00142   pc.printf("LSM6DS0 accelerometer & gyroscope = 0x%X\r\n", id);
00143   
00144   wait(3);
00145       
00146     // infinite loop
00147     while (true) {
00148         // check for trigger from periodicCallback()
00149     //pc.printf("6\n");        
00150         if (triggerSensorPolling && ble.getGapState().connected) {
00151             triggerSensorPolling = false;
00152 
00153             // Do blocking calls or whatever is necessary for sensor polling.
00154             // In our case, we simply update the HRM measurement.
00155             hrmCounter++;
00156 
00157             //  100 <= HRM bps <=175
00158             if (hrmCounter == 175) {
00159                 hrmCounter = 100;
00160             }
00161 
00162             // update bps
00163             hrService.updateHeartRate(hrmCounter);
00164 
00165     temp_sensor1->GetTemperature(&value1);
00166     humidity_sensor->GetHumidity(&value2);
00167     pc.printf("HTS221: [temp] %7s°C,   [hum] %s%%\r\n", printDouble(buffer1, value1), printDouble(buffer2, value2));
00168     
00169     temp_sensor2->GetFahrenheit(&value1);
00170     pressure_sensor->GetPressure(&value2);
00171     pc.printf("LPS25H: [temp] %7s°F, [press] %smbar\r\n", printDouble(buffer1, value1), printDouble(buffer2, value2));
00172 
00173     pc.printf("---\r\n");
00174 
00175     magnetometer->Get_M_Axes(axes);
00176     pc.printf("LIS3MDL [mag/mgauss]:  %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
00177 
00178     accelerometer->Get_X_Axes(axes);
00179     pc.printf("LSM6DS0 [acc/mg]:      %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
00180 
00181     gyroscope->Get_G_Axes(axes);
00182     pc.printf("LSM6DS0 [gyro/mdps]:   %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
00183             
00184         } else {
00185             ble.waitForEvent(); // low power wait for event
00186         }
00187     }
00188 }
00189 
00190 int main(void)
00191 {
00192     
00193     Ticker ticker;
00194     pc.printf("Hello World !\n");        
00195     ticker.attach(periodicCallback, 1); // blink LED every second
00196 
00197     BLE::Instance().init(bleInitComplete);
00198 }