/******************************************************************************* * Function Name: ConnectToPeripheralDevice ******************************************************************************** * Summary: * Connects to Peripheral device with given BD Address. * * Parameters: * void * * Return: * void * *******************************************************************************/ void ConnectToPeripheralDevice(void) { CYBLE_API_RESULT_T apiResult; /* If flag has been set to connect to a device... */ if(clientConnectToDevice) { /* Process pending BLE events */ CyBle_ProcessEvents(); #if 0 if(CYBLE_STATE_SCANNING == CyBle_GetState()) { CyBle_GapcStopScan(); #ifdef DEBUG_ENABLED UART_UartPutString("Stop Scan called from clientConnectToDevice "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif CyBle_ProcessEvents(); } #endif if(CYBLE_STATE_DISCONNECTED == CyBle_GetState()) { /* Reset the flag to connect to a device*/ clientConnectToDevice = FALSE; /* Connect to the device whose address has been saved as part of * potential node search */ apiResult = CyBle_GapcConnectDevice(&peripAddr); if(apiResult != CYBLE_ERROR_OK) { #ifdef DEBUG_ENABLED UART_UartPutString("Connect Request failed "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } else { #ifdef DEBUG_ENABLED UART_UartPutString("Connect Request Sent "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } /* Process pending BLE events */ CyBle_ProcessEvents(); } } }
/******************************************************************************* * Function Name: attrHandleInit ******************************************************************************** * * Summary: * This function gathhers all the information like attribute handles and MTU size * from the server. * * Parameters: * None. * * Return: * None. * *******************************************************************************/ void attrHandleInit() { switch(infoExchangeState) { case INFO_EXCHANGE_START: CyBle_GattcDiscoverPrimaryServiceByUuid(cyBle_connHandle, bleUartServiceUuidInfo); break; case BLE_UART_SERVICE_HANDLE_FOUND: attrHandleRange.startHandle = bleUartServiceHandle; attrHandleRange.endHandle = bleUartServiceEndHandle; CyBle_GattcDiscoverAllCharacteristics(cyBle_connHandle, attrHandleRange); break; case (SERVICE_AND_CHAR_HANDLES_FOUND): charDescHandleRange.startHandle = txCharHandle + 1; charDescHandleRange.endHandle = bleUartServiceEndHandle; CyBle_GattcDiscoverAllCharacteristicDescriptors(cyBle_connHandle, &charDescHandleRange); break; case (ALL_HANDLES_FOUND): CyBle_GattcExchangeMtuReq(cyBle_connHandle, CYBLE_GATT_MTU); break; default: break; } CyBle_ProcessEvents(); }
void Initialization(void) { /* Set the divider for ECO, ECO will be used as source when IMO is switched off to save power, to drive the HFCLK */ CySysClkWriteEcoDiv(CY_SYS_CLK_ECO_DIV8); /* Do the following for achieving lowest possible WCO & ECO startup current: * 1. Shut down the ECO (to reduce power consumption while WCO is starting) * 2. Enable WDT counter 0 to wakeup the system after 500ms (500ms = WCO startup time) * 3. Configure PSoC 4 BLE device in DeepSleep mode for the 500ms WCO startup time * 4. After WCO is enabled, restart the ECO so that BLESS interface can function * 5. Enable WDT counter 1 to wakeup the system after 1ms (1ms = ECO startup time) * 5. Configure PSoC 4 BLE device in DeepSleep mode for the 1ms ECO startup time */ CySysClkEcoStop(); /* Shutdown the ECO and later re-start in low power mode after WCO is turned on */ WDT_Interrupt_StartEx(WDT_Handler); /* Initialize WDT interrupt */ WCO_ECO_LowPowerStart(); /* Enable WCO & ECO in low power mode using WDT counter 0/1 as system wakeup sources respectively */ CyBle_Start(BLE_AppEventHandler); while (CyBle_GetState() == CYBLE_STATE_INITIALIZING) { CyBle_ProcessEvents(); } }
/******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * Main function. * * Parameters: * None * * Return: * None * *******************************************************************************/ int main() { /* Setup the system initially */ InitializeSystem(); /* Three simple APIs that showcases dynamic ADV payload update */ for(;;) { /* Single API call to service all the BLE stack events. Must be * called at least once in a BLE connection interval */ CyBle_ProcessEvents(); /* Configure the system in lowest possible power modes during and between BLE ADV events */ EnterLowPowerMode(); /* LOW_POWER_NOTE - If you like to measure the current consumed by this project, following changes are to be done to achieve lowest possible current number: 1. Set the "Debug Select" option under Dynamic Broadcaster.cydwr -> System -> Programming/Debugging to GPIO 2. Comment out Advertising_LED_Write(LED_ON); line of code in StackEventHandler routine */ #if ENABLE_DYNAMIC_ADV DynamicADVPayloadUpdate(); #endif } }
/****************************************************************************** Function Name: main ******************************************************************************* Summary: Main routine of this firmware. Initializes the components once and hanles the BLE events and UART data in a loop forever. Parameters: None. Return: None. ******************************************************************************/ int main() { /* This start-up delay is for the Android app to open when the locator * device is plugged into the phone's USB port so that the first printf * message will not be missed. */ CyDelay(3000); CyGlobalIntEnable; UART_DEB_Start(); /* Start communication component */ printf("PSoC: BLE Find Me Locator is Connected\r\n"); Disconnect_LED_Write(LED_OFF); apiResult = CyBle_Start(AppCallBack); if(apiResult != CYBLE_ERROR_OK) { printf("PSoC: CyBle_Start API Error: 0x%x \r\n", apiResult); } while(1) { /******************************************************************* * Processes all pending BLE events in the stack *******************************************************************/ CyBle_ProcessEvents(); /* Process the received UART data */ ProcessUartData(); } }
/******************************************************************************* * Function Name: InitializeSystem ******************************************************************************** * * Summary: * Systm initialization function. * * Parameters: * None * * Return: * None * *******************************************************************************/ void InitializeSystem(void) { CyGlobalIntEnable; /* Enable Global Interrupts*/ /* Internal low power oscillator is no longer required after Watch Crystal oscillator is started */ CySysClkIloStop(); /* Set the divider for ECO, ECO will be used as source when IMO is switched off to save power */ CySysClkWriteEcoDiv(CY_SYS_CLK_ECO_DIV8); BLE_Engine_Start(); /* start the BLE interface */ /* Wait for BLE Component to Initialize */ while (CyBle_GetState() == CYBLE_STATE_INITIALIZING) { CyBle_ProcessEvents(); } #if (CONSOLE_LOG_ENABLE) Console_Start(); /* Console log interface */ Console_UartPutString("System initialization complete\r\n"); #endif /* End of #if (CONSOLE_LOG_ENABLE) */ /* ADD YOUR CODE TO INITIALIZE OTHER COMPONENTS IN YOUR DESIGN */ }
void HandleI2CWrite(void) { CYBLE_GATTC_WRITE_CMD_REQ_T I2CDataWriteCmd; /* Check if the peripheral is connected before trying to write*/ if(CyBle_GetState() == CYBLE_STATE_CONNECTED) { /* update the attribute handle to be written */ I2CDataWriteCmd.attrHandle = I2CWriteDataCharHandle; I2CDataWriteCmd.value.len = byteCnt; I2CDataWriteCmd.value.val = wrBuf; do { apiResult = CyBle_GattcWriteWithoutResponse(cyBle_connHandle, &I2CDataWriteCmd); CyBle_ProcessEvents(); } while((CYBLE_ERROR_OK != apiResult) && (CYBLE_STATE_CONNECTED == cyBle_state)); } }
/******************************************************************************* * Function Name: InitializeSystem ******************************************************************************** * * Summary: * Systm initialization function. * * Parameters: * None * * Return: * None * *******************************************************************************/ void InitializeSystem(void) { CyGlobalIntEnable; /* Enable Global Interrupts*/ /* Internal low power oscillator is no longer required after Watch Crystal oscillator is started */ CySysClkIloStop(); /* Set the divider for ECO, ECO will be used as source when IMO is switched off to save power */ CySysClkWriteEcoDiv(CY_SYS_CLK_ECO_DIV8); BLE_Engine_Start(); /* Kick start the BLE GATT server and client interface */ /* Wait for BLE Component to Initialize */ while (CyBle_GetState() == CYBLE_STATE_INITIALIZING) { CyBle_ProcessEvents(); } #if BLE_COEXISTENCE_ENABLE *(uint32*)(CYREG_RADIO_TX_RX_MUX_REGISTER)&= ~RADIO_TX_RX_MUX_MASK; /* Clear Previous mux selection */ *(uint32*)(CYREG_RADIO_TX_RX_MUX_REGISTER) |= BLESS_MUX_INPUT_MASK; /* Set BLESS as the source of the mux */ *(uint32*)(CYREG_BLE_BLESS_RF_CONFIG) |= RADIO_TX_RX_SEL; /* Select Tx enable & Rx enable signals from BLESS as input to mux */ Radio_Control_Interrupt_StartEx(&Radio_Control_ISR); #endif /* End of #if BLE_COEXISTENCE_ENABLE */ }
/******************************************************************************* * Function Name: BLE_Run ******************************************************************************** * * Summary: * BLE interface processing engine. This API should be continuously called by * the application in its main loop. * * Parameters: * None * * Return: * None * *******************************************************************************/ void BLE_Run(void) { CyBle_ProcessEvents(); /* ADD YOUR CODE TO PERFORM OTHER BLE OPERATIONS IN MAIN LOOP. * STORING BONDING INFORMATION TO FLASH IS ONE EXAMPLE */ }
/* Main loop */ int main() { CYBLE_API_RESULT_T apiResult; CyGlobalIntEnable; Initialization(); for(;;) { /* Delayed start of advertisement */ if(initCounter == 6) { initCounter = 7; WDT_DisableWcoEcoCounters(); apiResult = CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_CUSTOM); if(apiResult != CYBLE_ERROR_OK) { CYASSERT(0); } } CyBle_ProcessEvents(); /* BLE stack processing state machine interface */ LowPower(); } }
int main() { CYBLE_API_RESULT_T apiResult; uint32 count = 0; uint8 triggerNotification = 0; // Enable global interrupts CyGlobalIntEnable; // Initialize the watchdog timer CySysWdtSetIsrCallback(CY_SYS_WDT_COUNTER0, Watchdog0_cb); // Initialize the BLE device. apiResult = CyBle_Start(StackEventHandler); // Validate BLE stack initialization successed CYASSERT(apiResult == CYBLE_ERROR_OK); for (;;) { // Service all the BLE stack events. // Must be called at least once in a BLE connection interval CyBle_ProcessEvents(); if (deviceConnected) { if (counterCccDescriptor.dirty) { // Update Counter CCCD updateCounterCccDescriptor(); } else if (triggerNotification) { // Send notification if required if (enableCounterNotification) { sendCounterNotification(count); } triggerNotification = 0; } else if (triggerUpdateCounter) { // Update counter value count++; updateCounter(count); triggerNotification = ((count & 0x0000000F) == 0); triggerUpdateCounter = 0; } } // Scan update queue if (rgbDescriptor.dirty) { // Update RGB Descriptor updateRgbDescriptor(); } // Enter to deep sleep mode { CYBLE_LP_MODE_T state; state = CyBle_EnterLPM(CYBLE_BLESS_DEEPSLEEP); if (state == CYBLE_BLESS_DEEPSLEEP) { CySysPmDeepSleep(); } } } }
/******************************************************************************* * Function Name: RestartCentralScanning ******************************************************************************** * Summary: * Restarts Central scanning. Also, if the time that the device has remained * in Central role exceeds pre-determined value, then the switch role flag is set. * * Parameters: * void * * Return: * void * *******************************************************************************/ void RestartCentralScanning(void) { /* If the current role is Central and the Central time has exceeded the preset time, * then set the flag to switch role to Peripheral */ if((BLE_CENTRAL == ble_gap_state) && (WatchDog_CurrentCount() - centralStartedTime > CENTRAL_STATE_SPAN) && ((CYBLE_STATE_DISCONNECTED == CyBle_GetState()) || (CYBLE_STATE_SCANNING == CyBle_GetState()))) { /* Switch role flag set */ switch_Role = TRUE; #ifdef DEBUG_ENABLED UART_UartPutString("switchRole from restartScanning loop "); UART_UartPutCRLF(' '); #endif return; } /* If restart scanning flag is set, the restart the Central scanning */ if(restartScanning) { /* Process pending BLE events */ CyBle_ProcessEvents(); if(CYBLE_STATE_DISCONNECTED == CyBle_GetState()) { /* Reset the restart scanning flag */ restartScanning = FALSE; #ifdef DEBUG_ENABLED UART_UartPutString("restartScanning loop "); UART_UartPutCRLF(' '); #endif /* Start Central scan and process the event */ CyBle_GapcStartScan(CYBLE_SCANNING_FAST); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Start Scan from restartScanning loop "); UART_UartPutCRLF(' '); #endif } } }
/******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * System entry and execution point for application * * Parameters: * None * * Return: * int * *******************************************************************************/ int main() { /* Start the components */ InitializeSystems(); for(;;) { /* CyBle_ProcessEvents() allows BLE stack to process pending events */ CyBle_ProcessEvents(); } }
int main() { /* Place your initialization/startup code here (e.g. MyInst_Start()) */ //printf("Restarted\n"); float resistor_divider_multiplier; float adc_multiplier; float fudge_multiplier; uint16 offset; uint32 value; int i; offset = 402; resistor_divider_multiplier = ((220000 + 18000) / 18000); adc_multiplier = 2.048 / 65536; fudge_multiplier = 1.02534275031159; initializeSystem(); for(;;) { elapsed = elapsed + 1; UART_UartPutChar(72u);//H UART_UartPutChar(101u);//e UART_UartPutChar(108u);//l UART_UartPutChar(108u);//l UART_UartPutChar(111u);//o iprintf(", World! %d", elapsed); UART_UartPutChar(13u);//CR UART_UartPutChar(10u);//LF TP1_Write(1u); /* Place your application code here. */ CyBle_ProcessEvents(); TP1_Write(0u); if (elapsed == 0) { //voltageReading = 29.6907207207207 * ((float)rawADCValue/0x7FFF); //voltageReading = 0.0009 * (float)rawADCValue + 0.4238; //voltageReading = 0.0005892 * (float)rawADCValue + 0.28026; value = 0; for (i = 0; i < 16; i++) { value += rawADCValues[i]; } value = value / 16; voltageReading = fudge_multiplier * resistor_divider_multiplier * adc_multiplier * (float)(value - offset); SendVoltageMeasurementNotification(voltageReading); SendRawADCNotification(rawADCValue); //printf("Voltage: %f\n", voltageReading); } } }
int main() { CyGlobalIntEnable; CyBle_Start(BleEventHandler); while(connHandle.bdHandle == 0) /* Wait for connection to GATT server */ CyBle_ProcessEvents(); CyBle_GattcStartDiscovery(connHandle); /* Attempt discovery of configured services */ while(ledStateHandle == 0) /* Wait for discovery */ CyBle_ProcessEvents(); writeData = 0x01; /* Turn on LED on Minimal_Peripheral dongle */ writeValue.val = &writeData; writeValue.len = sizeof(writeData); writeValue.actualLen = sizeof(writeData); writeReqParam.value = writeValue; writeReqParam.attrHandle = ledStateHandle; /* Use discovered handle */ CyBle_GattcWriteWithoutResponse(connHandle, &writeReqParam); /* Write to server */ CyBle_ProcessEvents(); return 0; }
/******************************************************************************* * Function Name: main ******************************************************************************** * Summary: * System entrance point. This calls the initializing function and * continuously process BLE and CapSense events. * * Parameters: * void * * Return: * int * *******************************************************************************/ int main() { uint8 lpmSel = DEEPSLEEP; /* This function will initialize the system resources such as BLE and CapSense */ InitializeSystem(); for(;;) { /*Process event callback to handle BLE events. The events generated and * used for this application are inside the 'CustomEventHandler' routine*/ CyBle_ProcessEvents(); /* Updated LED for status during BLE active states */ HandleStatusLED(); if(TRUE == deviceConnected) { /* After the connection, send new connection parameter to the Client device * to run the BLE communication on desired interval. This affects the data rate * and power consumption. High connection interval will have lower data rate but * lower power consumption. Low connection interval will have higher data rate at * expense of higher power. This function is called only once per connection. */ UpdateConnectionParam(); /* When the Client Characteristic Configuration descriptor (CCCD) is written * by Central device for enabling/disabling notifications, then the same * descriptor value has to be explicitly updated in application so that * it reflects the correct value when the descriptor is read */ UpdateNotificationCCCD(); lpmSel = LPMselData; } #ifdef ENABLE_LOW_POWER_MODE /* Put system to Deep sleep, including BLESS, and wakeup on interrupt. * The source of the interrupt can be either BLESS Link Layer in case of * BLE advertisement and connection or by User Button press during BLE * disconnection */ HandleLowPowerMode(lpmSel); #endif if(restartAdvertisement) { /* Reset 'restartAdvertisement' flag*/ restartAdvertisement = FALSE; /* Start Advertisement and enter Discoverable mode*/ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); } } /* End of for(;;) */ }
int main() { CyGlobalIntEnable; /* Enable global interrupts. */ /* Place your initialization/startup code here (e.g. MyInst_Start()) */ Advertising_Led_Write(LED_OFF); Error_Led_Write(LED_OFF); apiResult = CyBle_Start(bleCallBack); if (apiResult != CYBLE_ERROR_OK) { printf("CyBle_Start API error: %x \r\n", apiResult); Error_Led_Write(LED_ON); } for(;;) { /* Place your application code here. */ CyBle_ProcessEvents(); } }
/******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * Main function. * * Parameters: * None * * Return: * None * *******************************************************************************/ int main() { CYBLE_API_RESULT_T apiResult; CYBLE_STATE_T bleState; CyGlobalIntEnable; PWM_Start(); UART_Start(); UART_UartPutString("Welcome to BLE OOB Pairing Demo\r\n"); apiResult = CyBle_Start(StackEventHandler); if(apiResult != CYBLE_ERROR_OK) { /* BLE stack initialization failed, check your configuration */ CYASSERT(0); } CyBle_IasRegisterAttrCallback(IasEventHandler); for(;;) { /* Single API call to service all the BLE stack events. Must be * called at least once in a BLE connection interval */ CyBle_ProcessEvents(); bleState = CyBle_GetState(); if(bleState != CYBLE_STATE_STOPPED && bleState != CYBLE_STATE_INITIALIZING) { /* Configure BLESS in DeepSleep mode */ CyBle_EnterLPM(CYBLE_BLESS_DEEPSLEEP); /* Configure PSoC 4 BLE system in sleep mode */ CySysPmSleep(); /* BLE link layer timing interrupt will wake up the system */ } } }
/******************************************************************************* * Function Name: main ******************************************************************************** * Summary: * System entrance point. This calls the initializing function and continuously * process BLE and CapSense events. * * Parameters: * void * * Return: * int * *******************************************************************************/ int main() { /* This function will initialize the system resources such as BLE and CapSense */ InitializeSystem(); for(;;) { /*Process event callback to handle BLE events. The events generated and * used for this application are inside the 'CustomEventHandler' routine*/ CyBle_ProcessEvents(); if(TRUE == deviceConnected) { /* Send CapSense Slider data when respective notification is enabled */ if(TRUE == sendCapSenseSliderNotifications) { /* Check for CapSense slider swipe and send data accordingly */ HandleCapSenseSlider(); } } } }
int main() { /* Enabling Global interrupts */ CyGlobalIntEnable; /* Start BLE component with appropriate Event handler function */ CyBle_Start(ApplicationEventHandler); /* Turn OFF All the LEDs */ ALL_LED_OFF(); /* Loop For Ever */ for(;;) { /* Function to handle the state of the Client */ handle_ble_CAR_Client_State(); /* This function checks the internal task queue in the BLE Stack, and pending operation of the BLE Stack, if any */ CyBle_ProcessEvents(); } }
/******************************************************************************* * Function Name: main ******************************************************************************** * Summary: * System entrance point. This calls the initializing function and * continuously process BLE events. * * Parameters: * void * * Return: * int * *******************************************************************************/ int main() { /* This function will initialize the system resources such as BLE and * NEC pulse timer */ InitializeSystem(); for(;;) { /* Process event callback to handle BLE events. The events generated and * used for this application are inside the 'CustomEventHandler' routine */ CyBle_ProcessEvents(); /* Update LED for status during BLE active states */ HandleStatusLED(); if(TRUE == deviceConnected) { /* After the connection, send new connection parameter to the Client device * to run the BLE communication on desired interval. This affects the data rate * and power consumption. High connection interval will have lower data rate but * lower power consumption. Low connection interval will have higher data rate at * expense of higher power. This function is called only once per connection. */ UpdateConnectionParam(); } if(restartAdvertisement) { /* Reset 'restartAdvertisement' flag*/ restartAdvertisement = FALSE; /* Start Advertisement and enter Discoverable mode*/ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); } } /* End of for(;;) */ }
int main() { hkj_timer t; const uint16 myCharHandle = 0x0E; uint8 writeData = 0; CYBLE_GATT_VALUE_T writeValue = \ { &writeData, sizeof(writeData), sizeof(writeData) }; CYBLE_GATTC_WRITE_REQ_T writeReqParam = \ { .value = writeValue, .attrHandle = myCharHandle }; CYBLE_STACK_LIB_VERSION_T stackVersion; CyGlobalIntEnable; UART_Start(); hkj_debug_init(); CyBle_GetStackLibraryVersion(&stackVersion); debug_print("Latency Central Stack: %u.%u.%u.%u\r\n", \ stackVersion.majorVersion, stackVersion.minorVersion, \ stackVersion.patch, stackVersion.buildNumber); CyBle_Start(BleEventHandler); hkj_timer_ms_init(&t); while(1) { CyBle_ProcessEvents(); if (connHandle.bdHandle != 0) { if (hkj_timer_ms_get_delta(&t) > 500) { WRITE_CMD_PIN_Write(1); CyBle_GattcWriteWithoutResponse(connHandle, &writeReqParam); hkj_timer_ms_reset_delta(&t); CyDelay(2); WRITE_CMD_PIN_Write(0); } } hkj_ble_events_log_debug_print(); } }
/******************************************************************************* * Function Name: InitializeSystem ******************************************************************************** * * Summary: * Systm initialization function. * * Parameters: * None * * Return: * None * *******************************************************************************/ void InitializeSystem(void) { CyGlobalIntEnable; /* Enable Global Interrupts*/ /* Set the divider for ECO, ECO will be used as source when IMO is switched off to save power */ CySysClkWriteEcoDiv(CY_SYS_CLK_ECO_DIV8); #if LOW_POWER_STARTUP_ENABLE /* If LOW_POWER_STARTUP_ENABLE is set, then do the following for achieving lowest possible WCO & ECO startup current: * 1. Shut down the ECO (to reduce power consumption while WCO is starting) * 2. Enable WDT counter 0 to wakeup the system after 500ms (500ms = WCO startup time) * 3. Configure PSoC 4 BLE device in DeepSleep mode for the 500ms WCO startup time * 4. After WCO is enabled, restart the ECO so that BLESS interface can function * 5. Enable WDT counter 1 to wakeup the system after 1ms (1ms = ECO startup time) * 5. Configure PSoC 4 BLE device in DeepSleep mode for the 1ms ECO startup time */ CySysClkEcoStop(); /* Shutdown the ECO and later re-start in low power mode after WCO is turned on */ WDT_Interrupt_StartEx(WDT_Handler); /* Initialize WDT interrupt */ WCO_ECO_LowPowerStart(); /* Enable WCO & ECO in low power mode using WDT counter 0/1 as system wakeup sources respectively */ #endif /* End of #if LOW_POWER_STARTUP_ENABLE */ #if (CONSOLE_LOG_ENABLE) Console_Start(); /* Console log interface */ Console_UartPutString("Low power system startup complete\r\n"); #endif /* End of #if (CONSOLE_LOG_ENABLE) */ BLE_Engine_Start(); /* start the BLE interface */ /* Wait for BLE Component to Initialize */ while (CyBle_GetState() == CYBLE_STATE_INITIALIZING) { CyBle_ProcessEvents(); } }
*******************************************************************************/int main() { CyGlobalIntEnable; #if (DEBUG_UART_ENABLED == ENABLED) UART_DEB_Start(); #endif /* (DEBUG_UART_ENABLED == ENABLED) */ DBG_PRINTF("BLE HID Keyboard Example Project \r\n"); LED_RED_Write(LED_OFF); LED_BLU_Write(LED_OFF); LED_GRN_Write(LED_OFF); /* Start CYBLE component and register generic event handler */ CyBle_Start(AppCallBack); #if (BAS_MEASURE_ENABLE != 0) ADC_Start(); #endif /* BAS_MEASURE_ENABLE != 0 */ while(1) { /* CyBle_ProcessEvents() allows BLE stack to process pending events */ CyBle_ProcessEvents(); /* To achieve low power in the device */ LowPowerImplementation(); if((CyBle_GetState() == CYBLE_STATE_CONNECTED) && (suspend != CYBLE_HIDS_CP_SUSPEND)) { if(mainTimer != 0u) { mainTimer = 0u; #if (BAS_SIMULATE_ENABLE != 0) SimulateBattery(); CyBle_ProcessEvents(); #endif /* BAS_SIMULATE_ENABLE != 0 */ #if (BAS_MEASURE_ENABLE != 0) MeasureBattery(); CyBle_ProcessEvents(); #endif /* BAS_MEASURE_ENABLE != 0 */ if(keyboardSimulation == ENABLED) { SimulateKeyboard(); } } /* Store bonding data to flash only when all debug information has been sent */ #if(CYBLE_BONDING_REQUIREMENT == CYBLE_BONDING_YES) #if (DEBUG_UART_ENABLED == ENABLED) if((cyBle_pendingFlashWrite != 0u) && ((UART_DEB_SpiUartGetTxBufferSize() + UART_DEB_GET_TX_FIFO_SR_VALID) == 0u)) #else if(cyBle_pendingFlashWrite != 0u) #endif /* (DEBUG_UART_ENABLED == ENABLED) */ { CYBLE_API_RESULT_T apiResult; apiResult = CyBle_StoreBondingData(0u); (void)apiResult; DBG_PRINTF("Store bonding data, status: %x \r\n", apiResult); } #endif /* CYBLE_BONDING_REQUIREMENT == CYBLE_BONDING_YES */ } } }
int main() { CYBLE_LP_MODE_T lpMode; CYBLE_BLESS_STATE_T blessState; CYBLE_STACK_LIB_VERSION_T stackVersion; CyGlobalIntEnable; UART_DEB_Start(); /* Start communication component */ printf("BLE Heart Rate Collector Example Project \r\n"); Disconnect_LED_Write(LED_OFF); Scanning_LED_Write(LED_OFF); Notification_LED_Write(LED_OFF); apiResult = CyBle_Start(AppCallBack); if(apiResult != CYBLE_ERROR_OK) { printf("CyBle_Start API Error: 0x%x \r\n", apiResult); } apiResult = CyBle_GetStackLibraryVersion(&stackVersion); if(apiResult != CYBLE_ERROR_OK) { printf("CyBle_GetStackLibraryVersion API Error: 0x%x \r\n", apiResult); } else { printf("Stack Version: %d.%d.%d.%d \r\n", stackVersion.majorVersion, stackVersion.minorVersion, stackVersion.patch, stackVersion.buildNumber); } CyBle_BasRegisterAttrCallback(BasCallBack); HrsInit(); while(1) { if(CyBle_GetState() != CYBLE_STATE_INITIALIZING) { /* Enter DeepSleep mode between connection intervals */ lpMode = CyBle_EnterLPM(CYBLE_BLESS_DEEPSLEEP); CyGlobalIntDisable; blessState = CyBle_GetBleSsState(); if(lpMode == CYBLE_BLESS_DEEPSLEEP) { if(blessState == CYBLE_BLESS_STATE_ECO_ON || blessState == CYBLE_BLESS_STATE_DEEPSLEEP) { /* Put the device into the DeepSleep mode only when all debug information has been sent */ if((UART_DEB_SpiUartGetTxBufferSize() + UART_DEB_GET_TX_FIFO_SR_VALID) == 0u) { CySysPmDeepSleep(); } else { CySysPmSleep(); } } } else { if(blessState != CYBLE_BLESS_STATE_EVENT_CLOSE) { CySysPmSleep(); } } CyGlobalIntEnable; /* Handle advertising led blinking */ HandleLeds(); } /* Store bonding data to flash only when all debug information has been sent */ if((cyBle_pendingFlashWrite != 0u) && ((UART_DEB_SpiUartGetTxBufferSize() + UART_DEB_GET_TX_FIFO_SR_VALID) == 0u)) { apiResult = CyBle_StoreBondingData(0u); printf("Store bonding data, status: %x \r\n", apiResult); } /******************************************************************* * Processes all pending BLE events in the stack *******************************************************************/ CyBle_ProcessEvents(); } }
/******************************************************************************* * Function Name: HandleUartTxTraffic ******************************************************************************** * * Summary: * This function takes data from UART RX buffer and pushes it to the server * as Write Without Response command. * * Parameters: * None. * * Return: * None. * *******************************************************************************/ void HandleUartTxTraffic(void) { uint8 index; uint8 uartTxData[MAX_MTU_SIZE - 3]; uint16 uartTxDataLength; static uint16 uartIdleCount = UART_IDLE_TIMEOUT; CYBLE_API_RESULT_T bleApiResult; CYBLE_GATTC_WRITE_CMD_REQ_T uartTxDataWriteCmd; uartTxDataLength = UART_SpiUartGetRxBufferSize(); #ifdef FLOW_CONTROL if(uartTxDataLength >= (UART_UART_RX_BUFFER_SIZE - (UART_UART_RX_BUFFER_SIZE/2))) { DisableUartRxInt(); } else { EnableUartRxInt(); } #endif if((uartTxDataLength != 0)) { if(uartTxDataLength >= (mtuSize - 3)) { uartIdleCount = UART_IDLE_TIMEOUT; uartTxDataLength = mtuSize - 3; } else { if(--uartIdleCount == 0) { /*uartTxDataLength remains unchanged */; } else { uartTxDataLength = 0; } } if(0 != uartTxDataLength) { uartIdleCount = UART_IDLE_TIMEOUT; for(index = 0; index < uartTxDataLength; index++) { uartTxData[index] = (uint8) UART_UartGetByte(); } uartTxDataWriteCmd.attrHandle = rxCharHandle; uartTxDataWriteCmd.value.len = uartTxDataLength; uartTxDataWriteCmd.value.val = uartTxData; #ifdef FLOW_CONTROL DisableUartRxInt(); #endif do { bleApiResult = CyBle_GattcWriteWithoutResponse(cyBle_connHandle, &uartTxDataWriteCmd); CyBle_ProcessEvents(); } while((CYBLE_ERROR_OK != bleApiResult) && (CYBLE_STATE_CONNECTED == cyBle_state)); } } }
/******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * This is the main entry point for this application. This function initializes all the * components used in the project. It computes the frequency whenever a capture event is * * Parameters: * None * * Return: * None * *******************************************************************************/ int main() { #if(UART_DEBUG_ENABLE) /* Variable to store the loop number */ uint8 loopNo = 0; #endif /* Enable global interrupt mask */ CyGlobalIntEnable; /* Disable ILO as it is not used */ CySysClkIloStop(); /* Initialize components related to BLE communication */ InitializeBLESystem(); /* Initialize components related to frequency counting */ Initialize_Freq_Meas_System(); /* Start UART component if UART debug is enabled */ #if(UART_DEBUG_ENABLE) /* Start UART component and send welcome string to hyper terminal on PC */ UART_Start(); UART_UartPutString("Welcome to Frequency Measurement Using PSoC 4 BLE\n"); UART_PutCRLF(); #endif while(1) { /* Compute frequency once in every PWM interval(2s) */ if(Calculate_Frequency == TRUE) { /* Check if valid capture event is detected */ if((Input_Sig_Ctr_Capture == 1) && (Ref_Clk_Ctr_Capture == 1)) { /* Compute frequency using the latched count value, computed frequency will be stored in ASCII format in a global array */ Compute_Frequency(); #if(UART_DEBUG_ENABLE) /* Print input signal counter value in hexadecimal */ UART_UartPutString("Input Signal Counter Value: "); UART_SendDebugData(Input_Signal_Count); UART_UartPutString(" "); /* Print input signal counter value in ASCII format */ /* Reset the array before storing the ASCII character */ Reset_Array(InputCounter_ASCII, DATA_END); Convert_HextoDec(Input_Signal_Count, InputCounter_ASCII); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(InputCounter_ASCII[DATA_END - loopNo -1]); } UART_PutCRLF(); /* Print reference clock counter value */ UART_UartPutString("Reference Clock Counter Value: "); UART_SendDebugData(Ref_Clock_Count); UART_UartPutString(" "); /* Print input signal counter value in ASCII format */ /* Reset the array before storing the ASCII character */ Reset_Array(RefCounter_ASCII, DATA_END); Convert_HextoDec(Ref_Clock_Count, RefCounter_ASCII); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(RefCounter_ASCII[DATA_END - loopNo -1]); } UART_PutCRLF(); /* Print Input Signal Frequency in decimal format */ UART_UartPutString("Input Frequency: "); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(Input_Frequency[DATA_END - loopNo -1]); } UART_PutCRLF(); #endif /* Reset the capture flag after computing the frequency */ Input_Sig_Ctr_Capture = 0; Ref_Clk_Ctr_Capture = 0; } /* If valid capture event is not registered, set the value of frequency to zero */ else { /* Reset the input_frequency array before storing the frequency value */ Reset_Array(Input_Frequency, DATA_END); /* If no capture event is detected in the 1s interval, set the frequency to zero */ FormatFrequencyData(ZERO_HZ); #if(UART_DEBUG_ENABLE) /* Print Input Signal Frequency in decimal format */ UART_UartPutString("Input Frequency: "); for(loopNo = 0; loopNo < DATA_END; loopNo++) { UART_UartPutChar(Input_Frequency[DATA_END - loopNo -1]); } UART_PutCRLF(); #endif } /* Reset the 2s interval flag for computing the frequency in the next interval */ Calculate_Frequency = 0; /* Send frequency value only if BLE device is connected */ if(TRUE == deviceConnected) { /* Send frequency value when notifications are enabled */ if((startNotification & CCCD_NTF_BIT_MASK)) { /* Send the frequency value to BLE central device by notifications */ SendDataOverFreqCounterNotification(Input_Frequency); } } } /* Function to handle LED status depending on BLE state */ HandleStatusLED(); /* Handle CCCD value update only if BLE device is connected */ if(TRUE == deviceConnected) { /* When the Client Characteristic Configuration descriptor (CCCD) is written * by Central device for enabling/disabling notifications, then the same * descriptor value has to be explicitly updated in application so that * it reflects the correct value when the descriptor is read */ UpdateNotificationCCCD(); } if(restartAdvertisement) { /* Reset 'restartAdvertisement' flag*/ restartAdvertisement = FALSE; /* Start Advertisement and enter Discoverable mode*/ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); } /*Process Event callback to handle BLE events. The events generated and * used for this application are inside the 'CustomEventHandler' routine*/ CyBle_ProcessEvents(); /* Put CPU to sleep */ CySysPmSleep(); } }
/******************************************************************************* * Function Name: SwitchRole ******************************************************************************** * Summary: * This function switches the role between Central and Peripheral. If device * is connected while switching role, then it is first disconnected. * * Parameters: * void * * Return: * void * *******************************************************************************/ void SwitchRole(void) { CYBLE_API_RESULT_T apiResult; /* if the switch role flag is set... */ if(switch_Role == TRUE) { /* Process pending BLE events */ CyBle_ProcessEvents(); /* If there is an existing connection, then disconnect before switching * role. */ if((cyBle_connHandle.bdHandle != 0)) { /* Disconnect the device and process the event */ CyBle_GapDisconnect(cyBle_connHandle.bdHandle); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Peripheral closed connection "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } switch(ble_gap_state) { case BLE_PERIPHERAL: /* If the current role is Peripheral and system is advertising, * then stop advertisement before switching role */ if(CyBle_GetState() == CYBLE_STATE_ADVERTISING) { CyBle_GappStopAdvertisement(); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Peripheral Advertisment Stopped "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } if(CyBle_GetState() == CYBLE_STATE_DISCONNECTED) { /* Switch BLE role by starting scan. This way, the system is set * to Central role */ apiResult = CyBle_GapcStartScan(CYBLE_SCANNING_FAST); if(CYBLE_ERROR_OK == apiResult) { #ifdef DEBUG_ENABLED UART_UartPutString("Start Scan API called "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif /* Record the time at which Central role was started. This will be * used for timeout and switching to Peripheral operation*/ centralStartedTime = WatchDog_CurrentCount(); /* Update the current BLE role to Central */ ble_gap_state = BLE_CENTRAL; /* Reset the switch role flag*/ switch_Role = FALSE; } else { /* If scanning did not start, maintain the current role and retry later */ ble_gap_state = BLE_PERIPHERAL; #ifdef DEBUG_ENABLED UART_UartPutString("Start Scan API failed "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } } /* Process Pending BLE Events */ CyBle_ProcessEvents(); break; case BLE_CENTRAL: /* If the current role is Central and system is scanning, * then stop scanning before switching role */ if(CyBle_GetState() == CYBLE_STATE_SCANNING) { CyBle_GapcStopScan(); CyBle_ProcessEvents(); #ifdef DEBUG_ENABLED UART_UartPutString("Central Scan stopped "); UART_UartPutCRLF(' '); #endif } if(CyBle_GetState() == CYBLE_STATE_DISCONNECTED) { #ifdef ENABLE_ADV_DATA_COUNTER /* Increment data counter */ new_advData.advData[new_advData.advDataLen - 1] = dataADVCounter; cyBle_discoveryModeInfo.advData = &new_advData; #ifdef DEBUG_ENABLED UART_UartPutString("Updated ADV data = "); PrintNum(dataADVCounter); UART_UartPutCRLF(' '); #endif #endif /* Switch BLE role by starting advertisement. This way, the system is * set to Peripheral role */ apiResult = CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); if(apiResult == CYBLE_ERROR_OK) { /* If advertisement started successfully, set the BLE state and * reset the switch role flag*/ ble_gap_state = BLE_PERIPHERAL; clientConnectToDevice = FALSE; switch_Role = FALSE; #ifdef DEBUG_ENABLED UART_UartPutString("Peripheral Advertisment called "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } else { /* If advertisement did not start, maintain the current role and retry later */ ble_gap_state = BLE_CENTRAL; #ifdef DEBUG_ENABLED UART_UartPutString("Start Peripheral Advertisment Failed "); SendBLEStatetoUART(CyBle_GetState()); UART_UartPutCRLF(' '); #endif } } /* Process Pending BLE Events */ CyBle_ProcessEvents(); break; default: break; } } }
/******************************************************************************* * Function Name: main() ******************************************************************************** * Summary: * Main function for the project. * * Parameters: * None * * Return: * None * * Theory: * The function starts BLE and UART components. * This function process all BLE events and also implements the low power * functionality. * *******************************************************************************/ int main() { CyGlobalIntEnable; #if (DEBUG_UART_ENABLED == ENABLED) UART_DEB_Start(); #endif /* (DEBUG_UART_ENABLED == ENABLED) */ DBG_PRINTF("BLE Cycling Sensor Example Project \r\n"); Disconnect_LED_Write(LED_OFF); Advertising_LED_Write(LED_OFF); CyBle_Start(AppCallback); /* Start CYBLE component and register generic event handler */ CyBle_Start(AppCallback); /* Register service specific callback functions */ CscsInit(); CpsInit(); WDT_Start(); /*************************************************************************** * Main polling loop ***************************************************************************/ while(1) { /* CyBle_ProcessEvents() allows BLE stack to process pending events */ CyBle_ProcessEvents(); /* To achieve low power in the device */ LowPowerImplementation(); /*********************************************************************** * Wait for connection established with Central device ***********************************************************************/ if(CyBle_GetState() == CYBLE_STATE_CONNECTED) { /******************************************************************* * Periodically simulate Cycling characteristics and send * results to the Client *******************************************************************/ if(mainTimer != 0u) { mainTimer = 0u; SimulateCyclingPower(); CyBle_ProcessEvents(); SimulateCyclingSpeed(); } /* Store bounding data to flash only when all debug information has been sent */ #if (DEBUG_UART_ENABLED == ENABLED) if((cyBle_pendingFlashWrite != 0u) && ((UART_DEB_SpiUartGetTxBufferSize() + UART_DEB_GET_TX_FIFO_SR_VALID) == 0u)) #else if(cyBle_pendingFlashWrite != 0u) #endif /* (DEBUG_UART_ENABLED == ENABLED) */ { CYBLE_API_RESULT_T apiResult; apiResult = CyBle_StoreBondingData(0u); (void)apiResult; DBG_PRINTF("Store bonding data, status: %x \r\n", apiResult); } } } }
int main() { CYBLE_API_RESULT_T apiResult; CYBLE_LP_MODE_T lpMode; CyGlobalIntEnable; CommInit(); /* Start communication component */ printf("BLE Uart Transmission Collector Example Project \r\n"); Scanning_LED_Write(LED_OFF); apiResult = CyBle_Start(AppCallBack); if(apiResult != CYBLE_ERROR_OK) { printf("CyBle_Start API Error: %xd \r\n", apiResult); } else { printf("CyBle_Start API ok \r\n"); } /* Enable the Interrupt component connected to interrupt */ TC_CC_ISR_StartEx(InterruptHandler); /* Start the components */ Timer_Start(); while(1) { if(CyBle_GetState() != CYBLE_STATE_INITIALIZING) { /* Enter DeepSleep mode between connection intervals */ lpMode = CyBle_EnterLPM(CYBLE_BLESS_DEEPSLEEP); if(lpMode == CYBLE_BLESS_DEEPSLEEP) { /* Put the device into the Deep Sleep mode only when all debug information has been sent if(UART_DEB_SpiUartGetTxBufferSize() == 0u) { CySysPmDeepSleep(); } else { CySysPmSleep(); }*/ CySysPmSleep(); /* Handle scanning led blinking */ HandleLEDs(ble_state); } HandleLEDs(ble_state); } /*********************************************************************** * Wait for connection established with Central device ***********************************************************************/ if(CyBle_GetState() == CYBLE_STATE_CONNECTED) { /******************************************************************* * Periodically measure a battery level and temperature and send * results to the Client *******************************************************************/ CommMonitorUart(); CommMonitorBLE(); #if 0 if(mainTimer != 0u) { mainTimer = 0u; if(storeBondingData == ENABLED) { cystatus retValue; retValue = CyBle_StoreBondingData(0u); printf("Store bonding data, status: %lx \r\n", retValue); storeBondingData = DISABLED; } } #endif } /******************************************************************* * Processes all pending BLE events in the stack *******************************************************************/ CyBle_ProcessEvents(); } }