//############################################################################## void tr_pen_color( uint8_t cl ) { UART_UartPutChar( 0x1b ); UART_UartPutChar( '[' ); UART_UartPutChar( '3' ); UART_UartPutChar( cl+'0' ); UART_UartPutChar( 'm' ); }
/******************************************************************************* * Function Name: PrintHex ******************************************************************************** * Summary: * Converts HEX number to characters in ASCII that can be printed on * terminal. * * Parameters: * num: HEX to be converted to string. * * Return: * void * *******************************************************************************/ void PrintHex(uint8 num) { #if (DEBUG_ENABLED == 1) uint8 temp[2]; temp[0] = num%16; num = num/16; temp[1] = num%16; UART_UartPutString("0x"); if(temp[1] < 10) { UART_UartPutChar('0' + temp[1]); } else { UART_UartPutChar('A' + (temp[1] - 10)); } if(temp[0] < 10) { UART_UartPutChar('0' + temp[0]); } else { UART_UartPutChar('A' + (temp[0] - 10)); } #else num = num; #endif }
//############################################################################## void tr_brush_color( uint8_t cl ) { UART_UartPutChar( 0x1b ); UART_UartPutChar( '[' ); UART_UartPutChar( '4' ); UART_UartPutChar( cl+'0' ); UART_UartPutChar( 'm' ); }
//############################################################################## void tr_locate( uint8_t y, uint8_t x ) { UART_UartPutChar( 0x1b ); UART_UartPutChar( '[' ); uart_putlong( y, 10 ); UART_UartPutChar( ';' ); uart_putlong( x, 10 ); UART_UartPutChar( 'H' ); }
//############################################################################## void tr_attr( uint8_t atr, uint8_t fg, uint8_t bg ) { UART_UartPutChar( 0x1b ); UART_UartPutChar( '[' ); UART_UartPutChar( atr+'0' ); UART_UartPutChar( ';' ); UART_UartPutChar( '3' ); UART_UartPutChar( fg+'0' ); UART_UartPutChar( ';' ); UART_UartPutChar( '4' ); UART_UartPutChar( bg+'0' ); UART_UartPutChar( 'm' ); }
int8 respondIrri(int8 irriStatus){ if(irriStatus == 0){ // If irriStatus is 0 then 'F' is sent to DevKit8000 UART_UartPutChar('F'); return 0; } else{ // If irriStatus isn't 0 then "XF" is sent to DevKit8000 UART_UartPutChar('X'); UART_UartPutChar('F'); return -1; } }
int8 respondVent(int8 ventStatus){ if(ventStatus == 0){ // If ventStatus is 0 then 'V' is sent to DevKit8000 UART_UartPutChar('V'); return 0; } else{ // If ventStatus isn't 0 then "XV" is sent to DevKit8000 UART_UartPutChar('X'); UART_UartPutChar('V'); return -1; } }
int8 respondWin(int8 winStatus){ if(winStatus == 0){ // If winStatus is 0 then 'W' is sent to DevKit8000 UART_UartPutChar('W'); return 0; } else{ // If heatStatus isn't 0 then "XW" is sent to DevKit8000 UART_UartPutChar('X'); UART_UartPutChar('W'); return -1; } }
int8 respondHeat(int8 heatStatus, uint8 onOff){ if(heatStatus == 0){ // If heatStatus is 0 then onOff('H' or 'K') is sent to DevKit8000 UART_UartPutChar(onOff); return 0; } else{ // If heatStatus isn't 0 then 'X' and onOff('H' or 'K') is sent to DevKit8000 UART_UartPutChar('X'); UART_UartPutChar(onOff); return -1; } }
//----------respondTemp0---------- int8 respondTemp(uint8 temp){ if(temp){ // If temp is between 1 and 200(both inclusive) "T" and temp is sent to DevKit8000 UART_UartPutChar('T'); UART_UartPutChar(temp); return 0; } else{ // If temp isn't between 1 and 200(both inclusive) "XT" is sent to DevKit8000 UART_UartPutChar('X'); UART_UartPutChar('T'); return -1; } }
int8 respondSoilHum(uint8 index, uint8 soilHum){ if(soilHum <= 10 && soilHum >= 1){ // If soilHum is between 1 and 10(both inclusive) "S", the index number and soilHum is sent to DevKit8000 UART_UartPutChar('S'); UART_UartPutChar(index + CONVERT_TO_ASCII + 1); //Conevert to ASCII and convert to 1-6. UART_UartPutChar(soilHum); return 0; } else{ // If soilHum isn't between 1 and 10(both inclusive) "XS" is sent to DevKit8000 UART_UartPutChar('X'); UART_UartPutChar('S'); return -1; } }
/***********************************Main***********************************/ int main() { int16 mav_data; ADC_ISR_StartEx(ADC_interrupt); CyGlobalIntEnable; UART_Start(); /* Initialize ADC */ ADC_Start(); /* Initialize ADC */ ADC_StartConvert(); /* Start ADC conversions */ ADC_IRQ_Enable(); /* Enable ADC interrupts */ for (;;) { if(data_ready) { mav_data = mavg_filter(accgroen); gradergroen = grader(mav_data); //UART_UartPutChar(mav_data); //UART_UartPutChar(mav_data>>8); UART_UartPutChar(gradergroen); UART_UartPutChar(gradergroen>>8); data_ready = FALSE; } } }
cystatus CyBtldrCommWrite(uint8* buffer, uint16 size, uint16* count, uint8 timeOut) { for(*count = 0; *count < size; (*count)++) { UART_UartPutChar(buffer[*count]); } return CYRET_SUCCESS; }
/******************************************************************************* * Function Name: Ancs_UpdateOutputInformation() ******************************************************************************** * Summary: * This function prints data onto the UART terminal. * * Parameters: * None * * Return: * None * * Theory: * The function prints the number of Missed calls, Voicemails and Emails on the * screen. The same line on the terminal is updated with new data if no other * notification came up. * *******************************************************************************/ static void Ancs_UpdateOutputInformation(void) { /* Update the same line if no new notification since. */ if(printStatus == PRINT_SAME_LINE) { /* Go back to the same line */ UART_UartPutChar(13); } else { UART_UartPutString("\n\r"); } printStatus = PRINT_SAME_LINE; UART_UartPutString("Missed calls: "); UART_UartPutChar(HexToDecimal(missedCallCount, 1)); UART_UartPutChar(HexToDecimal(missedCallCount, 0)); UART_UartPutString(" Voicemails: "); UART_UartPutChar(HexToDecimal(voiceMailCount, 1)); UART_UartPutChar(HexToDecimal(voiceMailCount, 0)); UART_UartPutString(" Emails: "); UART_UartPutChar(HexToDecimal(emailCount, 1)); UART_UartPutChar(HexToDecimal(emailCount, 0)); }
/* For GCC compiler revise _write() function for printf functionality */ int _write(int file, char *ptr, int len) { int i; file = file; for (i = 0; i < len; i++) { UART_UartPutChar(*ptr++); } return len; }
/******************************************************************************* * Function Name: PrintNum ******************************************************************************** * Summary: * Converts decimal number to characters in ASCII that can be printed on * terminal. * * Parameters: * num: number to be converted to string. * * Return: * void * *******************************************************************************/ void PrintNum(uint8 num) { #if (DEBUG_ENABLED == 1) uint8 temp[3]; temp[0] = num%10; num = num/10; temp[1] = num%10; num = num/10; temp[2] = num%10; if(temp[2] == 0) { if(temp[1] == 0) { UART_UartPutChar('0' + temp[0]); } else { UART_UartPutChar('0' + temp[1]); UART_UartPutChar('0' + temp[0]); } } else { UART_UartPutChar('0' + temp[2]); UART_UartPutChar('0' + temp[1]); UART_UartPutChar('0' + temp[0]); } #else num = num; #endif }
/******************************************************************************* * Function Name: UART_UartPutString ******************************************************************************** * * Summary: * Places a NULL terminated string in the transmit buffer to be sent at the * next available bus time. * This function is blocking and waits until there is space available to put * all the requested data into the transmit buffer. * * Parameters: * string: pointer to the null terminated string array to be placed in the * transmit buffer. * * Return: * None * *******************************************************************************/ void UART_UartPutString(const char8 string[]) { uint32 bufIndex; bufIndex = 0u; /* Blocks the control flow until all data has been sent */ while(string[bufIndex] != ((char8) 0)) { UART_UartPutChar((uint32) string[bufIndex]); bufIndex++; } }
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); } } }
/******************************************************************************* * Function Name: Ancs_HandleData() ******************************************************************************** * Summary: * The function handles the GATT notifications on the Data Source * characteristic. * * Parameters: * uint8 * value: Pointer to the data as part of the notification * * Return: * None * * Theory: * The function takes the GATT notification coming on the Data Source and * displays it to the user. * *******************************************************************************/ void Ancs_HandleData(uint8 * value) { uint8 * uid = value + 1; uint16 counter; switch(value[0]) { case ANCS_COMMAND_ID_GET_NOTIFICATION_ATTRIBUTES: if(memcmp(uid, ancsNotification.notificationUid, 4) == 0) { if(value[5] == ANCS_NOTIFICATION_ATTRIBUTE_ID_TITLE) { uint16 length = value[6] + (value[7] << 8); UART_UartPutString("from "); for(counter = 0; counter < length; counter++) { UART_UartPutChar(value[8 + counter]); } } } /* If positive and negative actions can be taken up */ if((ancsNotification.eventFlags & ANCS_EVENT_FLAG_POSITIVE_ACTION) && (ancsNotification.eventFlags & ANCS_EVENT_FLAG_NEGATIVE_ACTION)) { UART_UartPutString(". Accept (Y) or Decline (N)? "); ancsUsageState = ANCS_USAGE_INCOMING_CALL_WAITING_FOR_INPUT; } break; /* The case GET_APP_ATTRIBUTES is not shown in this example. * The case PERFORM_NOTIFICATION_ACTION is not a valid case. */ default: break; } }
/******************************************************************************* * Function Name: StackEventHandler ******************************************************************************** * * Summary: * This is an event callback function to receive events from the BLE Component. * * Parameters: * uint8 event: Event from the CYBLE component * void* eventParams: A structure instance for corresponding event type. The * list of event structure is described in the component * datasheet. * * Return: * None * *******************************************************************************/ void StackEventHandler(uint32 event, void *eventParam) { char authFailReasonCode[3]; CYBLE_GAP_AUTH_FAILED_REASON_T *authFailReason; switch(event) { /* Mandatory events to be handled by Find Me Target design */ case CYBLE_EVT_STACK_ON: case CYBLE_EVT_GAP_DEVICE_DISCONNECTED: /* Start BLE advertisement for 30 seconds and update link * status on LEDs */ CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); Advertising_LED_Write(LED_ON); PWM_WriteCompare(LED_NO_ALERT); break; case CYBLE_EVT_GAP_DEVICE_CONNECTED: UART_UartPutString("GAP Device Connected\r\n"); /* BLE link is established */ Advertising_LED_Write(LED_OFF); break; case CYBLE_EVT_TIMEOUT: if(*(uint8 *) eventParam == CYBLE_GAP_ADV_MODE_TO) { /* Advertisement event timed out, go to low power * mode (Hibernate mode) and wait for an external * user event to wake up the device again */ Advertising_LED_Write(LED_OFF); Hibernate_LED_Write(LED_ON); PWM_Stop(); Wakeup_SW_ClearInterrupt(); Wakeup_Interrupt_ClearPending(); Wakeup_Interrupt_Start(); CySysPmHibernate(); } break; /********************************************************** * GAP Events ***********************************************************/ case CYBLE_EVT_GAP_AUTH_REQ: UART_UartPutString("Authorization Requested\r\n"); break; case CYBLE_EVT_GAP_AUTH_COMPLETE: UART_UartPutString("Pairing is Successful!\r\n"); break; case CYBLE_EVT_GAP_AUTH_FAILED: authFailReason = ((CYBLE_GAP_AUTH_FAILED_REASON_T *)eventParam); UART_UartPutString("Authentication Failed with Reason Code: "); snprintf(authFailReasonCode, sizeof(authFailReasonCode), "%lu", (uint32)(*authFailReason)); UART_UartPutString(authFailReasonCode); UART_UartPutChar("\r\n"); break; /********************************************************** * GATT Events ***********************************************************/ case CYBLE_EVT_GATT_CONNECT_IND: UART_UartPutString("GATT Connection Indication\r\n"); /* Set OOB data after the connection indication but before the authorization * request is received. */ if(CyBle_GapSetOobData(cyBle_connHandle.bdHandle, CYBLE_GAP_OOB_ENABLE, securityKey, NULL, NULL) != CYBLE_ERROR_OK) { UART_UartPutString("Error in Setting OOB Data\r\n"); } else { UART_UartPutString("OOB Data is Set\r\n"); } break; default: break; } }
// Cypress tinyprintf void putdata ( void* p, char c){ if(c=='\n') UART_UartPutChar('\r'); UART_UartPutChar(c); }
void Loop_Master_WaitingSPort() { char itoastr[5]; uint8 tmpbyte; uint8 uartchar = UART_UartGetChar(); if (uartchar != 0) { UART_UartPutChar(uartchar); UART_UartPutChar('\n'); // Remember, when using address filtering, the node address have to be the first byte // of the payload. // Slave 1 is node address 100. // Slave 2 is node address 200. switch (uartchar) { case '1': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 1; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '2': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 2; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '3': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 3; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '4': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 1; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '5': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 2; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case '6': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 3; RFM69_DataPacket_TX(rfdatabytes, 64); }; break; case 'a': case 'A': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 100, 0); #endif rfdatabytes[0] = 100; rfdatabytes[1] = 0xAB; RFM69_DataPacket_TX(rfdatabytes, 64); /* Enter in RX state until response from slave is received or timeout. ¡¡¡ Remember !!! At Master we don´t use address filtering, so we can received data from different slaves. */ UART_UartPutString("Waiting data from Slave 1..."); RFM69_SetMode(OP_MODE_RX); timercnt = 1000; // set timout = 1000ms = 1s. master_state = 1; }; break; case 'b': case 'B': { // If using encryption, enable address filtering to avoid // encryption of the byte that contains the address, or the slave will not // respond. (more info in RFM datasheet) #ifdef TEST_WITH_ENCRYPTION RFM69_SetAddressFiltering(1, 200, 0); #endif rfdatabytes[0] = 200; rfdatabytes[1] = 0xAB; RFM69_DataPacket_TX(rfdatabytes, 64); /* Enter in RX state until response from slave is received or timeout. ¡¡¡ Remember !!! At Master we don´t use address filtering, so we can received data from different slaves. */ UART_UartPutString("Waiting data from Slave 2..."); RFM69_SetMode(OP_MODE_RX); timercnt = 1000; // set timout = 1000ms = 1s. master_state = 1; }; break; case '9': { tmpbyte = RFM69_GetTemperature(); itoa(tmpbyte, itoastr, 10); UART_UartPutString("Temperature: register raw value = "); UART_UartPutString(itoastr); UART_UartPutChar('\n'); }; break; case '?': { TerminalSend_Master(); }; break; } if (master_state == 0) UART_UartPutString("Select test :> "); } }
/******************************************************************************* * Function Name: UART_UartPutCRLF ******************************************************************************** * * Summary: * Places a byte of data followed by a carriage return (0x0D) and * line feed (0x0A) into the transmit buffer. * This function is blocking and waits until there is space available to put * all the requested data into the transmit buffer. * * Parameters: * txDataByte : the data to be transmitted. * * Return: * None * *******************************************************************************/ void UART_UartPutCRLF(uint32 txDataByte) { UART_UartPutChar(txDataByte); /* Blocks control flow until all data has been sent */ UART_UartPutChar(0x0Du); /* Blocks control flow until all data has been sent */ UART_UartPutChar(0x0Au); /* Blocks control flow until all data has been sent */ }
uint8_t send_command( const char *const text, const char *const command, const char *const wait, uint16_t timeout) { int length; // if text passed in, send to host if( text ){ UART_UartPutString( text ); } // if command passed in, send to host and wifi uarts if( command) { UART_UartPutString( command); uWIFI_UartPutString( command); } // if wait for reply text, supplied, scan buffer for command if ( wait ) { while( 1 ) { // attempt to get a string (needs timeout) length = at_getstr(rx_buffer,MAX_BUFFER,50); timeout -- ; // return 0 on timed out if( timeout == 0 ) { UART_UartPutString("\nTimed out waiting for correct reply\n"); return 0; } // got a return if( length ) { if ( 1 ) { UART_UartPutString( "buff = [\n"); UART_UartPutString( rx_buffer); UART_UartPutString( "]\n"); } // look for string if(strstr( rx_buffer, wait ) != NULL ) { UART_UartPutString("\nfound - ["); UART_UartPutString( rx_buffer ) ; // found break; } } else { if ( 0 ) { UART_UartPutString("\nEmpty buffer\n"); } } } } while( uWIFI_SpiUartGetRxBufferSize() ) { UART_UartPutChar( uWIFI_UartGetChar() ); } while( uWIFI_SpiUartGetRxBufferSize() ) { UART_UartPutChar( uWIFI_UartGetChar() ); } return 1; }
/******************************************************************************* * 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(); } }
/** * @brief Does all the work of getting data, simple parse and sending to LED's * * @return none */ void run_server(void) { uint8_t *buf_ptr; uint8_t ret = 0; //Set to black StripLights_DisplayClear(0); // LED off P1_6_Write(0); // this caused all sorts of issues, so i removed it #if 0 while( ret == 0 ) { ret = send_command("resetting\r\n", "AT+RST\r\n\n","ready",5000); //.com on later firmware, ready on others } P1_6_Write(0); #endif // Simple progress meter StripLights_SetXToColour( getColor(1) ,1 ); // returns "no change" , 1 CONNECT TO AP, 2 BE AN AP, 3 BOTH send_command("cwmode=3\r\n", "AT+CWMODE=1\r\n",NULL,DEFAULT_TIMEOUT); // Simple progress meter, stage 2 StripLights_SetXToColour( getColor(1) ,5 ); do { // LED On P1_6_Write(1); // Not really used, can be used to see if already connected send_command("get ip\r\n","AT+CIFSR\r\n",NULL,0); CyDelay(400); // wireless AP settings, first param is ap name, second password ret =send_command("connecting\r\n","AT+CWJAP=\"monkeysee\",\"monkeydo\"\r\n","OK",1000); // LED Off P1_6_Write(0); }while( ret == 0 ); // progress meter, stage 3 StripLights_SetXToColour( getColor(1) ,10 ); do { CyDelay(400); ret= send_command("check connection\r\n","AT+CWJAP?\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 4 StripLights_SetXToColour( getColor(1) ,15 ); //GET LOCAL IP ADDRESS do { CyDelay(400); ret= send_command("get ip\r\n","AT+CIFSR\r\n",NULL,0); } while( ret == 0 ); // progress meter, stage 5 StripLights_SetXToColour( getColor(1) ,20 ); //START UP MULTI-IP CONNECTION // 0 Single IP connection // 1 Multi IP connection do { CyDelay(400); ret= send_command("multip\r\n","AT+CIPMUX=1\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 6 StripLights_SetXToColour( getColor(1) ,25 ); do { CyDelay(400); ret= send_command("cipserver\r\n","AT+CIPSERVER=1,40002\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 7 StripLights_SetXToColour( getColor(1) ,30 ); // switch into UDP listen/receive mode, all data passed in will be of +IDT,0,length:data format do { CyDelay(400); ret= send_command("cipsto\r\n","AT+CIPSTO=9000\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 8 StripLights_SetXToColour( getColor(1) ,45 ); do { CyDelay(400); ret= send_command("cipmux\r\n","AT+CIPMUX=0\r\n","OK",DEFAULT_TIMEOUT); } while( ret == 0 ); // progress meter, stage 9 StripLights_SetXToColour( getColor(1) ,50 ); // setup done, tell host (if connected) UART_UartPutString("\nSetup and ready!\n"); // progress meter, stage 10, done StripLights_SetXToColour( getColor(2) ,StripLights_MAX_X ); CyDelay(200); // all off StripLights_DisplayClear(0); while(1) { int i ; uint8_t ch; // if switch is help, run into bootloader , mostly for dev BOOT_CHECK(); //led off P1_6_Write(0); // wait for data from ESP UART while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); // fetch one byte of data ch = uWIFI_UartGetChar(); // find start of +IPD,0,450: if( ch == '+' ) { //wait, this could be set to < 4 instead and then can drop the other checks. while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); if( ch == 'I' ) { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); if( ch == 'P' ) { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); if( ch == 'D' ) { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); //UART_UartPutString("Found +IPD\n"); // illformatted if( ch != ',' ) { UART_UartPutString("Unexpected char #1\n"); break; } //led on P1_6_Write(1); // scan for end of descriptive // 10 will be enough 0,450: i = 10 ; do { while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); i--; if( i ==0 ) { UART_UartPutString("couldn't find : marker\n"); break; } } while( ch != ':' ); //UART_UartPutString("Found Start of data block\n"); // point to start or end of LED buffer #if defined(REVERSE_DIRECTION) buf_ptr = (uint8_t*)&StripLights_ledArray[0][StripLights_MAX_X-1]; for( i = 0 ; i <= StripLights_MAX_X ; i++ ) { #else buf_ptr = (uint8_t*)&StripLights_ledArray[0][0]; for( i = 0 ; i <= StripLights_MAX_X ; i++ ) { #endif // fill in rx_buffer from ESP UART //gbr while ( uWIFI_SpiUartGetRxBufferSize() < 3 ); // 0 = green // 1 = red // 2 = blue buf_ptr[1] = uWIFI_UartGetChar(); buf_ptr[0] = uWIFI_UartGetChar(); buf_ptr[2] = uWIFI_UartGetChar(); #if defined(REVERSE_DIRECTION) buf_ptr -= sizeof(uint32_t); #else buf_ptr += sizeof(uint32_t); #endif } //end of buffer while ( uWIFI_SpiUartGetRxBufferSize() == 0 ); ch = uWIFI_UartGetChar(); // check this char for sanity if wanted /* UART_UartPutChar( ch) ; UART_UartPutString(" - Buffer filled\n"); UART_UartPutString( rx_buffer ); UART_UartPutString("END\n"); */ //send to LED strip while( StripLights_Ready() == 0); StripLights_Trigger(1); //CyDelay(4); BOOT_CHECK(); } } } } } } /** * @brief Just echo across UARTs * * * @return none */ void echo_uart(void) { while(1) { int ret; BOOT_CHECK(); ret = 0 ; while( ret == 0 ) { ret = send_command("resetting\r\n", "AT+RST\r\n\n","ready",5000); //.com on later firmware, ready on others } // echo from usb uart to wifi uart if( UART_SpiUartGetRxBufferSize() ) { uWIFI_UartPutChar( UART_UartGetChar() ); } //echo from wifi uart to usb uart if( uWIFI_SpiUartGetRxBufferSize() ) { UART_UartPutChar( uWIFI_UartGetChar() ); } } } // various simple effects (not used, sending PC does work) could be offline mode void ColorFader( int count , uint32 color) { while(count--){ FadeToColor( 0,StripLights_COLUMNS, color, 50,1 ); } } void Tween1( void ) { hsv_color tween; static led_color src; static hsv_color result ; src.c.r = rand()%255; src.c.g = rand()%255; src.c.b = rand()%255; tween = rgb_to_hsv((led_color)getColor(rand()%StripLights_COLOR_WHEEL_SIZE)); result.hsv = TweenerHSV( 0, StripLights_COLUMNS, result.hsv, tween.hsv, 10 ,1); // Tweener( 100,src.rgb ); src.c.r += 5-(rand()%10); src.c.g += 5-(rand()%10); src.c.b += 5-(rand()%10); result.hsv = TweenerHSV( StripLights_COLUMNS, StripLights_COLUMNS, result.hsv, tween.hsv, 10 ,-1 ); }
int main() { /* Initializing all the Flags and Indexes to 0 */ ALL_LED_OFF (); Count = 0; Index = 0; AddRequest = 0; DelRequest = 0; CyGlobalIntEnable; /* Comment this line to disable global interrupts. */ /* Start BLE component and register Event handler function */ CyBle_Start(StackEventHandler); /* Start UART Component which is used for receiving inputs and Debugging */ UART_Start(); printf("BLE WhiteList Example \r\n"); printf("Press A to add a Device to WhiteList. R to remove the Device from Whitelist \r\n"); /* Continuous loop scans for inputs from UART Terminal and accordingly handles Addition to and Removal from Whitelist. Also processes BLE events */ for(;;) { //Checks the internal task queue in the BLE Stack CyBle_ProcessEvents(); if(UART_SpiUartGetRxBufferSize()) { UartRxDataSim = UART_UartGetChar(); if (UartRxDataSim == 'A' || UartRxDataSim == 'a') // The user has to Enter D for disconnection { printf ("Enter the Address of the Device. Press Z to Go Back \r\n"); for (;;) { if (Count ==12) { //If the user had entered the full address, stop advertisement //for addition process CyBle_GappStopAdvertisement (); /*Once We stop advertisement, the CYBLE_EVT_GAPP_ADVERTISEMENT_START_STOP event is invoked. After this, the API for adding the device to whitelist is invoked in the StackEventHandler*/ RED_LED_ON (); AddRequest = 1; printf ("\r\n"); printf ("Address is 0x%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x \r\n", whitelistdeviceaddress.bdAddr[5], whitelistdeviceaddress.bdAddr[4], whitelistdeviceaddress.bdAddr[3], whitelistdeviceaddress.bdAddr[2], whitelistdeviceaddress.bdAddr[1], whitelistdeviceaddress.bdAddr[0]); printf ("Attempting to Add to whitelist \r \n"); Count = 0; break; } if(UART_SpiUartGetRxBufferSize()) { UartRxDataSim = UART_UartGetChar(); if (UartRxDataSim == 'Z' || UartRxDataSim == 'z') { Count = 0; printf("Press A to add a Device to WhiteList \r\n"); break; } else { if ((UartRxDataSim >= '0') && (UartRxDataSim <= '9' )) { AddrNibble = UartRxDataSim - '0'; UART_UartPutChar (UartRxDataSim); } else if ((UartRxDataSim >= 'A') && (UartRxDataSim <= 'F' )) { AddrNibble = UartRxDataSim - 'A' + 0xA; UART_UartPutChar (UartRxDataSim); } else if ((UartRxDataSim >= 'a') && (UartRxDataSim <= 'f' )) { AddrNibble = UartRxDataSim - 'a' + 0xA; UART_UartPutChar (UartRxDataSim); } else { printf ("\nplease Enter a Valid Address. Press A to Enter a New Address. R ro remove the Device\r\n"); Count = 0; break; } //Receiving the addresss Nibble by Nibble whitelistdeviceaddress.bdAddr[5 - (Count/2)] = (whitelistdeviceaddress.bdAddr[5 - (Count/2)]<<4)|AddrNibble; Count ++; } } } } else if (UartRxDataSim == 'R' || UartRxDataSim == 'r') { if (Index == 0) { printf ("No Devices in WhiteList. press A to Add \r\n"); } else { printf (" The List of Devices are given below \4\n"); uint8 i = 0; // Retrieving the list of added devices for user to choose for (i = 0; i< Index; i++) { printf ("Device %d 0x%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x \r\n",i + 1, whitelistdeviceaddressBackup[i].bdAddr[5], whitelistdeviceaddressBackup[i].bdAddr[4], whitelistdeviceaddressBackup[i].bdAddr[3], whitelistdeviceaddressBackup[i].bdAddr[2], whitelistdeviceaddressBackup[i].bdAddr[1], whitelistdeviceaddressBackup[i].bdAddr[0]); } printf ("Enter the Index of the device to be removed. Press Z to go back \r\n"); for (;;) { if(UART_SpiUartGetRxBufferSize()) { UartRxDataSim = UART_UartGetChar(); if (UartRxDataSim == 'Z' || UartRxDataSim == 'z') { printf("Press A to add a Device to WhiteList. R to remove \r\n"); break; } else if (UartRxDataSim >= '1' || UartRxDataSim <= '0' + Index) { RemoveIndex = UartRxDataSim - '1'; if(RemoveIndex < Index) { CyBle_GappStopAdvertisement (); /*Once We stop advertisement, the CYBLE_EVT_GAPP_ADVERTISEMENT_START_STOP event is invoked. After this, the API for removing the device from whitelist is invoked in the StackEventHandler*/ DelRequest = 1; break; } else { printf("There is no device with that number.\r\n"); } } else { printf ("Invaid Index. Press A to Add and R to remove a Device"); break; } } } } } } } }
/******************************************************************************* * Function Name: main() ******************************************************************************** * Summary: * The top-level application function for the project. * * Parameters: * None * * Return: * None * * Theory: * This is the main function for the application. It does the following - * 1. Initializes the BLE component * 2. Initializes a buffer from which data is sent out over BLE * 3. Registers a Protocol Service Multiplexer (PSM) for the L2CAP channel * 4. Sends L2CAP channel request to the peer device once BLE connection is made * 5. Once the L2CAP channel is made, starts sending data until credits exhaust * and waits for more credits * 6. The data is sent only when the previous data is transmitted completely, * to avoid packet loss. * * Refer Bluetooth 4.1 specification, Volume 3, Part A, section 3.4 for details. * * Side Effects: * None * *******************************************************************************/ int main() { uint32 counter = 0; CyGlobalIntEnable; CyBle_Start(StackEventHandler); UART_Start(); /* Clear screen and put a welcome message */ UART_UartPutChar(12); UART_UartPutString("========= BLE L2CAP Throughput Measurement - Sender side =========\n\n\r"); /* Initialize entire buffer; the amount of data sent will * depend on the peer device's MTU and MPS */ for(counter = 0; counter < MAX_MTU_SIZE; counter++) { buffer[counter] = counter; } for(;;) { if(CyBle_GetState() == CYBLE_STATE_CONNECTED) { /* State machine for L2CAP channel maintenance */ switch(channelState) { case CHANNEL_PSM_NOT_REGISTERED: /* Register a new PSM */ if(CYBLE_ERROR_OK == CyBle_L2capCbfcRegisterPsm(LOCAL_DEVICE_PSM, 0)) { channelState = CHANNEL_PSM_REGISTERED; } break; case CHANNEL_PSM_REGISTERED: /* Create a CBFC channel - send a request to the peer device. * Once the peer responds, CYBLE_EVT_L2CAP_CBFC_CONN_CNF * event will come up on this device. */ CyBle_L2capCbfcConnectReq(cyBle_connHandle.bdHandle, PEER_DEVICE_PSM, LOCAL_DEVICE_PSM, &cbfcLocalParameters); UART_UartPutString("\n\rL2CAP channel connection request sent. "); channelState = CHANNEL_SENT_REQUEST; break; case CHANNEL_CREATED: /* Keep sending data as long as credits are available. * Maximum of (peer device's MTU - 2) bytes can be sent in * one LE-frame. * New data is sent only when the previous data is * transmitted completely. */ if(previousDataTransmitted == true) { CyBle_L2capChannelDataWrite(cyBle_connHandle.bdHandle, l2capCid, buffer, cbfcPeerParameters.mtu - 2); previousDataTransmitted = false; } break; default: break; } } CyBle_ProcessEvents(); } }
//############################################################################## void tr_fill_line( char ascii, uint8_t cnt ) { uint8_t i; for(i=0; i<cnt; i++) UART_UartPutChar(ascii); }
/******************************************************************************* * Function Name: StackEventHandler() ******************************************************************************** * Summary: * Event handler function for the BLE events processing. * * Parameters: * uint32 eventCode: The event to be processed * void * eventParam: Pointer to hold the additional information associated * with an event * * Return: * None * * Theory: * The function is responsible for handling the events generated by the stack. * In addition to handling general events for BLE advertisement, connection, * and disconnection, this function handles the events related to L2CAP CBFC * connection-oriented channel connection and disconnection. * * For details on L2CAP connection-oriented channels, refer to Bluetooth 4.1 * specification, Volume 3, Part A, section 3.4. * * Side Effects: * None * *******************************************************************************/ void StackEventHandler(uint32 eventCode, void * eventParam) { CYBLE_L2CAP_CBFC_CONN_CNF_PARAM_T cbfcResponse; uint8 counter; switch(eventCode) { /* Stack initialized; ready for advertisement */ case CYBLE_EVT_STACK_ON: UART_UartPutString("\n\rAdvertising with Address: "); for(counter = 6; counter > 0; counter--) { UART_UartPutChar(HexToAscii(cyBle_deviceAddress.bdAddr[counter - 1], 1)); UART_UartPutChar(HexToAscii(cyBle_deviceAddress.bdAddr[counter - 1], 0)); UART_UartPutChar(' '); } CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); break; /* Advertisement timed out; Restart advertisement */ case CYBLE_EVT_GAPP_ADVERTISEMENT_START_STOP: if(CyBle_GetState() == CYBLE_STATE_DISCONNECTED) { CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); } break; case CYBLE_EVT_GAP_DEVICE_CONNECTED: UART_UartPutString("\n\rConnected. "); break; /* Device disconnected */ case CYBLE_EVT_GAP_DEVICE_DISCONNECTED: /* The L2CAP channel is disconnected but the PSM is already * registered. Update the state machine. */ channelState = CHANNEL_PSM_REGISTERED; previousDataTransmitted = true; /* Restart advertisement */ UART_UartPutString("\n\n\rDisconnected. "); UART_UartPutString("\n\rAdvertising again. "); UART_UartPutString("Address: "); for(counter = 6; counter > 0; counter--) { UART_UartPutChar(HexToAscii(cyBle_deviceAddress.bdAddr[counter - 1], 1)); UART_UartPutChar(HexToAscii(cyBle_deviceAddress.bdAddr[counter - 1], 0)); UART_UartPutChar(' '); } CyBle_GappStartAdvertisement(CYBLE_ADVERTISING_FAST); break; /* CBFC connection response is received */ case CYBLE_EVT_L2CAP_CBFC_CONN_CNF: cbfcResponse = *(CYBLE_L2CAP_CBFC_CONN_CNF_PARAM_T *)eventParam; /* If the connection request was accepted */ if(cbfcResponse.response == CYBLE_L2CAP_CONNECTION_SUCCESSFUL) { UART_UartPutString("\n\rL2CAP channel connection request accepted. Sending data. "); /* Cache the connection parameters and channel ID */ cbfcPeerParameters = cbfcResponse.connParam; l2capCid = cbfcResponse.lCid; /* Update the state machine to indicate that the channel * is created. */ channelState = CHANNEL_CREATED; } break; /* Peer device requested for CBFC channel disconnection */ case CYBLE_EVT_L2CAP_CBFC_DISCONN_IND: if(*(uint16 *)eventParam == l2capCid) { /* L2CAP channel disconnected but the PSM is still registered */ channelState = CHANNEL_PSM_REGISTERED; previousDataTransmitted = true; } break; /* Invalid credits received from peer device; initiate disconnect */ case CYBLE_EVT_L2CAP_CBFC_TX_CREDIT_IND: if(((CYBLE_L2CAP_CBFC_LOW_TX_CREDIT_PARAM_T *)eventParam)->result != CYBLE_L2CAP_RESULT_SUCCESS) { CyBle_L2capDisconnectReq(l2capCid); channelState = CHANNEL_PSM_REGISTERED; } break; /* Previous data transmission completed */ case CYBLE_EVT_L2CAP_CBFC_DATA_WRITE_IND: previousDataTransmitted = true; break; default: break; } }