/** * set BLE_RST pin to 0 and then release it */ void power_ResetKW40() { GPIO_DRV_ClearPinOutput( KW40_RST ); OSA_TimeDelay( 10 ); GPIO_DRV_SetPinOutput( KW40_RST ); OSA_TimeDelay( 200 ); }
static void MainTask(void *arg) { OSA_TimeDelay(500); drv_Mpu9250.Init(); OSA_TimeDelay(500); PRINTF("\n****** uServer ******\r\n"); LED1_EN; LED2_EN; LED3_EN; int counter = 0; while(1) { //drv_Mpu9250.Update(); LED1_TOGGLE; OSA_TimeDelay(50); LED3_TOGGLE; OSA_TimeDelay(50); LED2_TOGGLE; OSA_TimeDelay(50); LED1_TOGGLE; OSA_TimeDelay(50); LED3_TOGGLE; OSA_TimeDelay(50); LED2_TOGGLE; OSA_TimeDelay(50); OSA_TimeDelay(700); counter++; } }
/*! * \brief Kinetis SDK task, toggles a LED every 1 second. * \param param task parameter */ static void sdk_task(task_param_t param) { (void)param; /* unused parameter */ for(;;) { GPIO_DRV_TogglePinOutput(LED_RED); /* toggle blue LED */ OSA_TimeDelay(1000); /* wait 1000 ms */ } }
static void FnetTask() { // Delay the start of FNET OSA_TimeDelay(5000); /* Init UART. */ fnet_cpu_serial_init(FNET_CFG_CPU_SERIAL_PORT_DEFAULT, 115200); /* Enable Interrupts.*/ fnet_cpu_irq_enable(0); /* Run FNET application. - Function does not return */ fapp_main(); while(1){OSA_TimeDelay(1000);} }
static void bluetooth_AdvModeUpdateTask(task_param_t param) { bluetooth_SendGetAdvModeReq(); while(1) { bluetooth_WaitForAdvModeUpdate(OSA_WAIT_FOREVER); if(bluetoothCurrentAdvMode == bluetooth_advMode_enable) { OSA_TimeDelay( 500 ); if ( true == gui_sensorTag_IsActive() ) { GuiDriver_NotifyKW40( GUI_CURRENT_APP_SENSOR_TAG ); } bluetooth_icon.img = bluetooth_icon_blue_bmp; } else { watch_LinkStateUpdate(linkState_disconnected); bluetooth_icon.img = bluetooth_icon_white_bmp; } GuiDriver_ImageDraw(&bluetooth_icon); } }
/*! * task to blink led rtos between 1 seconds. */ void task_led_rtos(task_param_t param) { LED_RTOS_EN; while(1) { LED_RTOS_TOGGLE; OSA_TimeDelay(1000); } }
/*FUNCTION********************************************************************** * * Function Name : SMARTCARD_DRV_InstallInterfaceCallback * Description : This function de-activates the SMARTCARD interface/card slot. * *END**************************************************************************/ void SMARTCARD_DRV_Deactivate(uint32_t instance) { assert(instance < HW_SMARTCARD_INSTANCE_COUNT); /* Invoke SMARTCARD IP specific function to deactivate the card */ smartcardDrvInterface.smartcardDrvInterfaceDeactivate(instance); /*Wait for 100 ms*/ OSA_TimeDelay(100); }
/** * turn the screen on by switching on the power supply * and sending the command */ void power_TurnScreenON() { if ( false == isPowerActive_OLED ) { GPIO_DRV_TogglePinOutput( KW40_WU ); OSA_TimeDelay(10); GPIO_DRV_SetPinOutput( KW40_GPIO ); PWR_OLED_TurnON(); while ( OLED_STATUS_SUCCESS != OLED_SendCmd( OLED_CMD_DISPLAYON, FIRST_BYTE ) ) {} } }
void PORTD_IRQHandler(void) { PORT_HAL_ClearPortIntFlag(PORTD_BASE_PTR); if(haptic_MutexLock(0) == kStatus_OSA_Success) { GPIO_DRV_ClearPinOutput( KW40_GPIO ); OSA_TimeDelay(1); GPIO_DRV_SetPinOutput( KW40_GPIO ); haptic_MutexUnlock(); } }
static int nio_dummy_write(void *dev_context, void *fp_context, const void *buf, size_t nbytes, int *error) { NIO_DUMMY_DEV_CONTEXT_STRUCT *devc = (NIO_DUMMY_DEV_CONTEXT_STRUCT*)dev_context; NIO_DUMMY_FP_CONTEXT_STRUCT *fpc = (NIO_DUMMY_FP_CONTEXT_STRUCT*)fp_context; fpc->wcnt += nbytes; OSA_SemaWait(&devc->lock, OSA_WAIT_FOREVER); devc->total += nbytes; devc->wtotal += nbytes; OSA_SemaPost(&devc->lock); /* todo: replace with OSA yield. Not part of OSA yet */ OSA_TimeDelay(1); return 0; }
/*FUNCTION********************************************************************** * * Function Name : SDRAM_Initialization_sequence * Description : The SDRAM Initializes sequence. *END**************************************************************************/ void SDRAM_Initialization_sequence(sdram_block_selection_t whichBlock) { uint32_t *mrsAddr = 0; /* Issue a PALL command */ SDRAM_DRV_SendCommand(0, whichBlock, kSDRAMPrechargeCommand); /* Accessing a SDRAM location*/ *(uint16_t *)(SDRAM_START_ADDRESS) = SDRAM_COMMAND_ACCESSVALUE; /* Enable the refresh */ SDRAM_DRV_SetRefreshCmd(0, whichBlock, true); /* Wait for cycles */ OSA_TimeDelay(1); /* Issue MSR command */ SDRAM_DRV_SendCommand(0, whichBlock, kSDRAMMrsCommand); /* Put the right value on SDRAM address bus for SDRAM mode register, * The address of SDRAM Pins is as below: * A2 ~ A0: burst length 0 * 000->1 * 001->2 * 010->4 * 011->8 * res * A3: burst type * 0 -> seq * 1 -> Interleave * * A6 ~ A4: CAS latency * 000-> res * 001-> 1 * 010-> 2 * 011-> 3 * res * A8 ~ A7: Operationg Mode * 00->Stardard Operation * res * A9: Write Burst Mode * 0-> Programmed Burst Length * 1-> Single Location Access */ mrsAddr = (uint32_t *)(SDRAM_START_ADDRESS + 0x00000800U); *mrsAddr = SDRAM_COMMAND_ACCESSVALUE; }
/*! * task to blink led rtos between 1 seconds. */ void task_led_rtos( task_param_t param ) { TimerInit(&Led1Timer, "Led1Timer", 250, OnLed1TimerEvent, false); TimerInit(&Led2Timer, "Led2Timer", 250, OnLed2TimerEvent, false); TimerInit(&Led3Timer, "Led3Timer", 250, OnLed3TimerEvent, false); // Switch LED 1 ON GpioWrite(&Led1, 0); TimerStart(&Led1Timer); while (1) { if ( Led1TimerEvent == true ) { Led1TimerEvent = false; // Switch LED 1 OFF GpioWrite(&Led1, 1); // Switch LED 2 ON GpioWrite(&Led2, 0); TimerStart(&Led2Timer); } if ( Led2TimerEvent == true ) { Led2TimerEvent = false; // Switch LED 2 OFF GpioWrite(&Led2, 1); // Switch LED 3 ON GpioWrite(&Led3, 0); TimerStart(&Led3Timer); } if ( Led3TimerEvent == true ) { Led3TimerEvent = false; // Switch LED 3 OFF GpioWrite(&Led3, 1); // Switch LED 1 ON GpioWrite(&Led1, 0); TimerStart(&Led1Timer); } OSA_TimeDelay(50); } }
void task_fxos_rtos( task_param_t param ) { /*! I2C channel to be used by digital 3D accelerometer */ Fxos.instance = FXOS8700CQ_I2C_INSTANCE; I2c.I2c = &Fxos; I2cInit(&I2c, I2C_SCL, I2C_SDA); /* Initialize accelerometer */ FxosInit (FXOS_I2C_ADDRESS); while (1) { accel_sensor_data_t sensorData; if ( FxosReadSensorData(&sensorData) != FAIL ) { LOG_DEBUG_BARE("DATA: Accelerometer (X/Y/Z) \t%d \t%d \t%d\r\n", sensorData.accelX, sensorData.accelY, sensorData.accelZ); } OSA_TimeDelay(5000); } }
void panic( panicId_t id, uint32_t location, uint32_t extra1, uint32_t extra2 ) { #if gUsePanic_c /* Save the Link Register */ volatile uint32_t savedLR; // __asm("str r14, [SP]"); __asm("push {r2} "); __asm("push {LR} "); __asm("pop {r2} "); __asm("str r2, [SP, #4]"); __asm("pop {r2}"); panic_data.id = id; panic_data.location = location; panic_data.extra1 = extra1; panic_data.extra2 = extra2; panic_data.linkRegister = savedLR; panic_data.cpsr_contents = 0; #if 0 OSA_ExitCritical(kCriticalDisableInt); /* enable interrupts */ OSA_TimeDelay(100); /* allowing datalogs to get out */ #endif OSA_EnterCritical(kCriticalDisableInt); /* disable interrupts */ /* cause processor to halt */ #ifdef __IAR_SYSTEMS_ICC__ __asm("BKPT #0xF"); __asm("NOP"); __asm("NOP"); __asm("NOP"); #endif #ifdef RVDS __breakpoint(); #endif /* infinite loop just to ensure this routine never returns */ for(;;) { __asm("NOP"); } #endif }
/* ** =================================================================== ** Callback : runMonitor ** Description : Task function entry. ** Parameters : ** task_init_data - OS task parameter ** Returns : Nothing ** =================================================================== */ void runMonitor(os_task_param_t task_init_data) { /* Write your local variable definition here */ #ifdef PEX_USE_RTOS while (1) { #endif /* Write your code here ... */ OSA_TimeDelay(10); /* Example code (for task release) */ #ifdef PEX_USE_RTOS } #endif }
/** * task in charge for putting HEXIWEAR to sleep * @param param optional parameter */ static void power_Task( void* param ) { while (1) { osa_status_t status = OSA_SemaWait( &power_sema, OSA_WAIT_FOREVER ); if ( kStatus_OSA_Success == status ) { while ( POWER_STATUS_SUCCESS != power_Sleep() ) { OSA_TimeDelay( 100 ); } } else { catch( CATCH_SEMAPHORE ); } } }
void runSchedulerInterface(os_task_param_t task_init_data) { printf("[Scheduler Interface] Task started.\n"); // Allow scheduler and handler time to initialize OSA_TimeDelay(40); // Create a buffer for received messages char inputBuffer[HANDLER_BUFFER_SIZE + 1]; memset(inputBuffer, 0, HANDLER_BUFFER_SIZE + 1); // Create a queue to receive messages _queue_id receiveQueue = _initializeQueue(SCHEDULER_QUEUE_ID); // Register for reading with the serial handler if(!OpenR(receiveQueue)){ printf("[Scheduler Interface] Unable to register for reading with the serial handler.\n"); _task_block(); } #ifdef PEX_USE_RTOS while (1) { #endif // Wait for console input GetLine(inputBuffer); // Handle input commands if(!si_handleCommand(inputBuffer)){ printf("[Scheduler Interface] Invalid command.\n"); } // Clear input buffer memset(inputBuffer, 0, HANDLER_BUFFER_SIZE + 1); #ifdef PEX_USE_RTOS } #endif // Unregister with the serial handler Close(); }
/*lint -save -e970 Disable MISRA rule (6.3) checking. */ int main(void) /*lint -restore Enable MISRA rule (6.3) checking. */ { /* Write your local variable definition here */ /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/ PE_low_level_init(); /*** End of Processor Expert internal initialization. ***/ /* Write your code here */ /* For example: for(;;) { } */ for(;;){ GPIO_DRV_ClearPinOutput(RGB_RedLed); // On Red Led OSA_TimeDelay(300); GPIO_DRV_ClearPinOutput(RGB_GreenLed); // On Green Led OSA_TimeDelay(300); GPIO_DRV_ClearPinOutput(RGB_BlueLed); // On Blue Led OSA_TimeDelay(300); GPIO_DRV_SetPinOutput(RGB_RedLed); // Off Red Led OSA_TimeDelay(300); GPIO_DRV_SetPinOutput(RGB_GreenLed); // Off Green Led OSA_TimeDelay(300); GPIO_DRV_SetPinOutput(RGB_BlueLed); // Off Blue Led OSA_TimeDelay(300); } /*** Don't write any code pass this line, or it will be deleted during code generation. ***/ /*** RTOS startup code. Macro PEX_RTOS_START is defined by the RTOS component. DON'T MODIFY THIS CODE!!! ***/ #ifdef PEX_RTOS_START PEX_RTOS_START(); /* Startup of the selected RTOS. Macro is defined by the RTOS component. */ #endif /*** End of RTOS startup code. ***/ /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/ for(;;){} /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/ } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/
/*! * @brief Main demo function. */ int main (void) { tpm_general_config_t driverInfo; accel_dev_t accDev; accel_dev_interface_t accDevice; accel_sensor_data_t accelData; accel_i2c_interface_t i2cInterface; tpm_pwm_param_t yAxisParams; tpm_pwm_param_t xAxisParams; int16_t xData, yData; int16_t xAngle, yAngle; xAxisParams.mode = kTpmEdgeAlignedPWM; xAxisParams.edgeMode = kTpmHighTrue; xAxisParams.uFrequencyHZ = 100000u; xAxisParams.uDutyCyclePercent = 0u; yAxisParams.mode = kTpmEdgeAlignedPWM; yAxisParams.edgeMode = kTpmHighTrue; yAxisParams.uFrequencyHZ = 100000u; yAxisParams.uDutyCyclePercent = 0u; // Register callback func for I2C i2cInterface.i2c_init = I2C_DRV_MasterInit; i2cInterface.i2c_read = I2C_DRV_MasterReceiveDataBlocking; i2cInterface.i2c_write = I2C_DRV_MasterSendDataBlocking; accDev.i2c = &i2cInterface; accDev.accel = &accDevice; accDev.slave.baudRate_kbps = BOARD_ACCEL_BAUDRATE; accDev.slave.address = BOARD_ACCEL_ADDR; accDev.bus = BOARD_ACCEL_I2C_INSTANCE; // Initialize standard SDK demo application pins. hardware_init(); // Accel device driver utilizes the OSA, so initialize it. OSA_Init(); // Print the initial banner. PRINTF("Bubble Level Demo!\r\n\r\n"); // Initialize the Accel. accel_init(&accDev); // Prepare memory for initialization. memset(&driverInfo, 0, sizeof(driverInfo)); // Init TPM. TPM_DRV_Init(BOARD_BUBBLE_TPM_INSTANCE, &driverInfo); // Set clock for TPM. TPM_DRV_SetClock(BOARD_BUBBLE_TPM_INSTANCE, kTpmClockSourceModuleClk, kTpmDividedBy2); // Main loop. Get sensor data and update duty cycle for the TPM timer. while(1) { // Wait 5 ms in between samples (accelerometer updates at 200Hz). OSA_TimeDelay(5); // Get new accelerometer data. accDev.accel->accel_read_sensor_data(&accDev,&accelData); // Init PWM module with updated configuration. TPM_DRV_PwmStart(BOARD_BUBBLE_TPM_INSTANCE, &xAxisParams, BOARD_TPM_X_CHANNEL); TPM_DRV_PwmStart(BOARD_BUBBLE_TPM_INSTANCE, &yAxisParams, BOARD_TPM_Y_CHANNEL); // Get the X and Y data from the sensor data structure.fxos_data xData = (int16_t)((accelData.data.accelXMSB << 8) | accelData.data.accelXLSB); yData = (int16_t)((accelData.data.accelYMSB << 8) | accelData.data.accelYLSB); // Convert raw data to angle (normalize to 0-90 degrees). No negative angles. xAngle = abs((int16_t)(xData * 0.011)); yAngle = abs((int16_t)(yData * 0.011)); // Update angles to turn on LEDs when angles ~ 90 if(xAngle > 85) xAngle = 100; if(yAngle > 85) yAngle = 100; // Update angles to turn off LEDs when angles ~ 0 if(xAngle < 5) xAngle = 0; if(yAngle < 5) yAngle = 0; // Update pwm duty cycle xAxisParams.uDutyCyclePercent = 100 - xAngle ; yAxisParams.uDutyCyclePercent = 100 - yAngle ; // Print out the raw accelerometer data. PRINTF("x= %d y = %d\r\n", xData, yData); } }
/*! * @brief main function */ int main(void) { uint8_t i; uint8_t index, indexChar, value; uint8_t cmdBuff[1] = {0xFF}; uint8_t sendBuff[1] = {0xFF}; // save data sent to i2c slave uint8_t receiveBuff[1] = {0xFF}; // save data received from i2c slave i2c_master_state_t master; i2c_status_t returnValue; i2c_device_t slave = { .address = 0x3A, .baudRate_kbps = 100 }; hardware_init(); dbg_uart_init(); // Configure I2C pins configure_i2c_pins(BOARD_I2C_COMM_INSTANCE); OSA_Init(); GPIO_DRV_Init(0, ledPins); // Init I2C module I2C_DRV_MasterInit(BOARD_I2C_COMM_INSTANCE, &master); printf("\r\n====== I2C Master ======\r\n\r\n"); OSA_TimeDelay(500); LED_toggle_master(); OSA_TimeDelay(500); LED_toggle_master(); OSA_TimeDelay(500); LED_toggle_master(); OSA_TimeDelay(500); LED_toggle_master(); while (1) { printf("\r\nI2C Master reads values from I2C Slave sub address:\r\n"); printf("\r\n------------------------------------"); printf("\r\nSlave Sub Address | Character "); printf("\r\n------------------------------------"); for (i=Subaddress_Index_0; i<Invalid_Subaddress_Index; i++) { cmdBuff[0] = i; returnValue = I2C_DRV_MasterReceiveDataBlocking( BOARD_I2C_COMM_INSTANCE, &slave, cmdBuff, 1, receiveBuff, sizeof(receiveBuff), 500); if (returnValue == kStatus_I2C_Success) { printf("\r\n[%d] %c", i, receiveBuff[0]); } else { printf("\r\nI2C communication failed, error code: %d", returnValue); } } printf("\r\n------------------------------------"); printf("\r\n"); printf("\r\nPlease input Slave sub address and the new character."); do { printf("\r\nSlave Sub Address: "); indexChar = getchar(); putchar(indexChar); printf("\r\nInput New Character: "); value = getchar(); putchar(value); printf("\n"); index = (uint8_t)(indexChar - '0'); if (index >= Invalid_Subaddress_Index) { printf("\r\nInvalid Sub Address."); } } while (index >= Invalid_Subaddress_Index); cmdBuff[0] = index; sendBuff[0] = value; returnValue = I2C_DRV_MasterSendDataBlocking( BOARD_I2C_COMM_INSTANCE, &slave, cmdBuff, 1, sendBuff, sizeof(sendBuff), 500); if (returnValue != kStatus_I2C_Success) { printf("\r\nI2C communication failed, error code: %d", returnValue); } } }
/** * initialize MAXIM module */ maxim_status_t MAXIM_Init( handleMAXIM_t* maximHandle, const settingsMAXIM_t* maximSettings ) { /** * initialize intern structures, * which will be used from now on */ memcpy( (void*)&self, (void*)maximHandle, sizeof(self) ); memcpy( (void*)&settings, (void*)maximSettings, sizeof(settings) ); statusI2C_t status = I2C_Init( &(self.protocol), settings.address, settings.baudRate_kbps ); if ( STATUS_I2C_SUCCESS != status ) { return STATUS_MAXIM_INIT_ERROR; } else { // read revision ID statusI2C_t i2cStatus = STATUS_I2C_SUCCESS; genericI2cHandle_t i2cProtocol = self.protocol; /** * set up the registers */ i2cStatus |= MAXIM_Reset(); OSA_TimeDelay(50); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_LED_RED_PA, 0xFF ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_LED_IR_PA, 0x33 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_LED_GREEN_PA, 0xFF ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_PROXY_PA, 0x19 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_MULTILED_MODE_CR_12, 0x03 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_MULTILED_MODE_CR_34, 0x00 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_FIFO_CFG , 0x06 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_SPO2_CFG , 0x43 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_PROXY_INT_THR , 0x14 ); /** clear FIFO pointers */ i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_FIFO_WR_PTR , 0 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_FIFO_RD_PTR , 0 ); i2cStatus |= I2C_WriteReg( &i2cProtocol, MAXIM_REG_FIFO_OV_PTR , 0 ); // read only green LED valus maxim_bytesPerSample = MAXIM_BYTES_PER_ADC_VALUE * 1; maxim_bitMask = 0x00003FFFF; return STATUS_MAXIM_SUCCESS; } }
void APP_Run(void) { int i; uint8_t red, green, blue; uint8_t dimmPercent = 50; NEO_Init(); for(;;) { GPIO_DRV_TogglePinOutput(LEDRGB_BLUE); if (start) { NEO_ClearAllPixel(); NEO_TransferPixels(); for(i=0;i<NEO_NOF_PIXEL;i++) { red = 0x10+(i*0x10); if (red==0) { red = 0x10; } green = 0x20+(i*0x20); if (green==0) { green = 0x10; } blue = 0x30+(i*0x30); if (blue==0) { blue = 0x10; } NEO_SetPixelRGB(i, red, green, blue); NEO_TransferPixels(); OSA_TimeDelay(50); } NEO_ClearAllPixel(); NEO_TransferPixels(); for(i=0;i<=7;i++) { NEO_SetPixelRGB(i, 0x00, 0x00, (i+1)*10); NEO_DimmPercentPixel(i, i*10); } for(i=8;i<=15;i++) { NEO_SetPixelRGB(i, 0x00, i-7*10, 0x00); NEO_DimmPercentPixel(i, (i-8)*10); } for(i=16;i<=23;i++) { NEO_SetPixelRGB(i, i-15*10, 0x00, 0x00); NEO_DimmPercentPixel(i, (i-16)*10); } for(i=24;i<=31;i++) { NEO_SetPixelRGB(i, 0x00, 0x00, (i-23)*10); NEO_DimmPercentPixel(i, (i-23)*10); } for(i=32;i<=39;i++) { NEO_SetPixelRGB(i, 0x00, i-31*10, 0x00); NEO_DimmPercentPixel(i, (i-31)*10); } for(i=40;i<=47;i++) { NEO_SetPixelRGB(i, i-40*10, 0, 0x00); NEO_DimmPercentPixel(i, (i-39)*10); } for(i=48;i<=55;i++) { NEO_SetPixelRGB(i, 0, 0, i-47*10); NEO_DimmPercentPixel(i, (i-47)*10); } for(i=56;i<=63;i++) { NEO_SetPixelRGB(i, 0, 0, i-55*10); NEO_DimmPercentPixel(i, (i-55)*10); } NEO_TransferPixels(); for(i=0;i<NEO_NOF_PIXEL;i++) { green = 0x5+(i*0x10); if (red==0) { red = 0x5; } blue = 0x5+(i*0x15); if (green==0) { green = 0x5; } red = 0x5+(i*0x20); if (blue==0) { blue = 0x5; } NEO_SetPixelRGB(i, red, green, blue); NEO_DimmPercentPixel(i, dimmPercent); } NEO_TransferPixels(); NEOL_PixelTrail(0xff, 0x00, 0x00, NEO_PIXEL_FIRST, NEO_PIXEL_LAST, 12, 50, 10*2); NEOL_PixelTrail(0xff, 0xff, 0x00, NEO_PIXEL_FIRST, NEO_PIXEL_LAST, 12, 50, 10*2); NEOL_PixelTrail(0x00, 0xff, 0x00, NEO_PIXEL_FIRST, NEO_PIXEL_LAST, 12, 50, 10*2); NEOL_PixelTrail(0x00, 0xff, 0xff, NEO_PIXEL_FIRST, NEO_PIXEL_LAST, 12, 50, 10*2); NEO_ClearAllPixel(); NEOL_PixelTrail(0x00, 0x00, 0xff, NEO_PIXEL_FIRST, NEO_PIXEL_LAST, 12, 50, 10*2); NEO_ClearAllPixel(); NEOL_PixelTrail(0xff, 0x00, 0xff, NEO_PIXEL_FIRST, NEO_PIXEL_LAST, 12, 50, 10*2); } } }
/*! * @brief The i2c slave * The function runs i2c slave with interrupt active mode. Slave receive data from * master and echo back to master */ int main(void) { // Number byte data will be transfer uint32_t count = 0; uint32_t i = 0; // Buffer store data to transfer uint8_t dataBuff[DATA_LENGTH] = {0}; // state of slave i2c_slave_state_t slave; // user configuration i2c_slave_user_config_t userConfig = { .address = 0x7FU, .slaveCallback = NULL, .callbackParam = NULL, .slaveListening = false, #if FSL_FEATURE_I2C_HAS_START_STOP_DETECT .startStopDetect = false, #endif #if FSL_FEATURE_I2C_HAS_STOP_DETECT .stopDetect = false, #endif }; // Initialize hardware hardware_init(); // Initialize OSA OSA_Init(); PRINTF("\r\n================== I2C SLAVE NON-BLOCKING =================\r\n\r\n"); PRINTF("Slave is running ..."); // Initialize slave I2C_DRV_SlaveInit(BOARD_I2C_INSTANCE, &userConfig, &slave); // Loop transfer while(1) { // Slave receive buffer from master I2C_DRV_SlaveReceiveData(BOARD_I2C_INSTANCE, (uint8_t*)&count, 1); /* Wait until transfer is successful */ while (I2C_DRV_SlaveGetReceiveStatus(BOARD_I2C_INSTANCE, NULL) != kStatus_I2C_Success); // Clear receive buffer for(i = 0; i < count; i++) { dataBuff[i] = 0; } // Slave receive buffer from master I2C_DRV_SlaveReceiveData(BOARD_I2C_INSTANCE, dataBuff, count); /* Wait until transfer is successful */ while (I2C_DRV_SlaveGetReceiveStatus(BOARD_I2C_INSTANCE, NULL) != kStatus_I2C_Success); // Print receive data PRINTF("\r\nSlave received:\r\n"); for (i = 0; i < count; i++) { // Print 16 numbers in a line. if ((i & 0x0F) == 0) { PRINTF("\r\n "); } PRINTF(" %02X", dataBuff[i]); } // Slave send buffer received from master I2C_DRV_SlaveSendData(BOARD_I2C_INSTANCE, dataBuff, count); /* Wait until transfer is successful */ while (I2C_DRV_SlaveGetTransmitStatus(BOARD_I2C_INSTANCE, NULL) != kStatus_I2C_Success); OSA_TimeDelay(1); } }
/** * put MCU to VLPS mode, * enable/disable possible interrupts * @return status flag */ static power_status_t power_PutMCUToSleep() { bool sensorTimerState = false; /** check for active communication */ /** I2C */ i2c_status_t currentStatus; uint32_t rxBytesRemaining = 0, txBytesRemaining = 0; for ( uint8_t i2cIdx = 0; i2cIdx < 2; i2cIdx++ ) { currentStatus = kStatus_I2C_Success; currentStatus |= I2C_DRV_MasterGetSendStatus ( i2cIdx, &txBytesRemaining ); currentStatus |= I2C_DRV_MasterGetReceiveStatus( i2cIdx, &rxBytesRemaining ); if ( ( kStatus_I2C_Success == currentStatus ) && ( 0 != ( txBytesRemaining + rxBytesRemaining ) ) ) { return POWER_STATUS_INIT_ERROR; } } /** UART */ // ... switch ( currentPowerMode ) { case POWER_CURRENT_MODE_NORMAL: case POWER_CURRENT_MODE_SLEEP_SHALLOW: { // shouldn't happen catch( CATCH_POWER ); } case POWER_CURRENT_MODE_SLEEP_TOTAL: { // check sensor timer's state to remember for later sensorTimerState = timer_IsActive( HEXIWEAR_TIMER_SENSOR ); if ( true == sensorTimerState ) { timer_Stop( HEXIWEAR_TIMER_SENSOR ); } break; } case POWER_CURRENT_MODE_SLEEP_SENSOR_TAG: { // do nothing break; } } /** * set the wake-up source to none, * as it will be set by invoking the wake-up function in the appropriate interrupt handler */ if ( POWER_CURRENT_MODE_NORMAL != currentPowerMode ) { // disable interrupts // asm(" CPSID i"); /** put MCU to sleep (VLPS) */ POWER_SYS_SetMode( 1, kPowerManagerPolicyAgreement ); CLOCK_SYS_UpdateConfiguration( 0, kClockManagerPolicyForcible ); OSA_TimeDelay(10); // GPIO_DRV_TogglePinOutput( KW40_WU ); // enable interrupts // asm(" CPSIE i "); // rtc_datetime_t // tmpTime; // RTC_GetCurrentTime( &tmpTime ); // RTC_TriggerAlarm( &tmpTime, 1 ); } /** * MCU is now woken up, * undo all the power-save changes from the above */ switch ( currentPowerMode ) { case POWER_CURRENT_MODE_NORMAL: { RTC_EnableAlarm(); RTC_UpdateAlarm(); power_TurnScreenON(); // if the timer was enabled before entering the sleep mode, enable it if ( true == sensorTimerState ) { timer_Start( HEXIWEAR_TIMER_SENSOR ); } break; } case POWER_CURRENT_MODE_SLEEP_SHALLOW: { // shouldn't happen catch( CATCH_POWER ); break; } case POWER_CURRENT_MODE_SLEEP_TOTAL: { break; } case POWER_CURRENT_MODE_SLEEP_SENSOR_TAG: { break; } } return POWER_STATUS_SUCCESS; }
/*FUNCTION********************************************************************** * * Function Name : SMARTCARD_DRV_NCN8025Activate * Description : Activates the smartcard interface * *END**************************************************************************/ void SMARTCARD_DRV_NCN8025Activate(uint32_t instance, smartcard_reset_type_t resetType) { assert(instance < HW_SMARTCARD_INSTANCE_COUNT); smartcard_state_t * smartcardStatePtr = (smartcard_state_t *)g_smartcardStatePtr[instance]; smartcard_interface_slot_t * interfaceSlotParams = (smartcard_interface_slot_t *)(smartcardStatePtr->interfaceState->slot[smartcardStatePtr->interfaceConfig.cardSoltNo]); #if defined(EMVSIM_INSTANCE_COUNT) EMVSIM_Type * base = g_emvsimBase[instance]; #else uint32_t temp; UART_Type * base = g_uartBase[instance]; #endif smartcardStatePtr->timersState.initCharTimerExpired = false; smartcardStatePtr->resetType = resetType; /* Set data convention format into default direct mode */ #if defined(EMVSIM_INSTANCE_COUNT) smartcardStatePtr->cardParams.Fi = 372; smartcardStatePtr->cardParams.currentD = 1; EMVSIM_HAL_SetControl(base, kEmvsimCtrlInverseConvention, false); EMVSIM_HAL_SetBaudrateDivisor(base, (smartcardStatePtr->cardParams.Fi / smartcardStatePtr->cardParams.currentD)); #else UART_BWR_S2_RXINV(base, 0); UART_BWR_S2_MSBF(base, 0); UART_BWR_C3_TXINV(base, 0); #endif if(resetType == kSmartcardColdReset) { /* Ensure that RST is LOW and CMD is high here so that PHY goes in normal mode */ #if defined(EMVSIM_INSTANCE_COUNT) EMVSIM_HAL_SetVCCEnable(base, true); EMVSIM_HAL_SetCardVCCEnablePolarity(base, kEmvsimVccEnIsHigh); EMVSIM_HAL_ResetCard(base, kEmvsimResetAssert); #else GPIO_DRV_ClearPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.resetPort, (uint32_t)smartcardStatePtr->interfaceConfig.resetPin)); GPIO_DRV_SetPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.controlPort, (uint32_t)smartcardStatePtr->interfaceConfig.controlPin)); #endif if (smartcardStatePtr->cardParams.vcc == kSmartcardVoltageClassA5_0V) { /* vcc = 5v: vsel0=0,vsel1= 1 */ GPIO_DRV_SetPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.vsel1Port, (uint32_t)smartcardStatePtr->interfaceConfig.vsel1Pin)); GPIO_DRV_ClearPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.vsel0Port, (uint32_t)smartcardStatePtr->interfaceConfig.vsel0Pin)); } else if (smartcardStatePtr->cardParams.vcc == kSmartcardVoltageClassB3_3V) { /* vcc = 3.3v: vsel0=x,vsel1= 0 */ GPIO_DRV_ClearPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.vsel1Port, (uint32_t)smartcardStatePtr->interfaceConfig.vsel1Pin)); GPIO_DRV_ClearPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.vsel0Port, (uint32_t)smartcardStatePtr->interfaceConfig.vsel0Pin)); } else { /* vcc = 1.8v: vsel0=1,vsel1= 1 */ GPIO_DRV_SetPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.vsel1Port, (uint32_t)smartcardStatePtr->interfaceConfig.vsel1Pin)); GPIO_DRV_SetPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.vsel0Port, (uint32_t)smartcardStatePtr->interfaceConfig.vsel0Pin)); } /* Set PHY to start Activation sequence by pulling CMDVCC low */ #if defined(EMVSIM_INSTANCE_COUNT) EMVSIM_HAL_SetCardVCCEnablePolarity(base, kEmvsimVccEnIsLow); #else GPIO_DRV_ClearPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.controlPort, (uint32_t)smartcardStatePtr->interfaceConfig.controlPin)); #endif /* Wait for sometime as specified by EMV before pulling RST High */ /* As per EMV delay <= 42000 Clock cycles * as per PHY delay >= 1us */ #if defined(EMVSIM_INSTANCE_COUNT) /* Down counter trigger, and clear any pending counter status flag */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, false); EMVSIM_HAL_ClearTransmitStatus(base, kEmvsimGPCNT1Timeout); /* Disable counter interrupt */ EMVSIM_HAL_SetIntMode(base, kEmvsimIntGPCnt1, false); /* Set counter value */ EMVSIM_HAL_SetGPCNTValue(base, 1, interfaceSlotParams->clockToResetDelay); /* Select the clock for GPCNT */ EMVSIM_HAL_SetGPCClockSelect(base, 1, kEmvsimGPCCardClock); /* Trigger the counter */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, true); /* In polling mode */ while(!EMVSIM_HAL_GetTransmitStatus(base, kEmvsimGPCNT1Timeout)) {} /* Disable the counter */ EMVSIM_HAL_SetGPCClockSelect(base, 1, kEmvsimGPCClockDisable); /* Down counter trigger, and clear any pending counter status flag */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, false); EMVSIM_HAL_ClearTransmitStatus(base, kEmvsimGPCNT1Timeout); #else temp = (uint32_t)((float)(1 + (float)(((float)(1000*interfaceSlotParams->clockToResetDelay)) / ((float)smartcardStatePtr->interfaceConfig.sCClock)))); OSA_TimeDelay(temp); #endif /* Pull reset HIGH Now to mark the end of Activation sequence */ #if defined(EMVSIM_INSTANCE_COUNT) EMVSIM_HAL_ResetCard(base, kEmvsimResetDeassert); #else GPIO_DRV_SetPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.resetPort, (uint32_t)smartcardStatePtr->interfaceConfig.resetPin)); #endif } else if(resetType == kSmartcardWarmReset) { /* Ensure that card is not already active */ if(!interfaceSlotParams->active) { /* Card is not active;hence return */ return; } /* Pull RESET low to start warm Activation sequence */ #if defined(EMVSIM_INSTANCE_COUNT) EMVSIM_HAL_ResetCard(base, kEmvsimResetAssert); #else GPIO_DRV_ClearPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.resetPort, (uint32_t)smartcardStatePtr->interfaceConfig.resetPin)); #endif /* Wait for sometime as specified by EMV before pulling RST High */ /* As per EMV delay <= 42000 Clock cycles * as per PHY delay >= 1us */ #if defined(EMVSIM_INSTANCE_COUNT) /* Down counter trigger, and clear any pending counter status flag */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, false); EMVSIM_HAL_ClearTransmitStatus(base, kEmvsimGPCNT1Timeout); /* Disable counter interrupt */ EMVSIM_HAL_SetIntMode(base, kEmvsimIntGPCnt1, false); /* Set counter value */ EMVSIM_HAL_SetGPCNTValue(base, 1, interfaceSlotParams->clockToResetDelay); /* Select the clock for GPCNT */ EMVSIM_HAL_SetGPCClockSelect(base, 1, kEmvsimGPCCardClock); /* Trigger the counter */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, true); /* In polling mode */ while(!EMVSIM_HAL_GetTransmitStatus(base, kEmvsimGPCNT1Timeout)) {} /* Disable the counter */ EMVSIM_HAL_SetGPCClockSelect(base, 1, kEmvsimGPCClockDisable); /* Down counter trigger, and clear any pending counter status flag */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, false); EMVSIM_HAL_ClearTransmitStatus(base, kEmvsimGPCNT1Timeout); #else temp = (uint32_t)((float)(1 + (float)(((float)(1000*interfaceSlotParams->clockToResetDelay)) / ((float)smartcardStatePtr->interfaceConfig.sCClock)))); OSA_TimeDelay(temp); #endif /* Pull reset HIGH to mark the end of Activation sequence*/ #if defined(EMVSIM_INSTANCE_COUNT) EMVSIM_HAL_ResetCard(base, kEmvsimResetDeassert); #else GPIO_DRV_SetPinOutput(GPIO_MAKE_PIN((uint32_t)smartcardStatePtr->interfaceConfig.resetPort, (uint32_t)smartcardStatePtr->interfaceConfig.resetPin)); #endif } #if defined(EMVSIM_INSTANCE_COUNT) /* Down counter trigger, and clear any pending counter status flag */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, false); EMVSIM_HAL_ClearTransmitStatus(base, kEmvsimGPCNT0Timeout); EMVSIM_HAL_ClearTransmitStatus(base, kEmvsimGPCNT1Timeout); /* Set counter value for TS detection delay */ EMVSIM_HAL_SetGPCNTValue(base, 0, (INIT_DELAY_CLOCK_CYCLES + INIT_DELAY_CLOCK_CYCLES_ADJUSTMENT)); /* Pre-load counter value for ATR duration delay */ EMVSIM_HAL_SetGPCNTValue(base, 1, (EMV_ATR_DURATION_ETU + ATR_DURATION_ADJUSTMENT)); /* Select the clock for GPCNT for both TS detection and early start of ATR duration counter */ EMVSIM_HAL_SetGPCClockSelect(base, 0, kEmvsimGPCCardClock); EMVSIM_HAL_SetGPCClockSelect(base, 1, kEmvsimGPCTxClock); /* Enable counter interrupt for TS detection */ EMVSIM_HAL_SetIntMode(base, kEmvsimIntGPCnt0, true); /* Trigger the counter */ EMVSIM_HAL_SetControl(base, kEmvsimCtrlReceiverEnable, true); #endif /* Here the card was activated */ interfaceSlotParams->active = true; }
/*! * @brief Watchdog main routine * Run a simple application which enables watchdog, then * continuously refreshes the watchdog to prevent CPU reset * Upon SW1 button push, the watchdog will expire after * approximately 2 seconds and issue reset */ void main(void) { // Configure watchdog. const wdog_user_config_t wdogConfig = { .timeoutValue = 2048U,// Watchdog overflow time is about 2s .windowValue = 0, // Watchdog window value, 0-disable window function .clockPrescalerValue = kWdogClockPrescalerValueDevide1, // Watchdog clock prescaler .updateRegisterEnable = true, // Update register enabled .clockSource = kClockWdogSrcLpoClk, // Watchdog clock source is LPO 1KHz .workInWaitModeEnable = true, // Enable watchdog in wait mode .workInStopModeEnable = true, // Enable watchdog in stop mode .workInDebugModeEnable = false,// Disable watchdog in debug mode }; // Init hardware. hardware_init(); // Init OSA layer. OSA_Init(); // Call this function to initialize the console UART. This function // enables the use of STDIO functions (printf, scanf, etc.) dbg_uart_init(); // Init pinsfor switch and led. GPIO_DRV_Init(switchPins, ledPins); // Initialize wdog before the WDOG timer has a chance //to reset the device // Turn LED1 on; LED1_ON; WDOG_DRV_Init(&wdogConfig); // If not wdog reset, clear reset count if (!(RCM->SRS0 & RCM_SRS0_WDOG_MASK)) { WDOG_DRV_ClearResetCount(); printf("\r\n WDOG example \r\n"); } // Check if WDOG reset occurred , disable WDOG and turn off LED1. if (WDOG_DRV_GetResetCount()) { printf("\r\n WDOG reset count %ld",WDOG_DRV_GetResetCount()); } printf("\r\n Press SW1 to expire watchdog "); // Continue to run in loop to refresh watchdog until SW1 is pushed while (1) { // Check for SW1 button push.Pin is grounded when button is pushed. if (0 != is_key_pressed()) { while (1) { // Button has been pushed,blink LED // showing that the watchdog is about to expire. LED1_TOGGLE; OSA_TimeDelay(BLINK_TIME); } } // Restart the watchdog so it doesn't reset. WDOG_DRV_Refresh(); OSA_TimeDelay(100u); } }
uint32_t I2C_MS5637_Read(uint8_t osr) { uint8_t data[3] = {0,0,0}; uint8_t adc_read_reg = MS5637_ADC_READ; I2C_DRV_MasterSendDataBlocking(FSL_I2CCOM1, &MS5637_config, NULL, 0, &osr, 1, 1000); //initiate a pressure conversion switch (osr) { case D1_OSR_256: OSA_TimeDelay(1); break; // delay for conversion to complete case D1_OSR_512: OSA_TimeDelay(2); break; case D1_OSR_1024: OSA_TimeDelay(3); break; case D1_OSR_2048: OSA_TimeDelay(5); break; case D1_OSR_4096: OSA_TimeDelay(10); break; case D1_OSR_8192: OSA_TimeDelay(18); break; case D2_OSR_256: OSA_TimeDelay(1); break; case D2_OSR_512: OSA_TimeDelay(2); break; case D2_OSR_1024: OSA_TimeDelay(3); break; case D2_OSR_2048: OSA_TimeDelay(5); break; case D2_OSR_4096: OSA_TimeDelay(10); break; case D2_OSR_8192: OSA_TimeDelay(18); break; } I2C_DRV_MasterSendDataBlocking(FSL_I2CCOM1, &MS5637_config, NULL, 0, &adc_read_reg, 1, 1000); //initiate ADC read sequence I2C_DRV_MasterReceiveDataBlocking(FSL_I2CCOM1, &MS5637_config, NULL, 0, data, 3, 1000); //Read ADC registers return (uint32_t) (((uint32_t) data[0] << 16) | (uint32_t) data[1] << 8 | data[2]); // construct PROM data for return to main program }
int main (void) { uint8_t msg; uint32_t timeout = 0; uint32_t var; volatile uint16_t count; OSA_Init(); hardware_init(); dbg_uart_init(); configure_spi_pins(HW_SPI0); printf("dspi_edma_test_slave\r\n"); printf("\r\nDemo started...\r\n"); // Initialize configuration edma_init(); edma_dspi_rx_setup(kEDMAChannel2, (uint32_t)&g_slaveRxBuffer); dspi_slave_setup(HW_SPI0, SPI_BAUDRATE); printf("Press space bar to begin.\r\n"); msg = 'A'; while(msg != ' ') { msg = getchar(); } printf("\r\nDemo started...\r\n"); // Slave only have PCS0 PORT_HAL_SetMuxMode(PORTC_BASE, 0u, kPortMuxAlt7); // Enable eDMA channels requests to initiate DSPI transfers. EDMA_HAL_SetDmaRequestCmd(DMA_BASE, kEDMAChannel2, true); DSPI_HAL_StartTransfer(SPI0_BASE); // Waiting transfer complete printf("waiting transfer complete...\r\n"); while((bReceivedFlag == false) & (timeout < 50)) { OSA_TimeDelay(100); timeout++; } if(bReceivedFlag == false) { printf("No date received, please check connections\r\n"); } printf("received data:\r\n"); for(count = 0; count < TEST_DATA_LEN; count++) { var = g_slaveRxBuffer[count]; printf("%08X\t", (unsigned int)var); if((count + 1) % 4 == 0) { printf("\r\n"); } } printf("\r\nEnd of demo.\r\n"); }
/*! * @brief DSPI master Polling. * * Thid function uses DSPI master to send an array to slave * and receive the array back from slave, * thencompare whether the two buffers are the same. */ int main(void) { uint32_t i; uint32_t loopCount = 1; SPI_Type * dspiBaseAddr = (SPI_Type*)SPI0_BASE; uint32_t dspiSourceClock; uint32_t calculatedBaudRate; dspi_device_t masterDevice; dspi_command_config_t commandConfig = { .isChipSelectContinuous = false, .whichCtar = kDspiCtar0, .whichPcs = kDspiPcs0, .clearTransferCount = true, .isEndOfQueue = false }; // Init hardware hardware_init(); // Init OSA layer, used in DSPI_DRV_MasterTransferBlocking. OSA_Init(); // Call this function to initialize the console UART. This function // enables the use of STDIO functions (printf, scanf, etc.) dbg_uart_init(); // Print a note. printf("\r\n DSPI board to board polling example"); printf("\r\n This example run on instance 0 "); printf("\r\n Be sure DSPI0-DSPI0 are connected "); // Configure SPI pins. configure_spi_pins(DSPI_MASTER_INSTANCE); // Enable DSPI clock. CLOCK_SYS_EnableSpiClock(DSPI_MASTER_INSTANCE); // Initialize the DSPI module registers to default value, which disables the module DSPI_HAL_Init(dspiBaseAddr); // Set to master mode. DSPI_HAL_SetMasterSlaveMode(dspiBaseAddr, kDspiMaster); // Configure for continuous SCK operation DSPI_HAL_SetContinuousSckCmd(dspiBaseAddr, false); // Configure for peripheral chip select polarity DSPI_HAL_SetPcsPolarityMode(dspiBaseAddr, kDspiPcs0, kDspiPcs_ActiveLow); // Disable FIFO operation. DSPI_HAL_SetFifoCmd(dspiBaseAddr, false, false); // Initialize the configurable delays: PCS-to-SCK, prescaler = 0, scaler = 1 DSPI_HAL_SetDelay(dspiBaseAddr, kDspiCtar0, 0, 1, kDspiPcsToSck); // DSPI system enable DSPI_HAL_Enable(dspiBaseAddr); // Configure baudrate. masterDevice.dataBusConfig.bitsPerFrame = 8; masterDevice.dataBusConfig.clkPhase = kDspiClockPhase_FirstEdge; masterDevice.dataBusConfig.clkPolarity = kDspiClockPolarity_ActiveHigh; masterDevice.dataBusConfig.direction = kDspiMsbFirst; DSPI_HAL_SetDataFormat(dspiBaseAddr, kDspiCtar0, &masterDevice.dataBusConfig); // Get DSPI source clock. dspiSourceClock = CLOCK_SYS_GetSpiFreq(DSPI_MASTER_INSTANCE); calculatedBaudRate = DSPI_HAL_SetBaudRate(dspiBaseAddr, kDspiCtar0, TRANSFER_BAUDRATE, dspiSourceClock); printf("\r\n Transfer at baudrate %lu \r\n", calculatedBaudRate); while(1) { // Initialize the transmit buffer. for (i = 0; i < TRANSFER_SIZE; i++) { sendBuffer[i] = i + loopCount; } // Print out transmit buffer. printf("\r\n Master transmit:"); for (i = 0; i < TRANSFER_SIZE; i++) { // Print 16 numbers in a line. if ((i & 0x0F) == 0) { printf("\r\n "); } printf(" %02X", sendBuffer[i]); } // Reset the receive buffer. for (i = 0; i < TRANSFER_SIZE; i++) { receiveBuffer[i] = 0; } // Restart the transfer by stop then start again, this will clear out the shift register DSPI_HAL_StopTransfer(dspiBaseAddr); // Flush the FIFOs DSPI_HAL_SetFlushFifoCmd(dspiBaseAddr, true, true); // Clear status flags that may have been set from previous transfers. DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiTxComplete); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiEndOfQueue); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiTxFifoUnderflow); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiTxFifoFillRequest); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiRxFifoOverflow); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiRxFifoDrainRequest); // Clear the transfer count. DSPI_HAL_PresetTransferCount(dspiBaseAddr, 0); // Start the transfer process in the hardware DSPI_HAL_StartTransfer(dspiBaseAddr); // Send the data to slave. for (i = 0; i < TRANSFER_SIZE; i++) { // Write data to PUSHR DSPI_HAL_WriteDataMastermodeBlocking(dspiBaseAddr, &commandConfig, sendBuffer[i]); // Delay to wait slave is ready. OSA_TimeDelay(1); } // Delay to wait slave is ready. OSA_TimeDelay(10); // Restart the transfer by stop then start again, this will clear out the shift register DSPI_HAL_StopTransfer(dspiBaseAddr); // Flush the FIFOs DSPI_HAL_SetFlushFifoCmd(dspiBaseAddr, true, true); //Clear status flags that may have been set from previous transfers. DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiTxComplete); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiEndOfQueue); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiTxFifoUnderflow); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiTxFifoFillRequest); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiRxFifoOverflow); DSPI_HAL_ClearStatusFlag(dspiBaseAddr, kDspiRxFifoDrainRequest); // Clear the transfer count. DSPI_HAL_PresetTransferCount(dspiBaseAddr, 0); // Start the transfer process in the hardware DSPI_HAL_StartTransfer(dspiBaseAddr); // Receive the data from slave. for (i = 0; i < TRANSFER_SIZE; i++) { // Write command to PUSHR. DSPI_HAL_WriteDataMastermodeBlocking(dspiBaseAddr, &commandConfig, 0); // Check RFDR flag while (DSPI_HAL_GetStatusFlag(dspiBaseAddr, kDspiRxFifoDrainRequest)== false) {} // Read data from POPR receiveBuffer[i] = DSPI_HAL_ReadData(dspiBaseAddr); // Clear RFDR flag DSPI_HAL_ClearStatusFlag(dspiBaseAddr,kDspiRxFifoDrainRequest); // Delay to wait slave is ready. OSA_TimeDelay(1); } // Print out receive buffer. printf("\r\n Master receive:"); for (i = 0; i < TRANSFER_SIZE; i++) { // Print 16 numbers in a line. if ((i & 0x0F) == 0) { printf("\r\n "); } printf(" %02X", receiveBuffer[i]); } // Check receiveBuffer. for (i = 0; i < TRANSFER_SIZE; ++i) { if (receiveBuffer[i] != sendBuffer[i]) { // Master received incorrect. printf("\r\n ERROR: master received incorrect "); return -1; } } printf("\r\n DSPI Master Sends/ Recevies Successfully"); // Wait for press any key. printf("\r\n Press any key to run again"); getchar(); // Increase loop count to change transmit buffer. loopCount++; } }
/*! * @brief SPI master DMA non-blocking. * * Thid function uses SPI master to send an array to slave * and receive the array back from slave, * then compare whether the two buffers are the same. */ int main (void) { uint8_t loopCount = 0; uint32_t j; uint32_t failCount = 0; uint32_t calculatedBaudRate; spi_dma_master_state_t spiDmaMasterState; dma_state_t state; spi_dma_master_user_config_t userDmaConfig = { #if FSL_FEATURE_SPI_16BIT_TRANSFERS .bitCount = kSpi8BitMode, #endif .polarity = kSpiClockPolarity_ActiveHigh, .phase = kSpiClockPhase_FirstEdge, .direction = kSpiMsbFirst, .bitsPerSec = TRANSFER_BAUDRATE }; // init the hardware, this also sets up up the SPI pins for each specific SoC hardware_init(); // Init OSA layer. OSA_Init(); PRINTF("\r\nSPI board to board dma-non-blocking example"); PRINTF("\r\nThis example run on instance %d", (uint32_t)SPI_MASTER_INSTANCE); PRINTF("\r\nBe sure master's SPI%d and slave's SPI%d are connected\r\n", (uint32_t)SPI_MASTER_INSTANCE, (uint32_t)SPI_MASTER_INSTANCE); // Set up and init the master DMA_DRV_Init(&state); // Init the dspi module for eDMA operation SPI_DRV_DmaMasterInit(SPI_MASTER_INSTANCE, &spiDmaMasterState); SPI_DRV_DmaMasterConfigureBus(SPI_MASTER_INSTANCE, &userDmaConfig, &calculatedBaudRate); if (calculatedBaudRate > userDmaConfig.bitsPerSec) { PRINTF("\r\n**Something failed in the master bus config \r\n"); return -1; } else { PRINTF("\r\nBaud rate in Hz is: %d\r\n", calculatedBaudRate); } while(1) { // Initialize the source buffer for (j = 0; j < TRANSFER_SIZE; j++) { s_spiSourceBuffer[j] = j + loopCount; } // Reset the sink buffer for (j = 0; j < TRANSFER_SIZE; j++) { s_spiSinkBuffer[j] = 0; } // Start the transfer SPI_DRV_DmaMasterTransferBlocking(SPI_MASTER_INSTANCE, NULL, s_spiSourceBuffer, NULL, TRANSFER_SIZE, MASTER_TRANSFER_TIMEOUT); while (SPI_DRV_DmaMasterGetTransferStatus(SPI_MASTER_INSTANCE, NULL) == kStatus_SPI_Busy) { } // Delay sometime to wait slave receive and send back data OSA_TimeDelay(500U); //Receive data from slave SPI_DRV_DmaMasterTransfer(SPI_MASTER_INSTANCE, NULL, NULL, s_spiSinkBuffer, TRANSFER_SIZE); while (SPI_DRV_DmaMasterGetTransferStatus(SPI_MASTER_INSTANCE, NULL) == kStatus_SPI_Busy) { } // Verify the contents of the master sink buffer // refer to the slave driver for the expected data pattern failCount = 0; // reset failCount variable for (j = 0; j < TRANSFER_SIZE; j++) { if (s_spiSinkBuffer[j] != s_spiSourceBuffer[j]) { failCount++; } } // Print out transmit buffer. PRINTF("\r\nMaster transmit:"); for (j = 0; j < TRANSFER_SIZE; j++) { // Print 16 numbers in a line. if ((j & 0x0F) == 0) { PRINTF("\r\n "); } PRINTF(" %02X", s_spiSourceBuffer[j]); } // Print out receive buffer. PRINTF("\r\nMaster receive:"); for (j = 0; j < TRANSFER_SIZE; j++) { // Print 16 numbers in a line. if ((j & 0x0F) == 0) { PRINTF("\r\n "); } PRINTF(" %02X", s_spiSinkBuffer[j]); } if (failCount == 0) { PRINTF("\r\n Spi master transfer succeed! \r\n"); } else { PRINTF("\r\n **failures detected in Spi master transfer! \r\n"); } // Wait for press any key. PRINTF("\r\nPress any key to run again\r\n"); GETCHAR(); loopCount++; } }