ST / Mbed 2 deprecated SunTracker_BLE

Dependencies:   BLE_API X_NUCLEO_6180XA1 X_NUCLEO_IDB0XA1 X_NUCLEO_IHM01A1 X_NUCLEO_IKS01A1 mbed

Fork of SunTracker_BLE by ST Expansion SW Team

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

Go to the documentation of this file.
00001 /**
00002  ******************************************************************************
00003  * @file    main.cpp
00004  * @author  Fabio Brembilla
00005  * @version V2.0.0
00006  * @date    May, 2016
00007  * @brief   SunTracker + BLE (Server) Vertical Application
00008  *          This application use IHM01A1, 6180XA1, IKS01A1, IDB0XA1 expansion boards
00009  ******************************************************************************
00010  * @attention
00011  *
00012  * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
00013  *
00014  * Redistribution and use in source and binary forms, with or without modification,
00015  * are permitted provided that the following conditions are met:
00016  *   1. Redistributions of source code must retain the above copyright notice,
00017  *      this list of conditions and the following disclaimer.
00018  *   2. Redistributions in binary form must reproduce the above copyright notice,
00019  *      this list of conditions and the following disclaimer in the documentation
00020  *      and/or other materials provided with the distribution.
00021  *   3. Neither the name of STMicroelectronics nor the names of its contributors
00022  *      may be used to endorse or promote products derived from this software
00023  *      without specific prior written permission.
00024  *
00025  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00026  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00027  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00028  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
00029  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00030  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
00031  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
00032  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
00033  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00034  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00035  *
00036  ******************************************************************************
00037  */
00038 
00039 /* Define --------------------------------------------------------------------*/
00040 
00041 #define FlightSense //6180XA1 Main (remove only for debug)
00042 #define EasySpin    //IHM01A1 Main (remove only for debug)
00043 #define Sensors     //IKS01A1 Option
00044 #define Ble         //IDB0XA1 Option
00045 //#define Debug     //Verbose about Printf
00046 
00047 /* Includes ------------------------------------------------------------------*/
00048 
00049 // Mbed specific header files
00050 #include "mbed.h"
00051 
00052 // Helper header files
00053 #include "DevSPI.h"
00054 #include "DevI2C.h"
00055 
00056 // Component specific header files
00057 #ifdef FlightSense
00058     #include "x_nucleo_6180xa1.h"
00059 #endif
00060 
00061 #ifdef EasySpin
00062     #include "l6474_class.h"
00063 #endif
00064 
00065 #ifdef Sensors
00066     #include "x_nucleo_iks01a1.h"
00067 #endif
00068 
00069 // C header files
00070 #include <string.h>
00071 #include <stdlib.h>
00072 #include <stdio.h>
00073 #include <assert.h>
00074 
00075 /* BlueTooth -----------------------------------------------------------------*/
00076 
00077 #ifdef Ble
00078 
00079 #include "debug.h" // Need for PRINTF
00080 #include "Utils.h" // Need for STORE_LE_16 and STORE_LE_32
00081 
00082 // Not need to re-define it, it is already defined into UUID.h, just use UUID:: when you call it
00083 //const unsigned   LENGTH_OF_LONG_UUID = 16;
00084 //typedef uint16_t ShortUUIDBytes_t;
00085 //typedef uint8_t  LongUUIDBytes_t[LENGTH_OF_LONG_UUID];
00086 
00087 typedef enum ConnectionStatus_t {
00088     DISCONNECTED    =0,
00089     CONNECTED       =1
00090 } cns_t;
00091 
00092 #define BLE_DEV_NAME "SunTracker"
00093 #define BLE_DEV_MAC 0xFC,0x03,0x02,0x01,0xFB,0xFA // SERVER address (must be set into CLIENT BLE_peer_address_BE)
00094 #define BLE_ADVERTISING_INTERVAL 100
00095 uint8_t dat[] = {0x01,0x80,0x00,0x00,0x78,0x00}; // Data Sent during Advertising, must respect a Standard ST
00096     
00097 #include "CustomControlService.h"
00098 #include "CustomSensorsService.h"
00099 
00100 static BLE *p_BLEdev = NULL;
00101 static CustomControlService *p_customcontrolservice = NULL;
00102 static CustomSensorService  *p_customsensorservice = NULL;
00103 
00104 #define FeatureStatus      0x00000800
00105 #define FeatureDifference  0x00001000
00106 #define FeaturePosition    0x00002000
00107 #define FeatureSunPanel    0x00004000
00108 
00109 #endif
00110 
00111 /* Definitions ---------------------------------------------------------------*/
00112 
00113 #define SET_ACC 400     // Set Motor Acceleration
00114 #define SET_DEC 400     // Set Motor Deceleration
00115 #define SET_MAX 200     // Set Motor MaxSpeed
00116 #define SET_MIN 100     // Set Motor MinSpeed
00117 #define STOP 1000       // Set Motor Stop Position
00118 #define TOLLERANCE 80   // Tollerance between Left and Right before Start Movement
00119 #define RANGE_1 250     // Range 1 for Motor Speed
00120 #define RANGE_2 500     // Range 2 for Motor Speed
00121 #define TIMEOUT_STA 0.5 // Timeout for Ticker Status (in second)
00122 #define TIMEOUT_DIF 0.1 // Timeout for Ticker Difference (in second)
00123 #define TIMEOUT_POS 0.1 // Timeout for Ticker Position (in second)
00124 #define TIMEOUT_SUN 0.5 // Timeout for Ticker SunPanel (in second)
00125 
00126 /* Variables -----------------------------------------------------------------*/
00127 
00128 int8_t dir=0;          // Motor Rotation Direction: 0 = Stop, 1 = Anticlockwise, 2 = Clockwise
00129 int8_t changedir=0;    // Change Direction: 0 = No, 1 = Yes
00130 int8_t arrest=0;       // Arrest: 0 = No, 1 = Yes
00131 int16_t babybear=0;    // Difference (in Lux) between Left and Right
00132 int32_t acc_data[3];   // Difference of Accelerometer
00133 int16_t diff=0;        // Babybear or Accelerometer difference [--> Send BLE]
00134 int16_t diff_abs=0;    // Abs of Babybear or Accelerometer difference
00135 int8_t left=0;         // Left Command for Rotate Direction
00136 int8_t right=0;        // Right Command for Rotate Direction
00137 int16_t pos=0;         // Motor Position [--> Send BLE]
00138 int16_t measure=0;     // ADC Value from SunPanel [--> Send BLE]
00139 char DisplayStr[5];    // Display String
00140 int16_t Status=0;      // Status Shown on Display: 0 = Idle, 1 = Motor Speed, 2 = Solar Panel Value, 3 = Manual Control [--> Send BLE]
00141 int16_t status_bb, status_t, status_b, status_l, status_r; // Babybear Status
00142 uint16_t TimeStamp=0;  // TimeStamp for BLE
00143 bool tickerSta=false;
00144 bool tickerDif=false;
00145 bool tickerPos=false;
00146 bool tickerSun=false;
00147 bool BLEConnected=false;// BLE Connection Status
00148 
00149 /* Initializations ------------------------------------------------------------*/
00150 
00151 // Initializing SPI bus
00152 DevSPI dev_spi(D11, D12, D13);
00153 
00154 // Initializing I2C bus
00155 DevI2C dev_i2c(D14, D15);
00156 
00157 #ifdef FlightSense
00158 // Initializing FlightSense Component 6180XA1
00159 static X_NUCLEO_6180XA1 *board;
00160 MeasureData_t data_sensor_top, data_sensor_bottom, data_sensor_left, data_sensor_right;
00161 #endif
00162 
00163 #ifdef EasySpin
00164 // Initializing EasySpin Component IHM01A1
00165 static L6474 *motor;
00166 #endif
00167 
00168 #ifdef Sensors    
00169 // Initializing Sensors Component IKS01A1
00170 static X_NUCLEO_IKS01A1 *mems;
00171 MotionSensor *accelerometer;
00172 #endif
00173 
00174 InterruptIn mybutton(USER_BUTTON);
00175 
00176 AnalogIn analog_read(PC_3); // A1 Conflict with BLE SPI_CS --> Changed in Morpho PC_3
00177 
00178 /* Update_Status ------------------------------------------------------------*/
00179 
00180 void Update_Status(int16_t Stat)
00181 {
00182 
00183     char State[12]; // Characters into State must be <12 and never =>12 or it crash!!!
00184     if (Stat==1) strcpy(State,"FlightSense");
00185     if (Stat==2) strcpy(State,"ADCSunPanel");
00186     if (Stat==3) strcpy(State,"Sensors");
00187     printf("\r\n\r\nPUSH Status: %s", State);
00188 
00189 }
00190 
00191 /* User_Button_Pressed -------------------------------------------------------*/
00192 
00193 void User_Button_Pressed(void)
00194 {
00195 
00196     Status++;
00197 
00198 #ifdef Sensors //#ifdef Ble
00199     if (Status>3)  { Status=1; }
00200 #else
00201     if (Status>2)  { Status=1; }
00202 #endif 
00203 
00204     Update_Status(Status);
00205 
00206 }
00207 
00208 #ifdef Ble
00209 
00210 /* Bluetooth CallBack ---------------------------------------------------------*/
00211 
00212 static void onUpdatesEnabledCallback(GattAttribute::Handle_t handle)
00213 {
00214     if (p_customcontrolservice->isCommandHandle(handle)) p_customcontrolservice->enNotify(handle); 
00215     
00216     if (p_customsensorservice->isStatusHandle(handle)) p_customsensorservice->enNotify(handle); 
00217     if (p_customsensorservice->isDifferenceHandle(handle)) p_customsensorservice->enNotify(handle);  
00218     if (p_customsensorservice->isPositionHandle(handle)) p_customsensorservice->enNotify(handle);
00219     if (p_customsensorservice->isSunpanelHandle(handle)) p_customsensorservice->enNotify(handle);     
00220 }
00221 
00222 static void onUpdatesDisabledCallback(Gap::Handle_t handle)
00223 {
00224     if (p_customcontrolservice->isCommandHandle(handle)) p_customcontrolservice->disNotify(handle); 
00225     
00226     if (p_customsensorservice->isStatusHandle(handle)) p_customsensorservice->disNotify(handle); 
00227     if (p_customsensorservice->isDifferenceHandle(handle)) p_customsensorservice->disNotify(handle);  
00228     if (p_customsensorservice->isPositionHandle(handle)) p_customsensorservice->disNotify(handle);
00229     if (p_customsensorservice->isSunpanelHandle(handle)) p_customsensorservice->disNotify(handle);    
00230 }
00231 
00232 static void onDataReadCallback(const GattReadCallbackParams *eventDataP)
00233 {
00234 
00235     // if receive a manual Read request
00236 
00237     if (p_customsensorservice->isStatusHandle(eventDataP->handle))
00238     {   
00239         #ifdef Debug
00240             printf("\n\r\n\rSend BLE Display Status %d", Status);
00241         #endif
00242         p_customsensorservice->sendEnvStatus(Status, TimeStamp);
00243         
00244     } else if (p_customsensorservice->isDifferenceHandle(eventDataP->handle))
00245     {
00246         #ifdef Debug
00247             printf("\n\rSend BLE Difference %d lux/mems", diff); // Send BLE diff, no diff_abs
00248         #endif
00249         p_customsensorservice->sendEnvDifference(diff, TimeStamp);
00250 
00251     } else if (p_customsensorservice->isPositionHandle(eventDataP->handle))
00252     {
00253         #ifdef Debug
00254             printf("\n\rSend BLE Position %d", pos);
00255         #endif    
00256         p_customsensorservice->sendEnvPosition(pos, TimeStamp);
00257 
00258     } else if (p_customsensorservice->isSunpanelHandle(eventDataP->handle))
00259     {
00260         #ifdef Debug
00261             printf("\n\rSend BLE Sunpanel %d mV", measure);
00262         #endif    
00263         p_customsensorservice->sendEnvSunpanel(measure, TimeStamp);
00264 
00265     }
00266  
00267 }
00268 
00269 // This Callback happen when it RECEIVE a WRITE
00270 static void myonDataWriteCallback(const GattWriteCallbackParams *eventDataP)
00271 {   
00272 
00273     if (p_customcontrolservice->isCommandHandle(eventDataP->handle))
00274     {       
00275         // From CLIENT it receives a command in this format: Feature (4) + Type (1) + Data (2)        
00276         uint32_t Feature = eventDataP->data[0]<<24 | eventDataP->data[1]<<16 | eventDataP->data[2]<<8 | eventDataP->data[3];
00277         //uint8_t Type = eventDataP->data[4];
00278         int16_t Data = eventDataP->data[5]<<8 | eventDataP->data[6];
00279         
00280         //printf("\r\n\r\nmyonDataWriteCallback (Feature %x)", Feature);
00281         //printf("\r\nmyonDataWriteCallback (Type %x)", Type);        // Not Used
00282         //printf("\r\nmyonDataWriteCallback (Data Hex %x)", Data);
00283         //printf("\r\nmyonDataWriteCallback (Data Dec %d)", Data);
00284                
00285         switch(Feature)
00286         {
00287             case FeatureStatus:
00288                 printf("\r\n\r\nReceived STATUS %d", Data);
00289                 Status = Data;
00290                 Update_Status(Data);
00291                 break;
00292      
00293             case FeatureDifference:
00294                 #ifdef Debug
00295                     printf("\r\n\r\nReceived DIFF %d", Data);
00296                 #endif
00297                 diff = Data;
00298                 break;
00299  
00300             case FeaturePosition:
00301                 break;
00302             
00303             case FeatureSunPanel:
00304                 break;
00305                 
00306             default:
00307                 break;
00308         }
00309     }
00310     
00311 }
00312 
00313 static void onConnectionCallback(const Gap::ConnectionCallbackParams_t * connectionParams)
00314 {
00315     printf("\r\n\r\nonConnectionCallback (Line %d)", __LINE__);   
00316     BLEConnected=true;
00317 }
00318 
00319 static void onDisconnectionCallback(const Gap::DisconnectionCallbackParams_t * disConnectionReason)
00320 {
00321     printf("\r\n\r\nonDisconnectionCallback (Line %d)", __LINE__);
00322     p_BLEdev->gap().startAdvertising();
00323     BLEConnected=false;
00324 }
00325 
00326 #endif
00327 
00328 /* Bluetooth Initialization ---------------------------------------------------*/
00329 
00330 bool BLE_Initialization(void)
00331 {
00332 
00333 #ifdef Ble
00334 
00335     p_BLEdev = new BLE;
00336     if (!p_BLEdev) { printf("\r\nBLE Device creation failed\r\n"); }
00337     const Gap::Address_t BLE_address_BE = {BLE_DEV_MAC};        
00338     p_BLEdev->gap().setAddress(BLEProtocol::AddressType::PUBLIC, BLE_address_BE);
00339     
00340     p_BLEdev->init();
00341 
00342     // Set BLE CallBack Functions
00343     p_BLEdev->gattServer().onUpdatesEnabled(onUpdatesEnabledCallback);
00344     p_BLEdev->gattServer().onUpdatesDisabled(onUpdatesDisabledCallback);
00345     p_BLEdev->gattServer().onDataRead(onDataReadCallback);
00346     p_BLEdev->gattServer().onDataWritten(myonDataWriteCallback);
00347     p_BLEdev->gap().onConnection(onConnectionCallback);
00348     p_BLEdev->gap().onDisconnection(onDisconnectionCallback);
00349     //p_BLEdev->gattServer().onConfirmationReceived(onConfirmationReceivedCallback);    
00350     //p_BLEdev->gattServer().onDataSent(onDataSentCallback);    
00351     //p_BLEdev->gap().onTimeout(onTimeoutCallback);
00352 
00353     // BLE Services
00354     p_customcontrolservice = new CustomControlService(*p_BLEdev);   
00355     p_customsensorservice = new CustomSensorService(*p_BLEdev);
00356 
00357     // Setup BLE Advertising
00358     const static char DEVICE_NAME[] = BLE_DEV_NAME;
00359     p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
00360     p_BLEdev->gap().accumulateScanResponse(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA,dat,6);    
00361     p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::UNKNOWN);
00362     p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
00363     p_BLEdev->gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
00364     p_BLEdev->gap().setAdvertisingInterval(BLE_ADVERTISING_INTERVAL);
00365     p_BLEdev->gap().startAdvertising();
00366 
00367     printf("Initialization Ble OK (Line %d)\r\n", __LINE__);  
00368 
00369 #endif
00370 
00371     return true;
00372     
00373 }
00374 
00375 /* Initialization ------------------------------------------------------------*/
00376 
00377 bool Initialization(void)
00378 {
00379     
00380     dev_i2c.frequency(100000);      // Default 100KHz. At 10KHz, 20KHz, 200KHz and 400KHz doesn't work
00381     
00382 //----    
00383 
00384 #ifdef FlightSense
00385 
00386     // Initializing FlightSense Component
00387     board=X_NUCLEO_6180XA1::Instance(&dev_i2c, NC, NC, NC, NC); // NC as Interrupt fixed from FlightSense library 42
00388 
00389     status_bb=board->InitBoard();
00390     if(status_bb) VL6180x_ErrLog("Failed to init the board!\n\r");
00391 
00392     // Put GPIO not used as Interrupt in Hi-Z
00393     status_t=board->sensor_top->SetGPIOxFunctionality(1, GPIOx_SELECT_OFF);
00394     //status_b=board->sensor_botton->SetGPIOxFunctionality(1, GPIOx_SELECT_OFF); Not Present
00395     status_l=board->sensor_left->SetGPIOxFunctionality(1, GPIOx_SELECT_OFF);
00396     status_r=board->sensor_right->SetGPIOxFunctionality(1, GPIOx_SELECT_OFF);
00397     
00398     // Set Babybears
00399     status_l=board->sensor_left->AlsSetAnalogueGain(3);
00400     status_r=board->sensor_right->AlsSetAnalogueGain(3);
00401     status_l=board->sensor_left->StartMeasurement(als_continuous_polling, NULL, NULL, NULL);
00402     status_r=board->sensor_right->StartMeasurement(als_continuous_polling, NULL, NULL, NULL);
00403 
00404     printf("Init FlightSense OK\r\n");
00405 
00406 #endif
00407     
00408 //----
00409 
00410 #ifdef EasySpin
00411 
00412     // Initializing EasySpin Component
00413     motor = new L6474(D2, D8, PB_2, D9, D10, dev_spi); // D7 conflict with BNRG_RST (when motor change direction 0-1 reset BLE)
00414                                                        // Used Morpho PB_2 and made HW wiring
00415     if (motor->Init(NULL) != COMPONENT_OK)
00416         return false;
00417 
00418     motor->SetStepMode(StepperMotor::STEP_MODE_1_8);  // Default is STEP_MODE_1_16
00419 
00420     // Set defaults Motor Speed
00421     motor->SetAcceleration(SET_ACC);
00422     motor->SetDeceleration(SET_DEC);
00423     motor->SetMaxSpeed(SET_MAX);        // Variable by Light/Mems Sensors
00424     motor->SetMinSpeed(SET_MIN);
00425 
00426     printf("Init EasySpin OK\r\n");
00427 
00428 #endif
00429 
00430 //----  
00431 
00432 #ifdef Sensors
00433 
00434     // Initializing Sensors Component
00435     mems=X_NUCLEO_IKS01A1::Instance(&dev_i2c);
00436     accelerometer = mems->GetAccelerometer();
00437    
00438     printf("Init Sensors OK\r\n");
00439 
00440 #endif
00441     
00442     printf("Initialization OK (Line %d)\r\n", __LINE__);    
00443     return true;
00444 
00445 }
00446 
00447 /* Measure_Babybear ----------------------------------------------------------*/
00448 
00449 void Measure_Babybear(void)
00450 {
00451 
00452 #ifdef FlightSense
00453 
00454     status_l=board->sensor_left->GetMeasurement(als_continuous_polling, &data_sensor_left);
00455     status_r=board->sensor_right->GetMeasurement(als_continuous_polling, &data_sensor_right);
00456 
00457     babybear = data_sensor_right.lux - data_sensor_left.lux;
00458 
00459     diff = babybear;
00460 
00461 #endif
00462 
00463 }
00464 
00465 /* Measure_Accelerometer -----------------------------------------------------*/
00466 
00467 void Measure_Accelerometer(void)
00468 {
00469 
00470 #ifdef Sensors
00471 
00472     accelerometer->Get_X_Axes(acc_data);
00473 
00474     diff = acc_data[0];
00475 
00476 #endif
00477 
00478 }
00479 
00480 /* Control_Motor -------------------------------------------------------------*/
00481 
00482 void Control_Motor(void)
00483 {
00484 
00485 #ifdef EasySpin
00486 
00487     diff_abs = abs(diff);
00488 
00489     //printf("Diff: %d lux/mems\n\r", diff_abs);
00490     motor->SetMaxSpeed(diff_abs);
00491 
00492     if (diff>0) { left=0; right=1; }
00493     if (diff<0) { left=1; right=0; }
00494 
00495     if (diff_abs>TOLLERANCE) {
00496         if (diff_abs <=RANGE_1)
00497         {
00498             if (left)  { strcpy(DisplayStr,"E___"); }
00499             if (right) { strcpy(DisplayStr,"___3"); }
00500         }
00501         else if (diff_abs >RANGE_1 & diff_abs <=RANGE_2)
00502         {
00503             if (left)  { strcpy(DisplayStr,"E==="); }
00504             if (right) { strcpy(DisplayStr,"===3"); }
00505         }
00506         else if (diff_abs >RANGE_2)
00507         {
00508             if (left)  { strcpy(DisplayStr,"E~~~"); }
00509             if (right) { strcpy(DisplayStr,"~~~3"); }
00510         }
00511 
00512         // In Case of Change Direction
00513         if (left & dir==2)  { changedir=1; }
00514         if (right & dir==1) { changedir=1; }
00515 
00516         // Run only if Stop or Change Direction
00517         if (diff_abs>TOLLERANCE & (dir==0 | changedir==1)) {
00518             if (left)   { motor->Run(StepperMotor::FWD); dir=1; changedir=0; }
00519             if (right)  { motor->Run(StepperMotor::BWD); dir=2; changedir=0; }
00520             printf("\n\rRUN");
00521         }
00522     }
00523 
00524     // Get Motor Position and Control Rotation Block
00525     pos = motor->GetPosition();
00526     if (pos>STOP | pos<-STOP) {
00527         if (pos>0) { motor->GoTo(STOP); }
00528         if (pos<0) { motor->GoTo(-STOP); }
00529         printf("\n\rGOTO");
00530     }
00531 
00532     // Stop Motor
00533     if (diff_abs<=TOLLERANCE) { 
00534         arrest=1; 
00535         if (Status==1) { strcpy(DisplayStr,"----"); }
00536         if (Status==3) { strcpy(DisplayStr,"E  3"); }
00537     }
00538         
00539     if (arrest==1 && dir!=0 ) { // Stop just one time
00540         motor->HardStop();
00541         dir=0;
00542         changedir=0;
00543         arrest=0;
00544         printf("\n\rSTOP");
00545     }
00546 
00547 #endif
00548 
00549 }
00550 
00551 /* Measure_SolarPanel --------------------------------------------------------*/
00552 
00553 void Measure_SolarPanel(void)
00554 {
00555     
00556     // AnalogIn: 0V return 0.0 , 3.3V return 1.0
00557     measure = analog_read.read() * 3300;
00558     //printf("Measure = %.0f mV\r\n", measure);
00559     //board->display->DisplayDigit("A", 0);
00560 
00561     //if (abs(measure-prev_meas)>(prev_meas*0.1)) { prev_meas = measure; }
00562     //if (Status==2) { sprintf(DisplayStr, "%d", prev_meas); }
00563     
00564     if (Status==2) { sprintf(DisplayStr, "%d", measure); }
00565 }
00566 
00567 /* Ticker --------------------------------------------------------------------*/
00568 
00569 void tickerSta_Callback(void) { tickerSta=true; }
00570 void tickerDif_Callback(void) { tickerDif=true; }
00571 void tickerPos_Callback(void) { tickerPos=true; }
00572 void tickerSun_Callback(void) { tickerSun=true; }
00573 
00574 /* Main ----------------------------------------------------------------------*/
00575 
00576 int main()
00577 {
00578 
00579     // Printing to the console
00580     printf("\r\n\r\nSunTracker by Fabio Brembilla\r\n\r\n");
00581        
00582     Initialization();
00583     BLE_Initialization();
00584     
00585     mybutton.fall(&User_Button_Pressed);
00586 
00587     #ifdef Ble
00588     Ticker tickerSta_ticker, tickerDif_ticker, tickerPos_ticker, tickerSun_ticker;
00589     tickerSta_ticker.attach(tickerSta_Callback, TIMEOUT_STA);
00590     #endif 
00591     
00592     // Loop until push User Button to Set 0 Point
00593     printf("\r\nWait PUSH Button");
00594     strcpy(DisplayStr,"pusH");
00595     while(Status==0)
00596     {
00597         #ifdef FlightSense
00598         board->display->DisplayString(DisplayStr, strlen(DisplayStr)); // if I set fix len=4, it aligns digit from left
00599         //printf("%s\n\r", DisplayStr);
00600         #endif
00601         
00602         #ifdef Ble
00603         if (p_customsensorservice->isStatusNotificationEn()) {
00604             if (tickerSta) {
00605                 tickerSta=false;
00606                 #ifdef Debug
00607                     printf("\n\r\n\rSend BLE Display Status %d", Status);
00608                 #endif
00609                 //p_customsensorservice->sendEnvStatus(Status, TimeStamp);
00610                 p_customsensorservice->updateEnvStatus(Status, TimeStamp);    
00611             }
00612         }
00613         p_BLEdev->waitForEvent(); // Without it the CLIENT can't start to communicate
00614         #endif 
00615     }
00616 
00617     printf("\r\n\r\nStart Main Loop");
00618 
00619     #ifdef Ble
00620     tickerDif_ticker.attach(tickerDif_Callback, TIMEOUT_DIF);
00621     tickerPos_ticker.attach(tickerPos_Callback, TIMEOUT_POS);
00622     tickerSun_ticker.attach(tickerSun_Callback, TIMEOUT_SUN);
00623     #endif 
00624     
00625     #ifdef EasySpin
00626     motor->Enable(); // To put the motor on hold by execute CmdEnable
00627     #endif
00628 
00629     // Main Loop
00630     while(true)
00631     {  
00632         if (Status==1 | Status==2)    { Measure_Babybear(); }
00633         
00634         // If BLE is not connected, it uses Accelerometer from SERVER, otherwise receive the value from CLIENT
00635         if (BLEConnected==false) {
00636             if (Status==3)            { Measure_Accelerometer(); }
00637         }
00638         
00639         Control_Motor();
00640         Measure_SolarPanel();
00641         
00642         #ifdef FlightSense
00643         board->display->DisplayString(DisplayStr, strlen(DisplayStr)); // if I set fix len=4, it aligns digit from left
00644         //printf("%s\n\r", DisplayStr);
00645         #endif
00646         
00647         #ifdef Ble 
00648         //if (Status==3 & BLEConnected==false) { diff=0; }
00649         //if Status 3 and BLE not connected set diff=0 (no more useful if use SERVER Accelerometer)
00650         //After disconnect CLIENT, until it receive the timeout/notify to be really disconnected, it not receive diff!
00651         
00652         if (p_customsensorservice->isStatusNotificationEn()) {
00653             if (tickerSta) {
00654                 tickerSta=false;
00655                 #ifdef Debug
00656                     printf("\n\r\n\rSend BLE Display Status %d", Status);
00657                 #endif
00658                 //p_customsensorservice->sendEnvStatus(Status, TimeStamp);
00659                 p_customsensorservice->updateEnvStatus(Status, TimeStamp);    
00660             }
00661         }
00662         if (p_customsensorservice->isDifferenceNotificationEn()) {
00663             if (tickerDif) {
00664                 tickerDif=false;
00665                 #ifdef Debug
00666                     printf("\n\rSend BLE Difference %d lux/mems", diff); // Send BLE diff, no diff_abs
00667                 #endif
00668                 //p_customsensorservice->sendEnvDifference(diff, TimeStamp);
00669                 p_customsensorservice->updateEnvDifference(diff, TimeStamp);
00670             }
00671         }
00672         if (p_customsensorservice->isPositionNotificationEn()) {
00673             if (tickerPos) {
00674                 tickerPos=false;
00675                 #ifdef Debug      
00676                     printf("\n\rSend BLE Position %d", pos);
00677                 #endif
00678                 //p_customsensorservice->sendEnvPosition(pos, TimeStamp);
00679                 p_customsensorservice->updateEnvPosition(pos, TimeStamp);
00680             }
00681         }
00682         if (p_customsensorservice->isSunpanelNotificationEn()) {
00683             if (tickerSun) {
00684                 tickerSun=false;
00685                 #ifdef Debug   
00686                     printf("\n\rSend BLE SunPanel %d mV", measure); 
00687                 #endif           
00688                 //p_customsensorservice->sendEnvSunpanel(measure, TimeStamp);
00689                 p_customsensorservice->updateEnvSunpanel(measure, TimeStamp);
00690             }
00691         }
00692          
00693         p_BLEdev->waitForEvent();
00694         #endif
00695     }
00696 
00697     //status_l=board->sensor_left->StopMeasurement(als_continuous_polling);
00698     //status_r=board->sensor_right->StopMeasurement(als_continuous_polling);
00699 }