MBED_WEAK void core_util_critical_section_enter(void) { bool interrupts_disabled = !core_util_are_interrupts_enabled(); __disable_irq(); /* Save the interrupt disabled state as it was prior to any nested critical section lock use */ if (!interrupt_enable_counter) { critical_interrupts_disabled = interrupts_disabled; } /* If the interrupt_enable_counter overflows or we are in a nested critical section and interrupts are enabled, then something has gone badly wrong thus assert an error. */ MBED_ASSERT(interrupt_enable_counter < UINT32_MAX); // FIXME #ifndef FEATURE_UVISOR if (interrupt_enable_counter > 0) { MBED_ASSERT(interrupts_disabled); } #else #warning "core_util_critical_section_enter needs fixing to work from unprivileged code" #endif /* FEATURE_UVISOR */ interrupt_enable_counter++; }
/** * @brief Fast program a 32 row double-word (64-bit) at a specified address. * @param Address: specifies the address to be programmed. * @param DataAddress: specifies the address where the data are stored. * @retval None */ static void FLASH_Program_Fast(uint32_t Address, uint32_t DataAddress) { uint8_t row_index = 32; __IO uint64_t *dest_addr = (__IO uint64_t*)Address; __IO uint64_t *src_addr = (__IO uint64_t*)DataAddress; /* Check the parameters */ assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); /* Set FSTPG bit */ SET_BIT(FLASH->CR, FLASH_CR_FSTPG); /* Disable interrupts to avoid any interruption during the loop */ __disable_irq(); /* Program the 32 double word */ do { *dest_addr++ = *src_addr++; } while (--row_index != 0); /* Re-enable the interrupts */ __enable_irq(); }
void set_interrupt_priorities(const int8_t prios[]) { uint32_t old_primask, iser; int i = 0; uint32_t prio = 0; /* * We shouldn't change the priority of an enabled interrupt. * 1. Globally disable interrupts, saving the global interrupts disable state. * 2. Explicitly disable all interrupts, saving the individual interrupt enable state. * 3. Set interrupt priorities. * 4. Restore individual interrupt enables. * 5. Restore global interrupt enable state. */ old_primask = __get_PRIMASK(); __disable_irq(); iser = NVIC->ISER[0]; NVIC->ICER[0] = iser; for (i = 0; prios[i] != PRIORITY_TABLE_END; ++i) { switch (prios[i]) { case PRIORITY_0: case PRIORITY_1: case PRIORITY_2: case PRIORITY_3: prio = prios[i] - PRIORITY_0; break; default: NVIC_SetPriority(prios[i], prio); break; } } NVIC->ISER[0] = iser; __set_PRIMASK(old_primask); }
/**@brief Function for application main entry. Does not return. */ int main(void) { utils_setup(); softdevice_setup(); ant_channel_rx_broadcast_setup(); // Main loop. for (;;) { #ifdef CPU_LOAD_TRACE // Disabling interrupts in this way is highly not recommended. It has an impact on the work // of the SoftDevice and is used only to show CPU load. __disable_irq(); LEDS_OFF(BSP_LED_0_MASK); __WFI(); LEDS_ON(BSP_LED_0_MASK); __enable_irq(); #else // Put CPU in sleep if possible. uint32_t err_code = sd_app_evt_wait(); APP_ERROR_CHECK(err_code); #endif // CPU_LOAD_TRACE } }
void attachInterrupt(uint8_t pin, void (*function)(void), int mode) { volatile uint32_t *config; uint32_t cfg, mask; if (pin >= CORE_NUM_DIGITAL) return; switch (mode) { case CHANGE: mask = 0x0B; break; case RISING: mask = 0x09; break; case FALLING: mask = 0x0A; break; case LOW: mask = 0x08; break; case HIGH: mask = 0x0C; break; default: return; } mask = (mask << 16) | 0x01000000; config = portConfigRegister(pin); #if defined(KINETISK) attachInterruptVector(IRQ_PORTA, porta_interrupt); attachInterruptVector(IRQ_PORTB, portb_interrupt); attachInterruptVector(IRQ_PORTC, portc_interrupt); attachInterruptVector(IRQ_PORTD, portd_interrupt); attachInterruptVector(IRQ_PORTE, porte_interrupt); #elif defined(KINETISL) attachInterruptVector(IRQ_PORTA, porta_interrupt); attachInterruptVector(IRQ_PORTCD, portcd_interrupt); #endif __disable_irq(); cfg = *config; cfg &= ~0x000F0000; // disable any previous interrupt *config = cfg; intFunc[pin] = function; // set the function pointer cfg |= mask; *config = cfg; // enable the new interrupt __enable_irq(); }
void RtcEnterLowPowerStopMode( void ) { if( ( LowPowerDisableDuringTask == false ) && ( RtcTimerEventAllowsLowPower == true ) ) { // Disable IRQ while the MCU is being deinitialized to prevent race issues __disable_irq( ); BoardDeInitMcu( ); __enable_irq( ); /* Disable the Power Voltage Detector */ PWR_PVDCmd( DISABLE ); /* Set MCU in ULP (Ultra Low Power) */ PWR_UltraLowPowerCmd( ENABLE ); /*Disable fast wakeUp*/ PWR_FastWakeUpCmd( DISABLE ); /* Enter Stop Mode */ PWR_EnterSTOPMode( PWR_Regulator_LowPower, PWR_STOPEntry_WFI ); } }
Bool iapWriteBuffer(UInt32 flash_address, UInt32 * buffer, UInt32 count) { UInt32 iapParameter[5]; UInt32 iapResult[5]; //todo disable irq __disable_irq(); iapParameter[0] = IAP_COPY_RAM_TO_FLASH; iapParameter[1] = flash_address; iapParameter[2] = (UInt32)buffer; iapParameter[3] = count; iapParameter[4] = IAP_CCLK; iapExecute(iapParameter,iapResult); //todo enable irq __enable_irq(); if(iapResult[0] != IAP_SUCCESS) { return False; } return True; }
void TPM0_IRQHandler(){ // Handler for TPM0 interrupts: LED fading __disable_irq(); // Temporarily disable other interrupts if (TPM0_BASE_PTR->CONTROLS[LED_INTERRUPT].CnSC & TPM_CnSC_CHF_MASK) { //Writing to the CHF bit clears the interrupt TPM0_BASE_PTR->CONTROLS[LED_INTERRUPT].CnSC |= TPM_CnSC_CHF_MASK; // Increment counter used for LED Fading portion = 0.5 + sin(phase) / 2; TPM2_BASE_PTR->CONTROLS[RED_LED].CnV = TPM2_BASE_PTR->MOD * portion; TPM2_BASE_PTR->CONTROLS[GREEN_LED].CnV = TPM2_BASE_PTR->MOD * portion/2; TPM0_BASE_PTR->CONTROLS[BLUE_LED].CnV = TPM0_BASE_PTR->MOD * portion/4; phase += 0.5; } // Clear this interrupt NVIC_ClearPendingIRQ(TPM0_IRQn); // Reenable other interrupts __enable_irq(); }
/** \brief Test case: TC_CoreFunc_IPSR \details - Check if __get_IPSR intrinsic is available - Check if __get_xPSR intrinsic is available - Result differentiates between thread and exception modes */ void TC_CoreFunc_IPSR (void) { uint32_t result = __get_IPSR(); ASSERT_TRUE(result == 0U); // Thread Mode result = __get_xPSR(); ASSERT_TRUE((result & xPSR_ISR_Msk) == 0U); // Thread Mode TST_IRQHandler = TC_CoreFunc_IPSR_IRQHandler; irqIPSR = 0U; irqXPSR = 0U; NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_EnableIRQ(WDT_IRQn); __enable_irq(); NVIC_SetPendingIRQ(WDT_IRQn); for(uint32_t i = 10U; i > 0U; --i) {} __disable_irq(); NVIC_DisableIRQ(WDT_IRQn); ASSERT_TRUE(irqIPSR != 0U); // Exception Mode ASSERT_TRUE((irqXPSR & xPSR_ISR_Msk) != 0U); // Exception Mode }
bool PersistentStore::access_start() { uint32_t first_nblank_loc, first_nblank_val; IAP_STATUS_CODE status; // discover which slot we are currently using. __disable_irq(); status = BlankCheckSector(EEPROM_SECTOR, EEPROM_SECTOR, &first_nblank_loc, &first_nblank_val); __enable_irq(); if (status == CMD_SUCCESS) { // sector is blank so nothing stored yet for (int i = 0; i < EEPROM_SIZE; i++) ram_eeprom[i] = EEPROM_ERASE; current_slot = EEPROM_SLOTS; } else { // current slot is the first non blank one current_slot = first_nblank_loc / EEPROM_SIZE; uint8_t *eeprom_data = SLOT_ADDRESS(EEPROM_SECTOR, current_slot); // load current settings for (int i = 0; i < EEPROM_SIZE; i++) ram_eeprom[i] = eeprom_data[i]; } eeprom_dirty = false; return true; }
// Returns 1 if the receiving process was BLOCKED_ON_RECEIVE before the message was sent. int k_send_message_helper(int sender_id, int receiver_id, void* message_envelope) { PCB* receiving_proc; __disable_irq(); ((MSG_BUF*)message_envelope)->m_send_pid = sender_id; ((MSG_BUF*)message_envelope)->m_recv_pid = receiver_id; ((MSG_BUF*)message_envelope)->m_kdata[0] = 0; // Set delay to 0. receiving_proc = gp_pcbs[receiver_id]; enqueue(&(receiving_proc->msg_queue), message_envelope); if (receiving_proc->m_state == BLOCKED_ON_RECEIVE) { receiving_proc->m_state = READY; remove(&g_blocked_msg_queues[receiving_proc->m_priority], (Node*)receiving_proc); ready_queue_enqueue(receiving_proc); __enable_irq(); return 1; } __enable_irq(); return 0; }
int MODSERIAL::__getc(bool block) { // If no buffer is in use fall back to standard RX FIFO usage. // Note, we must block in this case and ignore bool "block" // so as to maintain compat with Mbed Serial. if (buffer_size[RxIrq] == 0 || buffer[RxIrq] == (char *)NULL) { while(! MODSERIAL_RBR_HAS_DATA ) ; return (int)(_RBR & 0xFF); } if (block) { while ( MODSERIAL_RX_BUFFER_EMPTY ) ; } // Blocks. else if ( MODSERIAL_RX_BUFFER_EMPTY ) return -1; int c = buffer[RxIrq][buffer_out[RxIrq]]; buffer_out[RxIrq]++; if (buffer_out[RxIrq] >= buffer_size[RxIrq]) { buffer_out[RxIrq] = 0; } // If we have made space in the RX Buffer then copy over // any characters in the RX FIFO that my reside there. // Temporarily disable the RX IRQ so that we do not re-enter // it under interrupts. if ( ! MODSERIAL_RX_BUFFER_FULL ) { uint32_t ier = _IER; _IER &= ~(1UL << 0); isr_rx(); _IER = ier; } __disable_irq(); buffer_count[RxIrq]--; __enable_irq(); return c; }
void erase_flash_block(uint32_t block_addr) { __disable_irq(); DO_IAP(IAP_ERAS_BLCK,block_addr,0,0); __enable_irq(); }
void erase_flash_page(uint32_t page_addr) { __disable_irq(); DO_IAP(IAP_ERAS_SECT,page_addr,0,0); __enable_irq(); }
// new common exception code // TODO: we have task switching so if fault occures in task we can just remove task from queue // void __attribute__((noreturn)) __error(uint32_t num, uint32_t pc, uint32_t lr) { #ifdef DEBUG_BUILD static const char * const faults[] = { "", // 0 "", // 1 "HardFault", // 2 "MemManage fault", // 3 "BusFault", // 4 "UsageFault", // 5 "illegal Flash Write", // 6 "", // 7 "", // 8 "", // 9 "", // 10 "PureVirtual function call", // 11 "failed to setup clock", // 12 "exit from main()", // 13 "", // 14 }; #endif /* Turn off peripheral interrupts */ __disable_irq(); timer_disable_all(); // turn off all PWM if(is_bare_metal()) // bare metal build without bootloader should reboot to DFU after any fault board_set_rtc_register(DFU_RTC_SIGNATURE, RTC_SIGNATURE_REG); /* Turn the USB interrupt back on so "the reboot to bootloader" keeps on functioning */ NVIC_EnableIRQ(OTG_HS_EP1_OUT_IRQn); NVIC_EnableIRQ(OTG_HS_EP1_IN_IRQn); NVIC_EnableIRQ(OTG_HS_EP1_IN_IRQn); NVIC_EnableIRQ(OTG_HS_IRQn); NVIC_EnableIRQ(OTG_FS_IRQn); __enable_irq(); if(boardEmergencyHandler) boardEmergencyHandler(); // call emergency handler #if 0 #ifdef ERROR_USART usart_putstr(ERROR_USART, "\r\n!!! Exception: "); #ifdef DEBUG_BUILD usart_putstr(ERROR_USART, faults[num]); #else usart_putudec(ERROR_USART, num); #endif usart_putstr(ERROR_USART, " at "); usart_putudec(ERROR_USART, pc); usart_putstr(ERROR_USART, " lr "); usart_putudec(ERROR_USART, lr); usart_putc(ERROR_USART, '\n'); usart_putc(ERROR_USART, '\r'); #endif #else #ifdef DEBUG_BUILD printf("\r\n!!! Exception: %s at %x LR=%x\n",faults[num], pc, lr); #else printf("\r\n!!! Exception: %d at %x LR=%x\n",num, pc, lr); #endif #endif error_throb(num); }
// Read data from I2C port // input: // I2Cx - I2C port // buf - pointer to data buffer // nbytes - number of bytes to receive // SlaveAddress - address of slave device // return: // I2C_ERROR if there was a timeout during I2C operations, I2C_SUCCESS otherwise I2C_Status I2Cx_Read(I2C_TypeDef* I2Cx, uint8_t *buf, uint32_t nbytes, uint8_t SlaveAddress) { // Enable Acknowledgment I2Cx->CR1 |= I2C_CR1_ACK; // Clear POS flag I2Cx->CR1 &= ~I2C_CR1_POS; // NACK position current // Initiate START sequence I2Cx->CR1 |= I2C_CR1_START; // Wait for EV5 if (I2Cx_WaitEvent(I2Cx,I2C_EVENT_EV5) == I2C_ERROR) return I2C_ERROR; // Send the slave address (EV5) I2Cx->DR = SlaveAddress | I2C_OAR1_ADD0; // Last bit set (receiver mode) // Wait for EV6 if (I2Cx_WaitFlagSet(I2Cx,I2C_F_ADDR) == I2C_ERROR) return I2C_ERROR; // There are can be three cases: // read 1 byte // read 2 bytes // read more than 2 bytes if (nbytes == 1) { // Receive 1 byte (AN2824 figure 2) I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_ACK); // Disable I2C acknowledgment // EV6_1 must be atomic operation (AN2824) __disable_irq(); (void)I2Cx->SR1; // Clear ADDR bit (void)I2Cx->SR2; I2Cx->CR1 |= I2C_CR1_STOP; // Generate a STOP condition __enable_irq(); // Wait for RxNE flag (receive buffer not empty) EV7 if (I2Cx_WaitFlagSet(I2Cx,I2C_F_RXNE) == I2C_ERROR) return I2C_ERROR; // Read received byte *buf = (uint8_t)I2Cx->DR; } else if (nbytes == 2) { // Receive 2 bytes (AN2824 figure 2) I2Cx->CR1 |= I2C_CR1_POS; // Set POS flag (NACK position next) // EV6_1 must be atomic operation (AN2824) __disable_irq(); (void)I2Cx->SR2; // Clear ADDR bit I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_ACK); // Disable I2C acknowledgment __enable_irq(); // Wait for BTF flag set (byte transfer finished) EV7_3 if (I2Cx_WaitFlagSet(I2Cx,I2C_F_BTF) == I2C_ERROR) return I2C_ERROR; // This should be atomic operation __disable_irq(); // Generate a STOP condition I2Cx->CR1 |= I2C_CR1_STOP; // Read first received byte *buf++ = (uint8_t)I2Cx->DR; __enable_irq(); // Read second received byte *buf = (uint8_t)I2Cx->DR; } else { // Receive more than 2 bytes (AN2824 figure 1) (void)I2Cx->SR2; // Clear ADDR bit // Read received bytes into buffer while (nbytes-- != 3) { // Wait for BTF (cannot guarantee 1 transfer completion time) if (I2Cx_WaitFlagSet(I2Cx,I2C_F_BTF) == I2C_ERROR) return I2C_ERROR; *buf++ = (uint8_t)I2Cx->DR; } // Wait for BTF flag set (byte transfer finished) EV7_2 if (I2Cx_WaitFlagSet(I2Cx,I2C_F_BTF) == I2C_ERROR) return I2C_ERROR; // Disable the I2C acknowledgment I2Cx->CR1 &= (uint16_t)~((uint16_t)I2C_CR1_ACK); __disable_irq(); // Read received byte N-2 *buf++ = (uint8_t)I2Cx->DR; // Generate a STOP condition I2Cx->CR1 |= I2C_CR1_STOP; __enable_irq(); // Read received byte N-1 *buf++ = I2Cx->DR; // Wait for last byte received if (I2Cx_WaitEvent(I2Cx,I2C_EVENT_EV7) == I2C_ERROR) return I2C_ERROR; // Read last received byte *buf = (uint8_t)I2Cx->DR; } // Wait for a STOP flag if (I2Cx_WaitFlagReset(I2Cx,I2C_F_STOPF) == I2C_ERROR) return I2C_ERROR; return I2C_SUCCESS; }
static bool bootloaderProcess(CrtpPacket *pk) { static char buffer[BUFFER_PAGES*PAGE_SIZE]; if ((pk->datalen>1) && (pk->header == 0xFF) && (pk->data[0]==0xFF)) { if (pk->data[1] == CMD_GET_INFO) { GetInfoReturns_t * info = (GetInfoReturns_t *)&pk->data[2]; info->pageSize = PAGE_SIZE; info->nBuffPages = BUFFER_PAGES; info->nFlashPages = flashPages; info->flashStart = FLASH_START; //memcpy(info->cpuId, cpuidGetId(), CPUID_LEN); info->version = PROTOCOL_VERSION; pk->datalen = 2+sizeof(GetInfoReturns_t); return true; } else if (pk->data[1] == CMD_GET_MAPPING) { const uint8_t mapping[] = {4, 16, 1, 64, 7, 128}; GetMappingReturns_t * returns = (GetMappingReturns_t *)&pk->data[2]; memcpy(returns->mapping, mapping, sizeof(mapping)); pk->datalen = 2+sizeof(mapping); return true; }/* else if (pk->data[1] == CMD_SET_ADDRESS) { SetAddressParameters_t * addressPk; addressPk = (SetAddressParameters_t *)&pk->data[2]; radioSetAddress(addressPk->address); } else */if (pk->data[1] == CMD_LOAD_BUFFER) { int i=0; LoadBufferParameters_t *params = (LoadBufferParameters_t *)&pk->data[2]; char *data = (char*) &pk->data[2+sizeof(LoadBufferParameters_t)]; //Fill the buffer with the given data for(i=0; i<(pk->datalen-(2+sizeof(LoadBufferParameters_t))) && (i+(params->page*PAGE_SIZE)+params->address)<(BUFFER_PAGES*PAGE_SIZE); i++) { buffer[(i+(params->page*PAGE_SIZE)+params->address)] = data[i]; } } else if (pk->data[1] == CMD_READ_BUFFER) { int i=0; ReadBufferParameters_t *params = (ReadBufferParameters_t *)&pk->data[2]; char *data = (char*) &pk->data[2+sizeof(ReadBufferParameters_t)]; //Return the data required for(i=0; i<25 && (i+(params->page*PAGE_SIZE)+params->address)<(BUFFER_PAGES*PAGE_SIZE); i++) { data[i] = buffer[(i+(params->page*PAGE_SIZE)+params->address)]; } pk->datalen += i; return true; } else if (pk->data[1] == CMD_READ_FLASH) { int i=0; char *data = (char*) &pk->data[2+sizeof(ReadFlashParameters_t)]; ReadFlashParameters_t *params = (ReadFlashParameters_t *)&pk->data[2]; char *flash= (char*)FLASH_BASE; //Return the data required for(i=0; i<25 && (i+(params->page*PAGE_SIZE)+params->address)<(flashPages*PAGE_SIZE); i++) { //data[i] = flash[(i+(params->page*PAGE_SIZE)+params->address)]; //data[i] = *((char*)(FLASH_BASE+i+(params->page*PAGE_SIZE)+params->address)); data[i] = flash[(i+(params->page*PAGE_SIZE)+params->address)]; } pk->datalen += i; return true; } else if (pk->data[1] == CMD_WRITE_FLASH) { int i; int j; unsigned int error = 0xFF; int flashAddress; uint32_t *bufferToFlash; WriteFlashParameters_t *params = (WriteFlashParameters_t *)&pk->data[2]; WriteFlashReturns_t *returns = (WriteFlashReturns_t *)&pk->data[2]; //Test if it is an acceptable write request if ( (params->flashPage<FLASH_START) || (params->flashPage>=flashPages) || ((params->flashPage+params->nPages)>flashPages) || (params->bufferPage>=BUFFER_PAGES) ) { //Return a failure answer returns->done = 0; returns->error = 1; pk->datalen = 2+sizeof(WriteFlashReturns_t); return true; } // Else, if everything is OK, flash the page(s) else { FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR |FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); __disable_irq(); //Erase the page(s) for(i=0; i<params->nPages; i++) { for (j=0; j<12; j++) { if ((uint32_t)(FLASH_BASE + ((uint32_t)params->flashPage*PAGE_SIZE) + (i*PAGE_SIZE)) == sector_address[j]) { if ( FLASH_EraseSector(j<<3, VoltageRange_3) != FLASH_COMPLETE) { error = 2; goto failure; } } } } //Write the data, long per long flashAddress = FLASH_BASE + (params->flashPage*PAGE_SIZE); bufferToFlash = (uint32_t *) (&buffer[0] + (params->bufferPage*PAGE_SIZE)); for (i=0; i<((params->nPages*PAGE_SIZE)/sizeof(uint32_t)); i++, flashAddress+=4) { if(FLASH_ProgramWord(flashAddress, bufferToFlash[i]) != FLASH_COMPLETE) { error = 3; goto failure; } } //Everything OK! great, send back an OK packet returns->done = 1; returns->error = 0; pk->datalen = 2+sizeof(WriteFlashReturns_t); FLASH_Lock(); __enable_irq(); return true; goto finally; failure: FLASH_Lock(); __enable_irq(); //If the write procedure failed, send the error packet //TODO: see if it is necessary or wanted to send the reason as well returns->done = 0; returns->error = error; pk->datalen = 2+sizeof(WriteFlashReturns_t); return true; finally: FLASH_Lock(); __enable_irq(); } } } return false; }
// software IO functions... void jshInterruptOff() { __disable_irq(); // Disabling interrupts is not reasonable when using one of the SoftDevices. }
// This method translates 2 wires (a tx and rx line) to 1 wire, by letting the // RX line control when data should be read or written from the single line void usb1WirePassthrough(uint8_t escIndex) { #ifdef BEEPER // fix for buzzer often starts beeping continuously when the ESCs are read // switch beeper silent here beeperSilence(); #endif // disable all interrupts __disable_irq(); // prepare MSP UART port for direct pin access // reset all the pins GPIO_ResetBits(S1W_RX_GPIO, S1W_RX_PIN); GPIO_ResetBits(S1W_TX_GPIO, S1W_TX_PIN); // configure gpio gpio_set_mode(S1W_RX_GPIO, S1W_RX_PIN, Mode_IPU); gpio_set_mode(S1W_TX_GPIO, S1W_TX_PIN, Mode_Out_PP); #ifdef STM32F10X // reset our gpio register pointers and bitmask values gpio_prep_vars(escIndex); #endif ESC_OUTPUT(escIndex); ESC_SET_HI(escIndex); TX_SET_HIGH; // Wait for programmer to go from 1 -> 0 indicating incoming data while(RX_HI); while(1) { // A new iteration on this loop starts when we have data from the programmer (read_programmer goes low) // Setup escIndex pin to send data, pullup is the default ESC_OUTPUT(escIndex); // Write the first bit ESC_SET_LO(escIndex); // Echo on the programmer tx line TX_SET_LO; //set LEDs RX_LED_OFF; TX_LED_ON; // Wait for programmer to go 0 -> 1 uint32_t ct=3333; while(!RX_HI) { if (ct > 0) ct--; // count down until 0; // check for low time ->ct=3333 ~600uS //byte LO time for 0 @ 19200 baud -> 9*52 uS => 468.75uS // App must send a 0 at 9600 baud (or lower) which has a LO time of at 104uS (or more) > 0 = 937.5uS LO // BLHeliSuite will use 4800 baud } // Programmer is high, end of bit // At first Echo to the esc, which helps to charge input capacities at ESC ESC_SET_HI(escIndex); // Listen to the escIndex, input mode, pullup resistor is on gpio_set_mode(escHardware[escIndex].gpio, escHardware[escIndex].pin, Mode_IPU); TX_LED_OFF; if (ct==0) break; //we reached zero // Listen to the escIndex while there is no data from the programmer while (RX_HI) { if (ESC_HI(escIndex)) { TX_SET_HIGH; RX_LED_OFF; } else { TX_SET_LO; RX_LED_ON; } } } // we get here in case ct reached zero TX_SET_HIGH; RX_LED_OFF; // Enable all irq (for Hardware UART) __enable_irq(); return; }
/******************************************************************************* * Function Name : WavePlayer_StartSpeaker * Description : Starts the wave player application. * Input : None * Output : None * Return : None *******************************************************************************/ void WavePlayer_StartSpeaker(void) { uint8_t MyKey = 0; uint32_t err = 0, Counter = 0x0; LCD_Clear(White); /* Disable the JoyStick interrupts */ IntExtOnOffConfig(DISABLE); while(ReadKey() != NOKEY) { } /* Display the welcome screen and the commands */ LCD_Update(ALL); /* Choose number of repetitions: 0 => infinite repetitions */ I2S_CODEC_ReplayConfig(0); I2S_CODEC_Init(OutputDevice_SPEAKER, AUDIO_FILE_ADDRESS); /* Endless loop */ while(1) { /* Check which key is pressed */ MyKey = ReadKey(); if(Counter == 0) { /* Mask All Interrupts */ __disable_irq(); /* Update the displayed progression information */ LCD_Update(PROGRESS); Counter = 0x5FFFF; /* Disable mask of all interrupts */ __enable_irq(); } Counter--; /* If "UP" pushbutton is pressed */ if(MyKey == UP) { /* Mask All Interrupts */ __disable_irq(); /* Check if the Codec is PLAYING audio file */ if (GetVar_AudioPlayStatus() == AudioPlayStatus_PLAYING) { I2S_CODEC_ControlVolume(VolumeDirection_HIGH, VOLStep); /* Update the display information */ LCD_Update(VOL); } /* UP bottomn pushed in PAUSE mode => Enable the Speaker device output ---*/ else { /* Update the display information */ LCD_Update(PLAY); /* Configure the Speaker as output and reinitialize all devices */ err = I2S_CODEC_SpeakerHeadphoneSwap(OutputDevice_SPEAKER, AUDIO_FILE_ADDRESS); /* Error message display if failure */ if (err != 0) { LCD_DisplayError(err); /* Enable the FSMC that share a pin w/ I2C1 (LBAR) */ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE); /* Clear the LCD */ LCD_Clear(White); /* Display the previous menu */ DisplayMenu(); /* Disable mask of all interrupts */ __enable_irq(); /* Enable the JoyStick interrupts */ IntExtOnOffConfig(ENABLE); return; } } /* Disable mask of all interrupts */ __enable_irq(); } /* If "DOWN" pushbutton is pressed */ if(MyKey == DOWN) { /* Mask All Interrupts */ __disable_irq(); /* If the Codec is PLAYING => Decrease Volume*/ if (GetVar_AudioPlayStatus() == AudioPlayStatus_PLAYING) { /* Increase the audio codec digital volume */ I2S_CODEC_ControlVolume(VolumeDirection_LOW, VOLStep); /* Update the LCD display */ LCD_Update(VOL); } else /* If the Codec is PAUSED => Headphone Enable */ { /* Update the LCD display */ LCD_Update(PLAY); /* Enable the Headphone output and reinitialize all devices */ err = I2S_CODEC_SpeakerHeadphoneSwap(OutputDevice_HEADPHONE, AUDIO_FILE_ADDRESS); /* Error message display if failure */ if (err != 0) { LCD_DisplayError(err); /* Enable the FSMC that share a pin w/ I2C1 (LBAR) */ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE); /* Clear the LCD */ LCD_Clear(White); /* Display the previous menu */ DisplayMenu(); /* Disable mask of all interrupts */ __enable_irq(); /* Enable the JoyStick interrupts */ IntExtOnOffConfig(ENABLE); return; } } /* Disable mask of all interrupts */ __enable_irq(); } /* If "RIGHT" pushbutton is pressed */ if(MyKey == RIGHT) { /* Mask All Interrupts */ __disable_irq(); /* Check if the Codec is PLAYING audio file */ if (GetVar_AudioPlayStatus() == AudioPlayStatus_PLAYING) { I2S_CODEC_ForwardPlay(STEP_FORWARD); /* Update the display information */ LCD_Update(FRWD); } /* Disable mask of all interrupts */ __enable_irq(); } /* If "LEFT" pushbutton is pressed */ if(MyKey == LEFT) { /* Mask All Interrupts */ __disable_irq(); /* Check if the Codec is PLAYING audio file */ if (GetVar_AudioPlayStatus() == AudioPlayStatus_PLAYING) { I2S_CODEC_RewindPlay(STEP_BACK); /* Update the display information */ LCD_Update(FRWD); } /* Disable mask of all interrupts */ __enable_irq(); } /* If "SEL" pushbutton is pressed */ if(MyKey == SEL) { /* Mask All Interrupts */ __disable_irq(); /* Update the display information */ LCD_Update(STOP); /* Command the Stop of the current audio stream */ SetVar_AudioPlayStatus(AudioPlayStatus_STOPPED); /* Disable mask of all interrupts */ __enable_irq(); I2S_CODEC_Stop(); SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_TXE, DISABLE); /* Enable the FSMC that share a pin w/ I2C1 (LBAR) */ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE); /* Clear the LCD */ LCD_Clear(White); /* Display the previous menu */ DisplayMenu(); /* Enable the JoyStick interrupts */ IntExtOnOffConfig(ENABLE); return; } /* If "KEY" pushbutton is pressed */ if(MyKey == KEY) { /* Mask All Interrupts */ __disable_irq(); /* If the Codec is Playing => PAUSE */ if (GetVar_AudioPlayStatus() == AudioPlayStatus_PLAYING) { /* Update the display information */ LCD_Update(PAUSE); /* Command the Pause of the current stream */ SetVar_AudioPlayStatus(AudioPlayStatus_PAUSED); } /* If the Codec is PAUSED => Resume PLAYING */ else if (GetVar_AudioPlayStatus() == AudioPlayStatus_PAUSED) { /* Update the LCD display */ LCD_Update(PLAY); /* Start playing from the last saved position */ I2S_CODEC_Play(GetVar_AudioDataIndex()); } /* If the Codec is STOPPED => PLAY from the file start address */ else if (GetVar_AudioPlayStatus() == AudioPlayStatus_STOPPED) { /* Update the display information */ LCD_Update(PLAY); /* Initialize all devices w/choosen parameters */ err = I2S_CODEC_Init(GetVar_CurrentOutputDevice(), AUDIO_FILE_ADDRESS); /* Error message display if failure */ if (err != 0) { LCD_DisplayError(err); /* Enable the FSMC that share a pin w/ I2C1 (LBAR) */ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE); /* Clear the LCD */ LCD_Clear(White); /* Display the previous menu */ DisplayMenu(); /* Disable mask of all interrupts */ __enable_irq(); /* Enable the JoyStick interrupts */ IntExtOnOffConfig(ENABLE); return; } /* Enable Playing the audio file */ I2S_CODEC_Play(GetVar_DataStartAddr()); } /* Disable mask of all interrupts */ __enable_irq(); } } }
long rod_CreateFile_edit (void) { s32 i = 0; FIL Fil; FIL Fil2; FRESULT result; FATFS fls; FILINFO fno; long res = 0; char t_str[25]; __disable_irq(); __disable_fiq(); IWDG_ReloadCounter(); res = f_mount(&fls, "0:", 1); res = f_open(&Fil,"0:Road.0", FA_CREATE_ALWAYS | FA_WRITE); f_printf(&Fil,"%s", "без маршрута "); f_putc(0,&Fil); // f_open(&Fil,"0:Road.000", FA_OPEN_ALWAYS | FA_WRITE); // f_lseek(&Fil, 16); for(i=1;i<500;i++) { { f_printf(&Fil,"%s %03u ","точка",i); f_putc(i,&Fil); } } //Получаем размер res = f_size(&Fil); f_close(&Fil); IWDG_ReloadCounter(); //Только чтение f_chmod("0:Road.0", AM_RDO, AM_RDO | AM_ARC); f_open(&Fil,"0:Road.log", FA_CREATE_ALWAYS | FA_WRITE); f_printf(&Fil,"%s", "Road.0"); f_close(&Fil); f_open(&Fil2,"0:Roads.txt", FA_CREATE_ALWAYS | FA_WRITE); f_printf(&Fil2,"%s", "Road.0"); f_close(&Fil2); // //Проверяем размер // f_open(&Fil,"0:Road.100", FA_OPEN_ALWAYS); // //if (f_size(&Fil) == 16000) res = 1; // res = f_size(&Fil); // f_close(&Fil); f_mount(0,"0:", 0); __enable_irq(); __enable_fiq(); return res; }
/* ********************************************************************************************************* * Disable the CPU interruption * * Description: Disable the Hardware interruptions * * Argument(s): none * * Returns : none ********************************************************************************************************* */ void BSP_IntDisAll(void) { __disable_irq(); }
uint32_t FLASH_Write_chars( uint32_t FlashAddress, uint8_t* Data ,uint16_t DataLength) { uint16_t temp; __disable_irq(); for (u16 i = 0; i < (DataLength/2); i++) { temp = (u16)(Data[i*2] + Data[i*2+1] *256); if (FLASH_ProgramHalfWord(FlashAddress, temp) == FLASH_COMPLETE) { /* Check the written value */ if (*(u16*)FlashAddress != temp) { /* Flash content doesn't match SRAM content */ //return(2); __enable_irq(); return FLASH_WRITE_ERROR; } } else { __enable_irq(); return FLASH_ERASE_ERROR; } FlashAddress += 2; } if (DataLength % 2 == 0) { __enable_irq(); return FLASH_OK; } else { temp = (u16)(Data[DataLength -1]); if (FLASH_ProgramHalfWord(FlashAddress, temp) == FLASH_COMPLETE) { /* Check the written value */ if (*(u16*)FlashAddress != temp) { /* Flash content doesn't match SRAM content */ __enable_irq(); return FLASH_WRITE_ERROR; } else { __enable_irq(); return FLASH_OK; } } else { __enable_irq(); return FLASH_ERASE_ERROR; } } }
void i2c_event(void) { static uint32_t cnt = 0; //I2C_TypeDef *regs; cnt++; if (cnt > 10000) cnt = 0; #ifndef I2C_DEBUG_LED #ifdef USE_I2C1 if (i2c1.status == I2CIdle) { if (i2c_idle(&i2c1)) { __disable_irq(); // More work to do if (i2c1.trans_extract_idx != i2c1.trans_insert_idx) { // Restart transaction doing the Rx part now PPRZ_I2C_SEND_START(&i2c1); } __enable_irq(); } } #endif #endif #ifdef USE_I2C2 #ifdef I2C_DEBUG_LED if (cnt == 0) { __disable_irq(); LED2_ON(); LED1_ON(); LED1_OFF(); LED1_ON(); LED1_OFF(); LED1_ON(); LED1_OFF(); LED1_ON(); LED1_OFF(); if (i2c2.status == I2CIdle) { LED1_ON(); LED1_OFF(); } else if (i2c2.status == I2CStartRequested) { LED1_ON(); LED1_OFF(); LED1_ON(); LED1_OFF(); } LED2_OFF(); //regs = (I2C_TypeDef *) i2c2.reg_addr; //LED_SHOW_ACTIVE_BITS(regs); __enable_irq(); } #endif //if (i2c2.status == I2CIdle) { //if (i2c_idle(&i2c2)) { //__disable_irq(); // More work to do //if (i2c2.trans_extract_idx != i2c2.trans_insert_idx) { // Restart transaction doing the Rx part now //PPRZ_I2C_SEND_START(&i2c2); } //__enable_irq(); } } #endif }
__weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) { uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickCTRL; TickType_t 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_ENABLE_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 from whatever is left in the count register to complete this tick period. */ portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG; /* Restart SysTick. */ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; /* Reset the reload register to the value required for normal tick periods. */ portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; /* 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_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. */ ulSysTickCTRL = portNVIC_SYSTICK_CTRL_REG; portNVIC_SYSTICK_CTRL_REG = ( ulSysTickCTRL & ~portNVIC_SYSTICK_ENABLE_BIT ); /* Re-enable interrupts - see comments above __disable_irq() call above. */ __enable_irq(); if( ( ulSysTickCTRL & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 ) { uint32_t ulCalculatedLoadValue; /* 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. */ ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG ); /* Don't allow a tiny value, or values that have somehow underflowed because the post sleep hook did something that took too long. */ if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) ) { ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ); } portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue; /* 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_ENABLE_BIT; vTaskStepTick( ulCompleteTickPeriods ); portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; } portEXIT_CRITICAL(); } }
void clockInit(void) { //uint32_t EMCClk; __disable_irq(); /* Set the XTAL oscillator frequency to 12MHz*/ CGU_SetXTALOSC(__CRYSTAL); CGU_EnableEntity(CGU_CLKSRC_XTAL_OSC, ENABLE); CGU_EntityConnect(CGU_CLKSRC_XTAL_OSC, CGU_BASE_M3); /* Set PL160M 12*1 = 12 MHz */ CGU_EntityConnect(CGU_CLKSRC_XTAL_OSC, CGU_CLKSRC_PLL1); // CGU_EntityConnect(CGU_CLKSRC_IRC, CGU_CLKSRC_PLL1); CGU_SetPLL1(1); CGU_EnableEntity(CGU_CLKSRC_PLL1, ENABLE); // setup CLKOUT CGU_EntityConnect(CGU_CLKSRC_PLL1, CGU_CLKSRC_IDIVB); CGU_EnableEntity(CGU_CLKSRC_IDIVB, ENABLE); CGU_SetDIV(CGU_CLKSRC_IDIVB, 12); // 12 -> 6 pclks per cpu clk, 10 -> 5 pclks // set input for CLKOUT to IDIVB LPC_CGU->BASE_OUT_CLK &= ~0x0f000000; LPC_CGU->BASE_OUT_CLK |= 0x0d000000; /* Run SPIFI from PL160M, /2 */ CGU_EntityConnect(CGU_CLKSRC_PLL1, CGU_CLKSRC_IDIVA); CGU_EnableEntity(CGU_CLKSRC_IDIVA, ENABLE); CGU_SetDIV(CGU_CLKSRC_IDIVA, 2); CGU_EntityConnect(CGU_CLKSRC_IDIVA, CGU_BASE_SPIFI); CGU_UpdateClock(); LPC_CCU1->CLK_M4_EMCDIV_CFG |= (1<<0) | (1<<5); // Turn on clock / 2 LPC_CREG->CREG6 |= (1<<16); // EMC divided by 2 LPC_CCU1->CLK_M4_EMC_CFG |= (1<<0); // Turn on clock /* Set PL160M @ 12*9=108 MHz */ CGU_SetPLL1(9); /* Run base M3 clock from PL160M, no division */ CGU_EntityConnect(CGU_CLKSRC_PLL1, CGU_BASE_M3); waitMS(10); /* Change the clock to 204 MHz */ /* Set PL160M @ 12*15=180 MHz */ CGU_SetPLL1(17); waitMS(10); CGU_UpdateClock(); //EMCFlashInit(); //vEMC_InitSRDRAM(SDRAM_BASE_ADDR, SDRAM_WIDTH, SDRAM_SIZE_MBITS, SDRAM_DATA_BUS_BITS, SDRAM_COL_ADDR_BITS); LPC_SCU->SFSP3_3 = 0xF3; /* high drive for SCLK */ /* IO pins */ LPC_SCU->SFSP3_4=LPC_SCU->SFSP3_5=LPC_SCU->SFSP3_6=LPC_SCU->SFSP3_7 = 0xD3; LPC_SCU->SFSP3_8 = 0x13; /* CS doesn't need feedback */ #if 0 EMCClk = CGU_GetPCLKFrequency(CGU_PERIPHERAL_M3CORE)/2; if (spifi_init(&sobj, 9, S_RCVCLK | S_FULLCLK, EMCClk)) { if (spifi_init(&sobj, 9, S_RCVCLK | S_FULLCLK, EMCClk)) { while(1); } } #endif __enable_irq(); // SPIFI_Init(); }
uint8_t I2cMcuWriteBuffer( I2c_t *obj, uint8_t deviceAddr, uint16_t addr, uint8_t *buffer, uint16_t size ) { uint32_t timeOut; __disable_irq( ); /* Test on BUSY Flag */ timeOut = TIMEOUT_MAX; while( I2C_GetFlagStatus( obj->I2c, I2C_FLAG_BUSY) ) { if( ( timeOut-- ) == 0 ) { I2cResetBus( obj ); __enable_irq( ); return( FAIL ); } } /* Send START condition */ I2C_GenerateSTART( obj->I2c, ENABLE ); /* Test on EV5 and clear it */ timeOut = TIMEOUT_MAX; while( !I2C_CheckEvent( obj->I2c, I2C_EVENT_MASTER_MODE_SELECT ) ) { if( ( timeOut-- ) == 0 ) { I2cResetBus( obj ); __enable_irq( ); return( FAIL ); } } /* Send device's address for write */ I2C_Send7bitAddress( obj->I2c, deviceAddr, I2C_Direction_Transmitter ); /* Test on EV6 and clear it */ timeOut = TIMEOUT_MAX; while( !I2C_CheckEvent( obj->I2c, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED ) ) { if( ( timeOut-- ) == 0 ) { I2cResetBus( obj ); __enable_irq( ); return( FAIL ); } } if( ( addr & 0xFF00 ) != 0x0000 ) { /* Send the device's internal address MSB to write to */ I2C_SendData( obj->I2c, ( uint8_t )( ( addr & 0xFF00 ) >> 8 ) ); /* Test on EV8 and clear it */ timeOut = TIMEOUT_MAX; while( !I2C_CheckEvent( obj->I2c, I2C_EVENT_MASTER_BYTE_TRANSMITTING ) ) { if( ( timeOut-- ) == 0 ) { I2cResetBus( obj ); __enable_irq( ); return( FAIL ); } } }
/** * @brief Background task * * @note * @param None * @retval None */ void Background (void) { if(TaskExecutionRequested & (1<< eMAIN_Profile_Event_Id)) { if(Hci_Cmd_Lock == FALSE) { TaskExecuted(eMAIN_Profile_Event_Id); BlueNRG_Profile_Event_Callback(); } } if(TaskExecutionRequested & (1<< eMAIN_Profile_Measurement_update_Id)) { if(Hci_Cmd_Lock == FALSE) { TaskExecuted(eMAIN_Profile_Measurement_update_Id); profileApplContext.profileProcessMeasurementFunc(); } } if(TaskExecutionRequested & (1<< eMAIN_HCI_Process_Request_Id)) { /** * It shall be controlled in the application that no HCI command are sent * if one is already pending */ if(Hci_Cmd_Lock == FALSE) { TaskExecuted(eMAIN_HCI_Process_Request_Id); HCI_Process(); } } if(TaskExecutionRequested & (1<< eMAIN_Profile_Process_Request_Id)) { if(Hci_Cmd_Lock == FALSE) { TaskExecuted(eMAIN_Profile_Process_Request_Id); Profile_Process_Q(); } } if(TaskExecutionRequested & (1<< eMAIN_Profile_StateMachine_update_Id)) { if(Hci_Cmd_Lock == FALSE) { TaskExecuted(eMAIN_Profile_StateMachine_update_Id); profileApplContext.profileStateMachineFunc(); } } if(TaskExecutionRequested & (1<< eMAIN_Profile_App_DeviceState_update_Id)) { if(Hci_Cmd_Lock == FALSE) { TaskExecuted(eMAIN_Profile_App_DeviceState_update_Id); profileApplContext.profileApplicationProcessFunc(); } } /** * Power management */ #if LOW_POWER_MODE __disable_irq(); if((TaskExecutionRequested == 0) || (((TaskExecutionRequested & EVENT_NOT_REQUIRING_SENDING_HCI_COMMAND) == 0) && (Hci_Cmd_Lock == TRUE))) { LPM_Enter_Mode(); } __enable_irq(); #endif /* LOW_POWER_MODE */ return; }
ErrorStatus FlashIap_ErasePage(uint8_t Page_Addr) { uint16_t Temp16; uint32_t temp; temp = __get_PRIMASK(); __disable_irq(); if(FlashIap_Unlock() == ERROR) { __set_PRIMASK(temp); return ERROR; } if(FlashIap_CloseAll_WPROT() == ERROR) { __set_PRIMASK(temp); return ERROR; } IAP->ADDR.IAPPA = Page_Addr; IAP->TRIG.TRIG = 0x00005EA1; for(Temp16 = 0; Temp16 < 0xFFFF; Temp16++) { if((IAP->STA.Word & (uint32_t)0x01) == (uint32_t)0x00) break; } if(Temp16 == 0xFFFF) { __set_PRIMASK(temp); return ERROR; } for(Temp16 = 0; Temp16 < 0xFFFF; Temp16++) { if((IAP->STA.Word & (uint32_t)0x02) == (uint32_t)0x02) break; } if(Temp16 == 0xFFFF) { __set_PRIMASK(temp); return ERROR; } if(FlashIap_WriteEnd() == ERROR) { __set_PRIMASK(temp); return ERROR; } if(FlashIap_OpenAll_WPROT() == ERROR) { __set_PRIMASK(temp); return ERROR; } __set_PRIMASK(temp); return SUCCESS; }
// **************************************************************************** void save_persistent_storage(uint8_t new_data[]) { unsigned int param[5]; int i; for (i = 0; i < NUMBER_OF_PERSISTENT_ELEMENTS; i++) { if (new_data[i] != persistent_data[i]) { param[0] = 50; param[1] = ((unsigned int)persistent_data) >> 10; param[2] = ((unsigned int)persistent_data) >> 10; __disable_irq(); iap_entry(param, param); __enable_irq(); if (param[0] != 0) { #ifndef NO_DEBUG uart0_send_cstring("ERROR: prepare sector failed\n"); #endif return; } param[0] = 59; // Erase page command param[1] = ((unsigned int)persistent_data) >> 6; param[2] = ((unsigned int)persistent_data) >> 6; param[3] = __SYSTEM_CLOCK / 1000; __disable_irq(); iap_entry(param, param); __enable_irq(); if (param[0] != 0) { #ifndef NO_DEBUG uart0_send_cstring("ERROR: erase page failed\n"); #endif return; } param[0] = 50; param[1] = ((unsigned int)persistent_data) >> 10; param[2] = ((unsigned int)persistent_data) >> 10; __disable_irq(); iap_entry(param, param); __enable_irq(); if (param[0] != 0) { #ifndef NO_DEBUG uart0_send_cstring("ERROR: prepare sector failed\n"); #endif return; } param[0] = 51; // Copy RAM to Flash command param[1] = (unsigned int)persistent_data; param[2] = (unsigned int)new_data; param[3] = 64; param[4] = __SYSTEM_CLOCK / 1000; __disable_irq(); iap_entry(param, param); __enable_irq(); if (param[0] != 0) { #ifndef NO_DEBUG uart0_send_cstring("ERROR: copy RAM to flash failed: "); uart0_send_uint32_hex(param[0]); uart0_send_linefeed(); #endif return; } return; } }