/* I2Cx: I2C1 or I2C2 (Now it only support I2C1) pBuffer: Buffer point NumByteToRW: Number of bytes read/write memAddr: 1-2 bytes memory address SlaveAddress: device address MemType: 1 = memory address size 1 bytes, 2 = memory address size 2 bytes */ Status I2C_IORW(I2C_TypeDef* I2Cx, uint8_t* pBuffer, uint32_t NumByteToRW, uint16_t memAddr, uint8_t SlaveAddress, uint8_t MemType ) { uint32_t ev, Timeout=0xFFFF; uint16_t temp, temp2; static uint32_t call_cnt = 0, i; Status ret; ret = rt_mutex_take(i2c_mux, RT_WAITING_FOREVER ); if( ret == RT_EOK ) { ret = Success; DevAddr = SlaveAddress; BufSize = NumByteToRW; i2c_buf = pBuffer; memtype = MemType; MemAddr = (uint8_t*)&memAddr; I2CDirection = I2C_DIRECTION_TX; I2CMode = DMA; i2cStatus = S1; if( SlaveAddress & 0x01 ) { if( BufSize == 1 ) i2cFlag = I2C_READ_INTERRUPT; //I2C_READ_POLLING; else i2cFlag = I2C_READ_DMA; } else i2cFlag = I2C_WRITE; I2Cx->CR2 |= I2C_IT_ERR | I2C_IT_EVT;// | CR2_DMAEN_Set; I2Cx->CR1 |= CR1_START_Set; Timeout = 0xFFFF; if( rt_event_recv( &i2c_event, I2C_COMPLETE, RT_EVENT_FLAG_AND | RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, &ev ) != RT_EOK ) {ret = Error; goto i2cError;} if( i2cFlag == I2C_READ_POLLING ) { while ((I2Cx->SR1&0x0001) != 0x0001) if (Timeout-- == 0) {ret = Error; goto i2cError;} Timeout = 0xFFFF; I2Cx->DR = DevAddr; /* Wait until ADDR is set: EV6 */ while ((I2Cx->SR1&0x0002) != 0x0002) { if (Timeout-- == 0){ret = Error; goto i2cError;} } /* Clear ACK bit */ I2Cx->CR1 &= CR1_ACK_Reset; /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 software sequence must complete before the current byte end of transfer */ __disable_irq(); /* Clear ADDR flag */ temp = I2Cx->SR2; /* Program the STOP */ I2Cx->CR1 |= CR1_STOP_Set; /* Re-enable IRQs */ __enable_irq(); /* Wait until a data is received in DR register (RXNE = 1) EV7 */ while ((I2Cx->SR1 & 0x00040) != 0x000040)if (Timeout-- == 0){ret = Error; goto i2cError;} /* Read the data */ *i2c_buf = I2Cx->DR; /* Make sure that the STOP bit is cleared by Hardware before CR1 write access */ while ((I2Cx->CR1&0x200) == 0x200)if (Timeout-- == 0){ret = Error; goto i2cError;} /* Enable Acknowledgement to be ready for another reception */ I2Cx->CR1 |= CR1_ACK_Set; } else { while ((I2Cx->CR1&0x200) == 0x200) { if (Timeout-- == 0) {ret = Error; break;} } if( i2cFlag == I2C_READ_INTERRUPT ) I2Cx->CR1 |= CR1_ACK_Set; } i2cError: if( ret == Error ) { /* TODO: i2c error handler */ /* Need check i2cErrorNo and Reset I2C bus */ } I2Cx->CR2 &= ~CR2_FREQ_Reset; //dump_i2c_register(I2C1); rt_mutex_release(i2c_mux); return ret; } else return Error; }
/** * \brief SAMD21 SAM-BA Main loop. * \return Unused (ANSI-C compatibility). */ int main(void) { #if SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY || SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES P_USB_CDC pCdc; #endif DEBUG_PIN_HIGH; /* Jump in application if condition is satisfied */ check_start_application(); /* We have determined we should stay in the monitor. */ /* System initialization */ board_init(); __enable_irq(); #if SAM_BA_INTERFACE == SAM_BA_UART_ONLY || SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES /* UART is enabled in all cases */ serial_open(); #endif #if SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY || SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES pCdc = usb_init(); #endif DEBUG_PIN_LOW; /* Initialize LEDs */ LED_init(); LEDRX_init(); LEDRX_off(); LEDTX_init(); LEDTX_off(); /* Start the sys tick (1 ms) */ SysTick_Config(1000); /* Wait for a complete enum on usb or a '#' char on serial line */ while (1) { #if SAM_BA_INTERFACE == SAM_BA_USBCDC_ONLY || SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES if (pCdc->IsConfigured(pCdc) != 0) { main_b_cdc_enable = true; } /* Check if a USB enumeration has succeeded and if comm port has been opened */ if (main_b_cdc_enable) { sam_ba_monitor_init(SAM_BA_INTERFACE_USBCDC); /* SAM-BA on USB loop */ while( 1 ) { sam_ba_monitor_run(); } } #endif #if SAM_BA_INTERFACE == SAM_BA_UART_ONLY || SAM_BA_INTERFACE == SAM_BA_BOTH_INTERFACES /* Check if a '#' has been received */ if (!main_b_cdc_enable && serial_sharp_received()) { sam_ba_monitor_init(SAM_BA_INTERFACE_USART); /* SAM-BA on Serial loop */ while(1) { sam_ba_monitor_run(); } } #endif } }
void jshInterruptOn() { __enable_irq(); // *** This wont be good with SoftDevice! }
static void USER_FUNC lum_enableAllIrq(void) { hfthread_resume_all(); __enable_irq(); }
/******************************************************************************* * Disable Driver *******************************************************************************/ void SnoozeCompare::disableDriver( void ) { if ( mode == RUN_LP ) { return; } if ( mode == VLPW || mode == VLPS ) { IRQ_NUMBER_t IRQ_CMP; switch (pin) { case 11: IRQ_CMP = IRQ_CMP0; break; #if defined(KINETISK) case 9: IRQ_CMP = IRQ_CMP1; break; case 4: IRQ_CMP = IRQ_CMP2; break; #endif default: IRQ_CMP = IRQ_CMP; return; } if ( return_isr_enabled == 0 ) NVIC_DISABLE_IRQ( IRQ_CMP ); NVIC_SET_PRIORITY( IRQ_CMP, return_priority ); __disable_irq( ); attachInterruptVector( IRQ_CMP, return_cmp_irq );// return prev interrupt __enable_irq( ); } if ( pin == 11 ) { CORE_PIN11_CONFIG = return_core_pin_config[0]; } else if ( pin == 4 ) { #if defined(KINETISK) CORE_PIN4_CONFIG = return_core_pin_config[1]; #else return; #endif } else if ( pin == 9 ) { #if defined(KINETISK) CORE_PIN9_CONFIG = return_core_pin_config[2]; #else return; #endif } #if defined(__MKL26Z64__) || defined(__MK66FX1M0__) LPTMR0_PSR = PSR; LPTMR0_CMR = CMR; LPTMR0_CSR = CSR; if ( !SIM_SCGC5_clock_active ) SIM_SCGC5 &= ~SIM_SCGC5_LPTIMER; #endif *cmpx_cr0 = CR0; *cmpx_cr1 = CR1; *cmpx_scr = SCR; *cmpx_fpr = FPR; *cmpx_muxcr = MUXCR; *cmpx_daccr = DACCR; if ( !SIM_SCGC4_clock_active ) SIM_SCGC4 &= ~SIM_SCGC4_CMP; }
int main(void) { volatile boolean_T runModel = 1; float modelBaseRate = 0.01; float systemClock = 168; #ifndef USE_RTX __disable_irq(); #endif ; stm32f4xx_init_board(); SystemCoreClockUpdate(); bootloaderInit(); rtmSetErrorStatus(BeschleunigungsAuswertung_M, 0); /* initialize external mode */ rtParseArgsForExtMode(0, NULL); BeschleunigungsAuswertung_initialize(); __enable_irq(); /* External mode */ rtSetTFinalForExtMode(&rtmGetTFinal(BeschleunigungsAuswertung_M)); rtExtModeCheckInit(1); { boolean_T rtmStopReq = false; rtExtModeWaitForStartPkt(BeschleunigungsAuswertung_M->extModeInfo, 1, &rtmStopReq); if (rtmStopReq) { rtmSetStopRequested(BeschleunigungsAuswertung_M, true); } } rtERTExtModeStartMsg(); __disable_irq(); ARMCM_SysTick_Config(modelBaseRate); runModel = (rtmGetErrorStatus(BeschleunigungsAuswertung_M) == (NULL)) && !rtmGetStopRequested(BeschleunigungsAuswertung_M); __enable_irq(); __enable_irq(); while (runModel) { /* External mode */ { boolean_T rtmStopReq = false; rtExtModeOneStep(BeschleunigungsAuswertung_M->extModeInfo, 1, &rtmStopReq); if (rtmStopReq) { rtmSetStopRequested(BeschleunigungsAuswertung_M, true); } } runModel = (rtmGetErrorStatus(BeschleunigungsAuswertung_M) == (NULL)) && !rtmGetStopRequested(BeschleunigungsAuswertung_M); } rtExtModeShutdown(1); #ifndef USE_RTX (void)systemClock; #endif ; /* Disable rt_OneStep() here */ /* Terminate model */ BeschleunigungsAuswertung_terminate(); __disable_irq(); return 0; }
__weak void vPortSuppressTicksAndSleep( portTickType xExpectedIdleTime ) { unsigned long ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements; portTickType xModifiableIdleTime; /* Make sure the SysTick reload value does not overflow the counter. */ if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks ) { xExpectedIdleTime = xMaximumPossibleSuppressedTicks; } /* Stop the SysTick momentarily. The time the SysTick is stopped for is accounted for as best it can be, but using the tickless mode will inevitably result in some tiny drift of the time maintained by the kernel with respect to calendar time. */ portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT; /* Calculate the reload value required to wait xExpectedIdleTime tick periods. -1 is used because this code will execute part way through one of the tick periods. */ ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) ); if( ulReloadValue > ulStoppedTimerCompensation ) { ulReloadValue -= ulStoppedTimerCompensation; } /* Enter a critical section but don't use the taskENTER_CRITICAL() method as that will mask interrupts that should exit sleep mode. */ __disable_irq(); /* If a context switch is pending or a task is waiting for the scheduler to be unsuspended then abandon the low power entry. */ if( eTaskConfirmSleepModeStatus() == eAbortSleep ) { /* Restart SysTick. */ portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT; /* Re-enable interrupts - see comments above __disable_irq() call above. */ __enable_irq(); } else { /* Set the new reload value. */ portNVIC_SYSTICK_LOAD_REG = ulReloadValue; /* Clear the SysTick count flag and set the count value back to zero. */ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; /* Restart SysTick. */ portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT; /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can set its parameter to 0 to indicate that its implementation contains its own wait for interrupt or wait for event instruction, and so wfi should not be executed again. However, the original expected idle time variable must remain unmodified, so a copy is taken. */ xModifiableIdleTime = xExpectedIdleTime; configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); if( xModifiableIdleTime > 0 ) { __dsb( portSY_FULL_READ_WRITE ); __wfi(); __isb( portSY_FULL_READ_WRITE ); } configPOST_SLEEP_PROCESSING( xExpectedIdleTime ); /* Stop SysTick. Again, the time the SysTick is stopped for is accounted for as best it can be, but using the tickless mode will inevitably result in some tiny drift of the time maintained by the kernel with respect to calendar time. */ portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT; /* Re-enable interrupts - see comments above __disable_irq() call above. */ __enable_irq(); if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 ) { /* The tick interrupt has already executed, and the SysTick count reloaded with ulReloadValue. Reset the portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick period. */ portNVIC_SYSTICK_LOAD_REG = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG ); /* The tick interrupt handler will already have pended the tick processing in the kernel. As the pending tick will be processed as soon as this function exits, the tick value maintained by the tick is stepped forward by one less than the time spent waiting. */ ulCompleteTickPeriods = xExpectedIdleTime - 1UL; } else { /* Something other than the tick interrupt ended the sleep. Work out how long the sleep lasted rounded to complete tick periods (not the ulReload value which accounted for part ticks). */ ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG; /* How many complete tick periods passed while the processor was waiting? */ ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick; /* The reload value is set to whatever fraction of a single tick period remains. */ portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1 ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements; } /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again, then set portNVIC_SYSTICK_LOAD_REG back to its standard value. The critical section is used to ensure the tick interrupt can only execute once in the case that the reload register is near zero. */ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; portENTER_CRITICAL(); { portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT; vTaskStepTick( ulCompleteTickPeriods ); portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; } portEXIT_CRITICAL(); } }
/************************************************************************************//** ** \brief Enables the generation IRQ interrupts. Typically called once during ** software startup after completion of the initialization. ** \return none. ** ****************************************************************************************/ void IrqInterruptEnable(void) { __enable_irq(); }
// See bl_shutdown_cleanup.h for documentation of this function. void shutdown_cleanup(shutdown_type_t shutdown) { #if !defined(BOOTLOADER_HOST) if (shutdown != kShutdownType_Reset) { // Clear (flush) the flash cache. flash_cache_clear(NULL); } if (shutdown != kShutdownType_Cleanup) { // Shutdown all peripherals because they could be active uint32_t i; for (i = 0; g_peripherals[i].typeMask != 0; i++) { if (g_peripherals[i].controlInterface->shutdown) { g_peripherals[i].controlInterface->shutdown(&g_peripherals[i]); } } } // If we are permanently exiting the bootloader, there are a few extra things to do. if (shutdown == kShutdownType_Shutdown) { // Turn off global interrupt lock_acquire(); // Shutdown microseconds driver. microseconds_shutdown(); #if defined(RCM_FM) // Disable force ROM. RCM_BWR_FM_FORCEROM(RCM, 0); // Clear status register (bits are w1c). RCM_BWR_MR_BOOTROM(RCM, 3); #endif // defined(RCM_FM) init_interrupts(); // Set the VTOR to default. SCB->VTOR = kDefaultVectorTableAddress; // Restore clock to default before leaving bootloader. configure_clocks(kClockOption_ExitBootloader); // De-initialize hardware such as disabling port clock gate deinit_hardware(); // Restore global interrupt. __enable_irq(); #if BL_FEATURE_BYPASS_WATCHDOG // De-initialize watchdog bootloader_watchdog_deinit(); #endif // BL_FEATURE_BYPASS_WATCHDOG } // Memory barriers for good measure. __ISB(); __DSB(); #endif }
/** * Attempt to allocate a given amount of memory from a given heap area. * * @param size The amount of memory, in bytes, to allocate. * @param heap The heap to allocate memory from. * * @return A pointer to the allocated memory, or NULL if insufficient memory is available. */ void *microbit_malloc(size_t size, HeapDefinition &heap) { uint32_t blockSize = 0; uint32_t blocksNeeded = size % MICROBIT_HEAP_BLOCK_SIZE == 0 ? size / MICROBIT_HEAP_BLOCK_SIZE : size / MICROBIT_HEAP_BLOCK_SIZE + 1; uint32_t *block; uint32_t *next; if (size <= 0) return NULL; // Account for the index block; blocksNeeded++; // Disable IRQ temporarily to ensure no race conditions! __disable_irq(); // We implement a first fit algorithm with cache to handle rapid churn... // We also defragment free blocks as we search, to optimise this and future searches. block = heap.heap_start; while (block < heap.heap_end) { // If the block is used, then keep looking. if(!(*block & MICROBIT_HEAP_BLOCK_FREE)) { block += *block; continue; } blockSize = *block & ~MICROBIT_HEAP_BLOCK_FREE; // We have a free block. Let's see if the subsequent ones are too. If so, we can merge... next = block + blockSize; while (*next & MICROBIT_HEAP_BLOCK_FREE) { if (next >= heap.heap_end) break; // We can merge! blockSize += (*next & ~MICROBIT_HEAP_BLOCK_FREE); *block = blockSize | MICROBIT_HEAP_BLOCK_FREE; next = block + blockSize; } // We have a free block. Let's see if it's big enough. // If so, we have a winner. if (blockSize >= blocksNeeded) break; // Otherwise, keep looking... block += blockSize; } // We're full! if (block >= heap.heap_end) { __enable_irq(); return NULL; } // If we're at the end of memory or have very near match then mark the whole segment as in use. if (blockSize <= blocksNeeded+1 || block+blocksNeeded+1 >= heap.heap_end) { // Just mark the whole block as used. *block &= ~MICROBIT_HEAP_BLOCK_FREE; } else { // We need to split the block. uint32_t *splitBlock = block + blocksNeeded; *splitBlock = blockSize - blocksNeeded; *splitBlock |= MICROBIT_HEAP_BLOCK_FREE; *block = blocksNeeded; } // Enable Interrupts __enable_irq(); return block+1; }
/* May require the use of a ticker.attach in order to update the snake every * x seconds. <http://mbed.org/handbook/Ticker> */ void moveSnake(void) { /* * NOTE: This is part of an ISR called by the Ticker * So no printf, limited use of malloc. * If issues occur, split up function */ /* TODO: test mbed ISR, determine how much memory allocation, * max time for ISR, etc * REMOVE PRINTF ONCE MIGRATION OCCURS */ LLRoot * master = &Snake; LLNode * tmp; char sHead_x, sHead_y, sHead_z; char apple_x, apple_y, apple_z; signed char XDIR, YDIR, ZDIR; char count; if(master == NULL) return; moveFlag = 1; errcode = 0; /* Careful usage required, stale data can occur with these variables */ sHead_x = master->head->x; sHead_y = master->head->y; sHead_z = master->head->z; apple_x = master->fruit_x; apple_y = master->fruit_y; apple_z = master->fruit_z; XDIR = YDIR = ZDIR = 0; switch(master->direction) { case XPOS: XDIR = 1; break; case XNEG: XDIR = -1; break; case YPOS: YDIR = 1; break; case YNEG: YDIR = -1; break; case ZPOS: ZDIR = 1; break; case ZNEG: ZDIR = -1; break; default: break; } /* Update snake nodes */ __disable_irq(); addToHeadLL(master, sHead_x + XDIR, sHead_y + YDIR, sHead_z + ZDIR); __enable_irq(); // BEAMMEUPSCOTTY myCube.plotPoint(sHead_x + XDIR, sHead_y + YDIR, sHead_z + ZDIR); if(LLDEBUG) printf("debug: adding [%d %d %d]\r\n", sHead_x + XDIR, sHead_y + YDIR, sHead_z + ZDIR); /* Boundary/Self checking */ count = 0; tmp = master->head; while(tmp != NULL) { ++count; /* Check head coordinates against all other nodes */ if(count > 1) { if((master->head->x == tmp->x) && (master->head->y == tmp->y) && (master->head->z == tmp->z)) { if(LLDEBUG) printf("debug: conflict with snake head: [%d %d %d] ... resetting game\r\n", master->head->x, master->head->y, master->head->z); resetSnake(master); reset = 1; errcode = 1; break; } } // TODO: flash cube face on wall hit // in if statements if(tmp->x > BOUNDARY) { resetSnake(master); reset = 1; errcode = 3; // TODO: light right wall break; } if(tmp->x < 0) { resetSnake(master); reset = 1; errcode = 3; // TODO: light left wall break; } if(tmp->y > BOUNDARY) { resetSnake(master); reset = 1; errcode = 3; // TODO: light back wall break; } if(tmp->y < 0) { resetSnake(master); reset = 1; errcode = 3; // TODO: light front wall break; } if(tmp->z > BOUNDARY) { resetSnake(master); reset = 1; errcode = 3; // TODO: light top wall break; } if(tmp->z < 0) { resetSnake(master); reset = 1; errcode = 3; // TODO: light bottom wall break; } tmp = tmp->next; } //master->length = count - 1; if(reset) { reset = 0; return; } /* Fruit detection */ if((sHead_x == apple_x) && (sHead_y == apple_y) && (sHead_z == apple_z)) { generateFruit(master); errcode = 2; if(LLDEBUG) printf("debug: keeping tail [%d %d %d]\r\n", master->tail->x, master->tail->y, master->tail->z); }else{ /* If we detect fruit, there is no need to remove the tail node. * Otherwise we can remove it to produce the snake movement */ // BEAMMEUPSCOTTY myCube.clearPoint(master->tail->x, master->tail->y, master->tail->z); if(LLDEBUG) printf("debug: removing [%d %d %d] because no fruit detected\r\n", master->tail->x, master->tail->y, master->tail->z); __disable_irq(); removeTailLL(master); __enable_irq(); } if(LLDEBUG) printListLL(master); /* Display LL header and node data */ }
int main(void) { /*Variable Declarations*/ uint8_t c; uint16_t size = 0; char ACK[7]="ACK\n"; char NACK[7]="NACK\n"; unsigned char status = 0; /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, Flash preread and Buffer caches - Systick timer is configured by default as source of time base, but user can eventually implement his proper time base source (a general purpose timer for example or other time source), keeping in mind that Time base duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and handled in milliseconds basis. - Low Level Initialization */ HAL_Init(); /* Configure the system clock to 168 MHz */ SystemClock_Config(); /* Add your application code here */ printf("\nAll Systems Initialized!"); printf("\n...Running Host Application Code...\n"); BSP_PB_Init(BUTTON_KEY,BUTTON_MODE_EXTI); /* Configure LED3, LED4, LED5 and LED6 */ BSP_LED_Init(LED3); BSP_LED_Init(LED4); //Line used for enabling Gating Board 2 BSP_LED_Init(LED5); //Line used for enabling Gating Board 1 BSP_LED_Init(LED6); /*Configure GPIO pin : PB11 for I/O Update*/ __HAL_RCC_GPIOB_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_11; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLDOWN; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pin : PD8 for Slave Select*/ GPIO_InitStruct.Pin = GPIO_PIN_8; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /*Configure GPIO pin : PD9 for Master Reset*/ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLDOWN; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /*Configure GPIO pin : PA2 for External Interrupts from ILLUM_EN*/ GPIO_InitStruct.Pin = GPIO_PIN_2; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING; GPIO_InitStruct.Pull = GPIO_PULLDOWN; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* Set the SPI parameters */ SpiHandle.Instance = SPI2; SpiHandle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; SpiHandle.Init.Direction = SPI_DIRECTION_1LINE; SpiHandle.Init.CLKPhase = SPI_PHASE_2EDGE; SpiHandle.Init.CLKPolarity = SPI_POLARITY_HIGH; SpiHandle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; SpiHandle.Init.CRCPolynomial = 7; SpiHandle.Init.DataSize = SPI_DATASIZE_8BIT; SpiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB; SpiHandle.Init.NSS = SPI_NSS_SOFT; SpiHandle.Init.TIMode = SPI_TIMODE_DISABLE; SpiHandle.Init.Mode = SPI_MODE_MASTER; //Initialize DDS for Host-Control initDDS(); resetphase(); modulation_off(); ioupdate(); printf("\nDDS Initialized for Host-Control."); printf("\nDDS Channel Setup Complete"); //Initialize Timer for generating sync pulse and exposure counting initializesync(); inituscounter(); printf("\nSync Pulse Initialized"); /* Initialize USB VCP */ TM_USB_VCP_Init(); printf("\nUSB Communication Setup Complete - Host Ready!"); ////This Block makes the Host respond to ILLUM_EN /* Enable and set External Interrupt to the highest priority */ HAL_NVIC_SetPriority(EXTI2_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTI2_IRQn); ////It should come at the end of all critical initialization //Start Pulsing VD_IN to start capture of frames //startsyncpulse(); /* Infinite loop */ while (1) { /* USB configured OK, drivers OK */ if (TM_USB_VCP_GetStatus() == TM_USB_VCP_CONNECTED) { BSP_LED_On(LED3); //Status - All Good! //Only process USB when modulation not in progress if (modulation_state==0){ /* If something arrived at VCP */ if(TM_USB_VCP_Getc(&c)==TM_USB_VCP_DATA_OK){ /* Return data back */ if (c=='M'){ //Add interrupt guard __disable_irq(); printf("\n"); //Take 51 Bytes in after receiving M size = 0; while((TM_USB_VCP_Getc(&cmd[size]) == TM_USB_VCP_DATA_OK)&&(size < commandsize)) { printf("%04x ",cmd[size]); size++; } printf("%d",size); status = parse_usb(cmd,size); //Block checks is the parsing went correct if (status==1){ TM_USB_VCP_Puts(ACK); BSP_LED_On(LED6); } else{ TM_USB_VCP_Puts(NACK); BSP_LED_Off(LED6); } } else{ BSP_LED_Off(LED6); TM_USB_VCP_Puts(NACK); } __enable_irq(); }} } else { /* USB not OK */ BSP_LED_Off(LED3); } } }
bool spi_stack_master_transceive(void) { uint8_t master_checksum = 0; uint8_t slave_checksum = 0; uint8_t send_length = spi_stack_buffer_size_send; volatile uint8_t dummy = 0; __disable_irq(); SPI->SPI_SR; SPI->SPI_RDR; uint16_t timeout = SPI_STACK_MASTER_TIMEOUT; // Sync with slave while(dummy != 0xFF && timeout != 0) { while((SPI->SPI_SR & SPI_SR_TDRE) == 0); SPI->SPI_TDR = 0xFF; while((SPI->SPI_SR & SPI_SR_RDRF) == 0); dummy = SPI->SPI_RDR; timeout--; } if(timeout == 0) { logspise("Timeout, did not receive 0xFF from Slave\n\r"); __enable_irq(); return false; } // Write length while((SPI->SPI_SR & SPI_SR_TDRE) == 0); SPI->SPI_TDR = send_length; PEARSON(master_checksum, send_length); // Write first byte while((SPI->SPI_SR & SPI_SR_TDRE) == 0); SPI->SPI_TDR = spi_stack_buffer_send[0]; PEARSON(master_checksum, spi_stack_buffer_send[0]); // Read length while((SPI->SPI_SR & SPI_SR_RDRF) == 0); uint8_t slave_length = SPI->SPI_RDR; PEARSON(slave_checksum, slave_length); // If master and slave length are 0, stop communication if(slave_length == 0 && send_length == 0) { // Read dummy while((SPI->SPI_SR & SPI_SR_RDRF) == 0); dummy = SPI->SPI_RDR; __enable_irq(); return true; } // Length to transceive is maximum of slave and master length uint8_t max_length = MIN(MAX(send_length, slave_length), SPI_STACK_BUFFER_SIZE); // Exchange data for(uint8_t i = 1; i < max_length; i++) { // Write while((SPI->SPI_SR & SPI_SR_TDRE) == 0); SPI->SPI_TDR = spi_stack_buffer_send[i]; PEARSON(master_checksum, spi_stack_buffer_send[i]); // Read while((SPI->SPI_SR & SPI_SR_RDRF) == 0); spi_stack_buffer_recv[i-1] = SPI->SPI_RDR; PEARSON(slave_checksum, spi_stack_buffer_recv[i-1]); } // Write CRC while((SPI->SPI_SR & SPI_SR_TDRE) == 0); SPI->SPI_TDR = master_checksum; // Read last data byte while((SPI->SPI_SR & SPI_SR_RDRF) == 0); spi_stack_buffer_recv[max_length-1] = SPI->SPI_RDR; PEARSON(slave_checksum, spi_stack_buffer_recv[max_length-1]); // Read CRC while((SPI->SPI_SR & SPI_SR_RDRF) == 0); uint8_t crc = SPI->SPI_RDR; // Is CRC correct? uint8_t master_ack = crc == slave_checksum; __NOP(); __NOP(); __NOP(); // Write ACK/NACK while((SPI->SPI_SR & SPI_SR_TDRE) == 0); SPI->SPI_TDR = master_ack; // Read ACK/NACK while((SPI->SPI_SR & SPI_SR_RDRF) == 0); uint8_t slave_ack = SPI->SPI_RDR; // If everything is OK, set sizes accordingly if(slave_ack == 1 && master_ack == 1) { spi_stack_buffer_size_recv = slave_length; if(send_length != 0) { spi_stack_buffer_size_send = 0; } } else { if(!master_ack) { logspisw("Checksum: Master(%d) != Slave(%d)\n\r", crc, slave_checksum); } if(!slave_ack) { logspisw("Checksum: Received NACK from Slave\n\r"); } __enable_irq(); return false; } __enable_irq(); return true; }
void dmxl_tick() { volatile uint32_t t = systime_usecs(); bool start_poll = false; if (t - g_dmxl_last_poll_time > DMXL_POLL_INTERVAL_USEC) { //start_poll = true; //printf("%d dmxl poll\r\n", (int)SYSTIME); if (g_dmxl_last_poll_time) g_dmxl_last_poll_time += DMXL_POLL_INTERVAL_USEC; else g_dmxl_last_poll_time = t; } // process the rx ring dmxl_chain_t *c = &g_dmxl_chain; while (c->rx_rpos != c->rx_wpos) { dmxl_process_byte(c, c->rxbuf[c->rx_rpos++]); __disable_irq(); if (c->rx_rpos >= DMXL_CHAIN_RXBUF_LEN) c->rx_rpos = 0; __enable_irq(); } // run the port state machine switch (c->port_state) { case DMXL_PORT_STATE_IDLE: if (start_poll) { USART1->CR1 &= ~USART_CR1_RE; c->port_state = DMXL_PORT_STATE_POLL_TX_EN; c->polling_id = c->id_base; // start with first servo c->t_state = t; dmxl_stuff_poll_pkt(c); pin_set_output_state(GPIOB, DMXL_PORTB_TXE_PIN, 1); // assert TXE } break; case DMXL_PORT_STATE_POLL_TX_EN: if (t - c->t_state > 3) { //printf("starting dmxl poll\r\n"); c->tx_byte_idx = 0; USART1->DR = c->txbuf[0]; c->port_state = DMXL_PORT_STATE_POLL_TX; c->t_state = systime_usecs(); } break; case DMXL_PORT_STATE_POLL_TX: if ((USART1->SR & USART_SR_TXE) || systime_usecs() - c->t_state > 100) { if (c->tx_byte_idx >= c->tx_pkt_len - 1) { c->port_state = DMXL_PORT_STATE_POLL_TX_LAST; c->t_state = systime_usecs(); } else USART1->DR = c->txbuf[++c->tx_byte_idx]; } break; case DMXL_PORT_STATE_POLL_TX_LAST: if ((USART1->SR & USART_SR_TC) || systime_usecs() - c->t_state > 100) { c->port_state = DMXL_PORT_STATE_POLL_TX_DIS; c->t_state = systime_usecs(); c->parser_state = DMXL_PARSER_STATE_PREAMBLE_0; } break; case DMXL_PORT_STATE_POLL_TX_DIS: if (systime_usecs() - c->t_state > 2) { pin_set_output_state(GPIOB, DMXL_PORTB_TXE_PIN, 0); // de-assert TXE c->port_state = DMXL_PORT_STATE_POLL_RX; c->t_state = systime_usecs(); USART1->CR1 |= USART_CR1_RE; //printf("%d starting rx\r\n", (int)SYSTIME); } break; case DMXL_PORT_STATE_POLL_RX: if ((c->parser_state == DMXL_PARSER_STATE_DONE) || (systime_usecs() - c->t_state > 1000)) { // if we haven't heard from it by 1ms, we're toast anyway //printf("%d exiting rx\r\n", (int)SYSTIME); // we need to either start polling the next servo, or we're done. c->polling_id++; //printf("%d poll complete\r\n", (int)SYSTIME); if (c->polling_id > c->num_nodes) c->port_state = DMXL_PORT_STATE_IDLE; else c->port_state = DMXL_PORT_STATE_POLL_RX_WAIT; dmxl_stuff_poll_pkt(c); USART1->CR1 &= ~USART_CR1_RE; c->t_state = systime_usecs(); } break; case DMXL_PORT_STATE_POLL_RX_WAIT: if (systime_usecs() - c->t_state > 100) { c->port_state = DMXL_PORT_STATE_POLL_TX_EN; pin_set_output_state(GPIOB, DMXL_PORTB_TXE_PIN, 1); // assert TXE c->t_state = systime_usecs(); } break; default: g_dmxl_chain.port_state = DMXL_PORT_STATE_IDLE; } }
/************************************************************************************//** ** \brief Enables the generation IRQ interrupts. Typically called once during ** software startup after completion of the initialization. ** \return none. ** ****************************************************************************************/ void IrqInterruptEnable(void) { __enable_irq(); } /*** end of IrqInterruptEnable ***/
/*Returns the diff analog values of both sets of pins, measured at the same time by the two ADC modules. * It waits until the value is read and then returns the result as a struct Sync_result, * use Sync_result.result_adc0 and Sync_result.result_adc1. * If a comparison has been set up and fails, it will return ADC_ERROR_VALUE in both fields of the struct. */ ADC::Sync_result ADC::analogSynchronizedReadDifferential(uint8_t pin0P, uint8_t pin0N, uint8_t pin1P, uint8_t pin1N) { Sync_result res = {ADC_ERROR_VALUE, ADC_ERROR_VALUE};; // check pins if(!adc0->checkDifferentialPins(pin0P, pin0N)) { adc0->fail_flag |= ADC_ERROR_WRONG_PIN; return res; // all others are invalid } if(!adc1->checkDifferentialPins(pin1P, pin1N)) { adc1->fail_flag |= ADC_ERROR_WRONG_PIN; return res; // all others are invalid } // check if we are interrupting a measurement, store setting if so. // vars to save the current state of the ADC in case it's in use ADC_Module::ADC_Config old_adc0_config = {0}; uint8_t wasADC0InUse = adc0->isConverting(); // is the ADC running now? if(wasADC0InUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->saveConfig(&old_adc0_config); __enable_irq(); } ADC_Module::ADC_Config old_adc1_config = {0}; uint8_t wasADC1InUse = adc1->isConverting(); // is the ADC running now? if(wasADC1InUse) { // this means we're interrupting a conversion // save the current conversion config, the adc isr will restore the adc __disable_irq(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->saveConfig(&old_adc1_config); __enable_irq(); } // no continuous mode adc0->singleMode(); adc1->singleMode(); // start both measurements adc0->startDifferentialFast(pin0P, pin0N); adc1->startDifferentialFast(pin1P, pin1N); // wait for both ADCs to finish while( (adc0->isConverting()) || (adc1->isConverting()) ) { yield(); //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); } __disable_irq(); // make sure nothing interrupts this part if (adc0->isComplete()) { // conversion succeded res.result_adc0 = adc0->readSingle(); } else { // comparison was false adc0->fail_flag |= ADC_ERROR_COMPARISON; } if (adc1->isComplete()) { // conversion succeded res.result_adc1 = adc1->readSingle(); } else { // comparison was false adc1->fail_flag |= ADC_ERROR_COMPARISON; } __enable_irq(); // if we interrupted a conversion, set it again if (wasADC0InUse) { //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc0->loadConfig(&old_adc0_config); } if (wasADC1InUse) { //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); adc1->loadConfig(&old_adc1_config); } //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) ); return res; }
void SPI2_SetPacketSize(uint8_t psize) { __disable_irq(); _psize=psize; __enable_irq(); }
void AudioInputAnalog::update(void) { audio_block_t *new_left=NULL, *out_left=NULL; unsigned int dc, offset; int16_t s, *p, *end; // allocate new block (ok if NULL) new_left = allocate(); __disable_irq(); offset = block_offset; if (offset < AUDIO_BLOCK_SAMPLES) { // the DMA didn't fill a block if (new_left != NULL) { // but we allocated a block if (block_left == NULL) { // the DMA doesn't have any blocks to fill, so // give it the one we just allocated block_left = new_left; block_offset = 0; __enable_irq(); //Serial.println("fail1"); } else { // the DMA already has blocks, doesn't need this __enable_irq(); release(new_left); //Serial.print("fail2, offset="); //Serial.println(offset); } } else { // The DMA didn't fill a block, and we could not allocate // memory... the system is likely starving for memory! // Sadly, there's nothing we can do. __enable_irq(); //Serial.println("fail3"); } return; } // the DMA filled a block, so grab it and get the // new block to the DMA, as quickly as possible out_left = block_left; block_left = new_left; block_offset = 0; __enable_irq(); // find and subtract DC offset.... // TODO: this may not be correct, needs testing with more types of signals dc = dc_average; p = out_left->data; end = p + AUDIO_BLOCK_SAMPLES; do { s = (uint16_t)(*p) - dc; // TODO: should be saturating subtract *p++ = s; dc += s >> 13; // approx 5.38 Hz high pass filter } while (p < end); dc_average = dc; // then transmit the AC data transmit(out_left); release(out_left); }
/*********************************************************************//** * @brief c_entry: Main EMAC program body * @param[in] None * @return int **********************************************************************/ int c_entry (void) { /* Data Packet format */ EMAC_PACKETBUF_Type DataPacket; uint8_t *txptr; uint32_t i = 0; #if TX_ONLY uint32_t j; #endif #if BOUNCE_RX uint8_t *rxptr; #endif #if ENABLE_HASH uint8_t dstAddr[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; #endif NVIC_SetPriorityGrouping(4); //sets PRIGROUP to 3:2 (XXX:YY) //Init LED LED_Init(); /* Initialize debug via UART0 * – 115200bps * – 8 data bit * – No parity * – 1 stop bit * – No flow control */ debug_frmwrk_init(); // Init EMAC Usr_Init_Emac(); #if TX_ONLY #ifdef MCB_LPC_1768 EINT0_Init(); #elif defined(IAR_LPC_1768) EINT3_Init(); #endif txptr = (uint8_t *)gTxBuf; /* pre-format the transmit packets */ PacketGen(txptr); #endif #if ENABLE_HASH EMAC_SetHashFilter(dstAddr, ENABLE); #endif #if BOUNCE_RX /* copy just received data from RX buffer to TX buffer and send out */ txptr = (uint8_t *)gTxBuf; rxptr = (uint8_t *)gRxBuf; #endif #if ENABLE_WOL _DBG_("Enter Sleep mode now..."); /* * On default state, All Multicast frames, All Broadcast frames and Frame that matched * with station address (unicast) are accepted. * To make WoL is possible, enable Rx Magic Packet and RxFilter Enable WOL */ EMAC_SetFilterMode((EMAC_RFC_PFILT_WOL_EN | EMAC_RFC_MAGP_WOL_EN), ENABLE); for (i = 0; i < 5; i++){ LED_Blink(PD_LED_PIN); /* Indicating system is in power down now. */ } // Disable irq interrupt __disable_irq(); /* Currently, support Sleep mode */ /* enter sleep mode */ LPC_SC->PCON = 0x0; /* Sleep Mode*/ __WFI(); // CPU will be suspend here... /* From power down to WOL, the PLL needs to be reconfigured, otherwise, the CCLK will be generated from 4Mhz IRC instead of main OSC 12Mhz */ /* Initialize system clock */ SystemInit(); /* * Initialize debug via UART */ debug_frmwrk_init(); /* * Init LED */ LED_Init(); _DBG_("Wake up from sleep mode"); /* Calling EMACInit() is overkill which also initializes the PHY, the main reason to do that is to make sure the descriptors and descriptor status for both TX and RX are clean and ready to use. It won't go wrong. */ Usr_Init_Emac(); // Re-Enable irq interrupt __enable_irq(); #endif /* endif ENABLE_WOL */ #if BOUNCE_RX while( 1 ) { LED_Blink(BLINK_LED_PIN); if ( PacketReceived == TRUE ) { PacketReceived = FALSE; /* Reverse Source and Destination, then copy the body */ memcpy( (uint8_t *)txptr, (uint8_t *)(rxptr+6), 6); memcpy( (uint8_t *)(txptr+6), (uint8_t *)rxptr, 6); memcpy( (uint8_t *)(txptr+12), (uint8_t *)(rxptr+12), (ReceiveLength - 12)); _DBG_("Send packet"); DataPacket.pbDataBuf = (uint32_t *)txptr; DataPacket.ulDataLen = ReceiveLength; EMAC_WritePacketBuffer(&DataPacket); EMAC_UpdateTxProduceIndex(); } } #endif /* endif BOUNCE_RX */ #if TX_ONLY /* Transmit packets only */ while ( 1 ) { while (Pressed == RESET){ LED_Blink(BLINK_LED_PIN); } Pressed = RESET; txptr = (uint8_t *)gTxBuf; _DBG_("Send packet"); LED_Blink(TX_LED_PIN); DataPacket.pbDataBuf = (uint32_t *)txptr; // Note that there're 4-byte CRC added DataPacket.ulDataLen = TX_PACKET_SIZE + 4; EMAC_WritePacketBuffer(&DataPacket); EMAC_UpdateTxProduceIndex(); for ( j = 0; j < 0x200000; j++ ); /* delay */ } #endif /* endif TX_ONLY */ return 0; }
// restore interrupt enable state void leave_critical(bool enable) { if(enable) __enable_irq(); }
void DS1820main(void) { static u8 fistsech=0; s16 temp1,temp2; //u8 buff[16]; // u8 i,j,num=DS18B20_NUM; if(fistsech==0) { Delay_init(72);//72M Delay_ms(20); Init_DS18B20_IO(); #if 0 if(1==OWFirst()) //第一次搜索到ROM数据 { memcpy(&ID_Buff[0][0],GetRomAddr(),8);//复制ID数据到IDbuff for(temp1=1;temp1<DS18B20_NUM;temp1++) { if( OWSearch()==1) { memcpy(&ID_Buff[temp1][0],GetRomAddr(),8);//复制ID数据到IDbuff } else { break;//没有器件 } } } else{ return; } #endif temp[0]= '\t'; temp[1]='T'; temp[2]='i'; temp[3]='m'; temp[4]='e'; temp[5]=':'; temp[11]= '\t'; temp[12]='T'; temp[13]='e'; temp[14]='m'; temp[15]='p'; temp[16]=':'; temp[23]='\t'; temp[20]='.' ; temp[27]='.' ; temp[30]= '\t'; temp[31]= '\r'; temp[32]= '\n'; fistsech=1; } __disable_irq();// 相当于 CPSID I //读取2个指定ID的温度传感器数值 // tempA是在顶部没有划的,tempB顶部划了一下:-) temp1 = DS18B20_ReadDesignateTemper(ID_Buff[0]); __enable_irq();// 相当于 CPSIE I // temp2 = DS18B20_ReadDesignateTemper(ID_Buff[1]); if(temp1==0) return ; Temp_pid[0]=temp1; //用于PID计算 temp[6]=time_run/10000+0x30; temp[7]=time_run%10000/1000+0x30; temp[8]=time_run%10000%1000/100+0x30; temp[9]=time_run%10000%1000%100/10+0x30; temp[10]=time_run%10000%1000%100%10+0x30; temp[17]= temp1/10000+0x30; temp[18]= temp1%10000/1000+0x30; temp[19]= temp1%10000%1000/100+0x30; temp[21]= temp1%10000%1000%100/10+0x30; temp[22]= temp1%10000%1000%100%10+0x30; temp[24]=temp2/10000+0x30; temp[25]= temp2%10000/1000+0x30; temp[26]= temp2%10000%1000/100+0x30; temp[28]= temp2%10000%1000%100/10+0x30; temp[29]= temp2%10000%1000%100%10+0x30; temp[30] = temp1; temp[31] = temp2; }
void CEC_STANDBY(void) { uint32_t Index = 0U; uint32_t temp = 0U; TSB_WD_MOD_WDTE = 0U; TSB_WD->CR = 0x000000B1; SystemInit(); UART_Configuration(UART0); /*initial cec port */ TSB_PK->CR = 0x01U; TSB_PK->FR1 = 0x01U; TSB_PK->IE = 0x01U; /*initial cec frame data buffer */ CEC_RxFrame.Initiator = CEC_UNKNOWN; CEC_RxFrame.Destination = CEC_UNKNOWN; CEC_RxFrame.Opcode = 0xFFU; CEC_RxFrame.current_num = 0x0U; CEC_RxFrame.Max_num = 0x0U; CEC_RxFrame.current_state = DATA_INIT; for (Index = 0U; Index < 17U; Index++) { CEC_RxFrame.CEC_Data[Index] = 0xFFU; } CEC_RxFrameTmp = CEC_RxFrame; CEC_TxFrame = CEC_RxFrame; /*initial cec register */ CEC_Enable(); CEC_SWReset(); while (CEC_GetRxState() == ENABLE); while (CEC_GetTxState() == BUSY); CEC_DefaultConfig(); /*initial cec interupt */ __disable_irq(); TSB_CG->IMCGB = 0x00300000U; TSB_CG->IMCGD = 0x00000030U; TSB_CG->IMCGB = 0x00310000U; TSB_CG->IMCGD = 0x00000031U; TSB_CG->ICRCG = 0x06U; TSB_CG->ICRCG = 0x0cU; NVIC_EnableIRQ(INTCECRX_IRQn); NVIC_EnableIRQ(INTCECTX_IRQn); __enable_irq(); /*set logical address TV */ CEC_SetLogicalAddr(CEC_TV); /*Enable CEC reception */ CEC_SetRxCtrl(ENABLE); while (1) { /*Recieve new frame or not */ if (CEC_RxFrameTmp.current_state == DATA_END) { CEC_RxFrame = CEC_RxFrameTmp; CEC_RxFrameTmp.current_num = 0U; CEC_RxFrameTmp.current_state = DATA_INIT; temp = CEC_RxFrame.current_num; if (temp > 0U) { UART_Print(UART0, "CEC Message: "); for (Index = 0U; Index < temp; Index++) { UART_Print(UART0, "0x%2x " + CEC_RxFrame.CEC_Data[Index]); } UART_Print(UART0, "\n"); } for (Index = 0U; Index < 17U; Index++) { CEC_RxFrameTmp.CEC_Data[Index] = 0xFFU; } /*CEC message is "Active Source" */ if (CEC_RxFrame.CEC_Data[1] == 0x82U) { CEC_Send_Frame(CEC_TV, CEC_BROADCAST, 0x36U, 0U, CEC_RxFrame.CEC_Data); } } } }
/******************************************************************************* * Enable Driver *******************************************************************************/ void SnoozeCompare::enableDriver( void ) { if ( mode == RUN_LP ) { return; } if ( mode == VLPW || mode == VLPS ) { IRQ_NUMBER_t IRQ_CMP; switch (pin) { case 11: IRQ_CMP = IRQ_CMP0; break; #if defined(KINETISK) case 9: IRQ_CMP = IRQ_CMP1; break; case 4: IRQ_CMP = IRQ_CMP2; break; #endif default: IRQ_CMP = IRQ_CMP; return; } return_priority = NVIC_GET_PRIORITY( IRQ_CMP );//get current priority int priority = nvic_execution_priority( );// get current priority // if running from handler mode set priority higher than current handler priority = ( priority < 256 ) && ( ( priority - 16 ) > 0 ) ? priority - 16 : 128; NVIC_SET_PRIORITY( IRQ_CMP, priority );//set priority to new level __disable_irq( ); return_cmp_irq = _VectorsRam[IRQ_CMP+16];// save prev isr attachInterruptVector( IRQ_CMP, wakeupIsr ); __enable_irq( ); } if ( SIM_SCGC4 & SIM_SCGC4_CMP ) SIM_SCGC4_clock_active = true; else SIM_SCGC4 |= SIM_SCGC4_CMP; CR0 = *cmpx_cr0; CR1 = *cmpx_cr1; SCR = *cmpx_scr; FPR = *cmpx_fpr; MUXCR = *cmpx_muxcr; DACCR = *cmpx_daccr; uint8_t _pin = 0; *cmpx_cr0 = 0; *cmpx_cr1 = 0; *cmpx_scr = 0; #if defined(__MKL26Z64__) || defined(__MK66FX1M0__) if ( SIM_SCGC5 & SIM_SCGC5_LPTIMER ) SIM_SCGC5_clock_active = true; else SIM_SCGC5 |= SIM_SCGC5_LPTIMER; PSR = LPTMR0_PSR; CMR = LPTMR0_CMR; CSR = LPTMR0_CSR; #endif if ( pin == 11 ) { if ( mode >= LLS ) llwu_configure_modules_mask( LLWU_CMP0_MOD ); return_core_pin_config[0] = CORE_PIN11_CONFIG; CORE_PIN11_CONFIG = PORT_PCR_MUX( 0 ); _pin = 0x00; } else if ( pin == 4 ) { #if defined(KINETISK) if ( mode >= LLS ) llwu_configure_modules_mask( LLWU_CMP2_MOD ); return_core_pin_config[1] = CORE_PIN4_CONFIG; CORE_PIN4_CONFIG = PORT_PCR_MUX( 0 ); _pin = 0x01; #else return; #endif } else if ( pin == 9 ) { #if defined(KINETISK) if ( mode >= LLS ) llwu_configure_modules_mask( LLWU_CMP1_MOD ); return_core_pin_config[2] = CORE_PIN9_CONFIG; CORE_PIN9_CONFIG = PORT_PCR_MUX( 0 ); _pin = 0x01; #else return; #endif } // save if isr is already enabled and enable isr if not if ( mode == VLPW || mode == VLPS ) { IRQ_NUMBER_t IRQ_CMP; switch (pin) { case 11: IRQ_CMP = IRQ_CMP0; break; #if defined(KINETISK) case 9: IRQ_CMP = IRQ_CMP1; break; case 4: IRQ_CMP = IRQ_CMP2; break; #endif default: IRQ_CMP = IRQ_CMP; return; } return_isr_enabled = NVIC_IS_ENABLED( IRQ_CMP ); if ( return_isr_enabled == 0 ) NVIC_ENABLE_IRQ( IRQ_CMP ); } // setup compare *cmpx_cr0 = CMP_CR0_FILTER_CNT( 0x07 ); if ( type == CHANGE ) *cmpx_scr = CMP_SCR_CFF | CMP_SCR_CFR | CMP_SCR_IEF | CMP_SCR_IER; else if ( type == RISING || type == HIGH ) *cmpx_scr = CMP_SCR_CFF | CMP_SCR_CFR | CMP_SCR_IER; else if ( type == FALLING || type == LOW ) *cmpx_scr = CMP_SCR_CFF | CMP_SCR_CFR | CMP_SCR_IEF; else return; uint8_t tap = ( threshold_crossing/0.0515625 ) - 1; *cmpx_fpr = 0x00; *cmpx_muxcr = CMP_MUXCR_MSEL( 0x07 ) | CMP_MUXCR_PSEL( _pin ); *cmpx_daccr = CMP_DACCR_DACEN | CMP_DACCR_VRSEL | CMP_DACCR_VOSEL( tap ); #if defined(__MKL26Z64__) || defined(__MK66FX1M0__) // compare needs lptmr to operate in low power with LC, 3.6 *cmpx_cr1 = CMP_CR1_EN | CMP_CR1_TRIGM; SIM_SCGC5 |= SIM_SCGC5_LPTIMER; LPTMR0_CSR = 0; LPTMR0_PSR = LPTMR_PSR_PBYP | LPTMR_PSR_PCS( LPTMR_LPO );//LPO Clock LPTMR0_CMR = 1; LPTMR0_CSR = LPTMR_CSR_TEN | LPTMR_CSR_TCF; #else *cmpx_cr1 = CMP_CR1_EN; #endif }
/** * @brief Configures the NVIC interrupts. * @param None * @retval None */ void NVIC_Configuration(void) { //NVIC_InitTypeDef NVIC_InitStructure; #ifdef VECT_TAB_RAM /* Set the Vector Table base location at 0x20000000 */ NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0); #else /* VECT_TAB_FLASH */ /* Configure the preemption priority and subpriority: - 1 bits for pre-emption priority: possible value are 0 or 1 - 3 bits for subpriority: possible value are 0..7 - Lower values gives higher priority */ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); #if 0 /* Enable the WAKEUP_BUTTON_EXTI_IRQn Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = WAKEUP_BUTTON_EXTI_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = PreemptionPriorityValue; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable the KEY_BUTTON_EXTI_IRQn Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = KEY_BUTTON_EXTI_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #endif #if 0 /* Enable the USART1 Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQChannel; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable the USART2 Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQChannel; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #endif #if 0 /* Enable the TIM2 global Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQChannel; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable the TIM3 global Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQChannel; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #endif /* Set the Vector Table base location at 0x08000000 */ //NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0); /* Set the Vector Table base location at 0x08002000 -> USE AIP*/ // NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x2000); NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x6000); __enable_irq(); #endif }
~CriticalSectionLocker() { __enable_irq(); }
int i2c_init(i2c_t *i2c, i2c_mode_t mode, uint32_t speed) { i2c_config_t const * const conf = i2c->config; GPIO_InitTypeDef gpio_init_s; I2C_InitTypeDef i2c_init_s; NVIC_InitTypeDef nvic_init_s; __disable_irq(); if(i2c->mode != I2C_MODE_DISABLED) { __enable_irq(); return 1; } GPIO_StructInit(&gpio_init_s); I2C_StructInit(&i2c_init_s); // All I2C peripherals are on APB1 RCC_APB1PeriphClockCmd(conf->clock, ENABLE); // Reset RCC_APB1PeriphResetCmd(conf->clock, ENABLE); RCC_APB1PeriphResetCmd(conf->clock, DISABLE); //////////////////////////////////////////////////////////////////// // GPIO Config //////////////////////////////////////////////////////////////////// // Set alternate functions to use GPIO_PinAFConfig(conf->sda_gpio, conf->sda_pinsrc, conf->af); GPIO_PinAFConfig(conf->scl_gpio, conf->scl_pinsrc, conf->af); /* // Mode configuration gpio_init_s.GPIO_Mode = GPIO_Mode_IN; gpio_init_s.GPIO_Speed = GPIO_Speed_50MHz; gpio_init_s.GPIO_PuPd = GPIO_PuPd_NOPULL; gpio_init_s.GPIO_OType = GPIO_OType_OD; gpio_init_s.GPIO_Pin = conf->sda_pin; GPIO_Init(conf->sda_gpio, &gpio_init_s); gpio_init_s.GPIO_Pin = conf->scl_pin; GPIO_Init(conf->scl_gpio, &gpio_init_s); */ // Mode configuration gpio_init_s.GPIO_Mode = GPIO_Mode_AF; gpio_init_s.GPIO_Speed = GPIO_Speed_50MHz; gpio_init_s.GPIO_PuPd = GPIO_PuPd_UP; gpio_init_s.GPIO_OType = GPIO_OType_OD; // For some reason the order here matters and it really shouldn't gpio_init_s.GPIO_Pin = conf->scl_pin; GPIO_Init(conf->scl_gpio, &gpio_init_s); gpio_init_s.GPIO_Pin = conf->sda_pin; GPIO_Init(conf->sda_gpio, &gpio_init_s); //////////////////////////////////////////////////////////////////// // I2C Config //////////////////////////////////////////////////////////////////// i2c_init_s.I2C_Mode = I2C_Mode_I2C; i2c_init_s.I2C_DutyCycle = I2C_DutyCycle_2; i2c_init_s.I2C_ClockSpeed = 100000; i2c_init_s.I2C_OwnAddress1 = 0xA0; i2c_init_s.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; i2c_init_s.I2C_Ack = I2C_Ack_Enable; //////////////////////////////////////////////////////////////////// // Interrupt Config //////////////////////////////////////////////////////////////////// nvic_init_s.NVIC_IRQChannel = conf->irq_er; nvic_init_s.NVIC_IRQChannelSubPriority = 2; nvic_init_s.NVIC_IRQChannelPreemptionPriority = 2; nvic_init_s.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&nvic_init_s); nvic_init_s.NVIC_IRQChannel = conf->irq_ev; nvic_init_s.NVIC_IRQChannelSubPriority = 3; nvic_init_s.NVIC_IRQChannelPreemptionPriority = 3; nvic_init_s.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&nvic_init_s); I2C_ITConfig(i2c->i2c, I2C_IT_ERR, ENABLE); I2C_ITConfig(i2c->i2c, I2C_IT_BUF, ENABLE); I2C_ITConfig(i2c->i2c, I2C_IT_EVT, ENABLE); //////////////////////////////////////////////////////////////////// // Finalize //////////////////////////////////////////////////////////////////// I2C_Cmd(i2c->i2c, ENABLE); I2C_Init(i2c->i2c, &i2c_init_s); i2c->mode = mode; __enable_irq(); return 1; }
void event_timer_clear_flag(u32 id) { __disable_irq(); __event_timer_flag__[id] = 0; __enable_irq(); }
int main (void) { int i; /* Basic chip initialization is taken care of in SystemInit() called * from the startup code. SystemInit() and chip settings are defined * in the CMSIS system_<part family>.c file. */ SysTick->LOAD = (SystemCoreClock/100) -1; SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ while(1) { __disable_irq(); LPC_IOCON->R_PIO0_11 &= ~0x3E; LPC_IOCON->R_PIO0_11 |= 0x81; LPC_GPIO0->DIR = 0xBCE; // PIO0_0 - PIO0_11 as output (exclude reset, I2C, swdclk) LPC_GPIO0->MASKED_ACCESS[0xBCE] = ~0; // Drive the pins high LPC_SYSCON->STARTAPRP0 = 0; // falling edge LPC_SYSCON->STARTRSRP0CLR = LPC_SYSCON->STARTRSRP0CLR; // Clear all interrupts LPC_SYSCON->STARTERP0 = 0xBCE; // enable interrupts for(i=0;i<8;i++) { int irq; // The logic below converts our ordinal index 0-7 to an interrupt vector number. // For simplicity we skip vector 0 which is on PIO0_0 the reset pin, vectors 4,5 // which are I2C pins and need pullups, and vector 10 which is PIO0_10 the SWDCLK pin. irq = i + 1; if(irq >= 4) irq += 2; if(irq == 10) irq++; NVIC_EnableIRQ(irq); // Create priority levels for different interrupts. For the Cortex-M0, // there are priorities 0-3. On the Cortex-M3 parts like the LPC1343, // priorities can be from 0-7. priLUT[irq] = i%4; NVIC_SetPriority(irq, priLUT[irq]); } LPC_GPIO0->MASKED_ACCESS[0xBCE] = 0; // Drive pins low // Zero the data structure for(i=0;i<30;i++) { IR[i].VectorNumber = IR[i].IntClocks = 0; } IRIdx = 0; LPC_GPIO0->MASKED_ACCESS[0xBCE] = ~0; // Drive the pins high again __enable_irq(); // Wait 1 second for(i=0;i<100;i++) while(! (SysTick->CTRL&SysTick_CTRL_COUNTFLAG_Msk)); // Now print out the interrupt results debug_printf(" N: Vec Pri Pending Cycles\n"); for(i=0;i<IRIdx;i++) { debug_printf("%2d: %3d %3d %7x %d\n", i, IR[i].VectorNumber, priLUT[IR[i].VectorNumber], IR[i].Pending, IR[0].IntClocks - IR[i].IntClocks); } // Wait 5 seconds for(i=0;i<500;i++) while(! (SysTick->CTRL&SysTick_CTRL_COUNTFLAG_Msk)); } }
void HAL_enable_irq(int is) { if ((is & 1) == 0) { __enable_irq(); } }
void AudioInputAnalogStereo::update(void) { audio_block_t *new_left=NULL, *out_left=NULL; audio_block_t *new_right=NULL, *out_right=NULL; int32_t tmp; int16_t s, *p, *end; //Serial.println("update"); // allocate new block (ok if both NULL) new_left = allocate(); if (new_left == NULL) { new_right = NULL; } else { new_right = allocate(); if (new_right == NULL) { release(new_left); new_left = NULL; } } __disable_irq(); if (offset_left < AUDIO_BLOCK_SAMPLES || offset_right < AUDIO_BLOCK_SAMPLES) { // the DMA hasn't filled up both blocks if (block_left == NULL) { block_left = new_left; offset_left = 0; new_left = NULL; } if (block_right == NULL) { block_right = new_right; offset_right = 0; new_right = NULL; } __enable_irq(); if (new_left) release(new_left); if (new_right) release(new_right); return; } // the DMA filled blocks, so grab them and get the // new blocks to the DMA, as quickly as possible out_left = block_left; out_right = block_right; block_left = new_left; block_right = new_right; offset_left = 0; offset_right = 0; __enable_irq(); // // DC Offset Removal Filter // 1-pole digital high-pass filter implementation // y = a*(x[n] - x[n-1] + y[n-1]) // The coefficient "a" is as follows: // a = UNITY*e^(-2*pi*fc/fs) // fc = 2 @ fs = 44100 // // DC removal, LEFT p = out_left->data; end = p + AUDIO_BLOCK_SAMPLES; do { tmp = (uint16_t)(*p); tmp = ( ((int32_t) tmp) << 14); int32_t acc = hpf_y1[0] - hpf_x1[0]; acc += tmp; hpf_y1[0] = FRACMUL_SHL(acc, COEF_HPF_DCBLOCK, 1); hpf_x1[0] = tmp; s = signed_saturate_rshift(hpf_y1[0], 16, 14); *p++ = s; } while (p < end); // DC removal, RIGHT p = out_right->data; end = p + AUDIO_BLOCK_SAMPLES; do { tmp = (uint16_t)(*p); tmp = ( ((int32_t) tmp) << 14); int32_t acc = hpf_y1[1] - hpf_x1[1]; acc += tmp; hpf_y1[1]= FRACMUL_SHL(acc, COEF_HPF_DCBLOCK, 1); hpf_x1[1] = tmp; s = signed_saturate_rshift(hpf_y1[1], 16, 14); *p++ = s; } while (p < end); // then transmit the AC data transmit(out_left, 0); release(out_left); transmit(out_right, 1); release(out_right); }