Example #1
0
void flash_write(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32) {
    #if defined(MCU_SERIES_L4)

    // program the flash uint64 by uint64
    for (int i = 0; i < num_word32 / 2; i++) {
        uint64_t val = *(uint64_t*)src;
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) {
            // error occurred during flash write
            HAL_FLASH_Lock(); // lock the flash
            return;
        }
        flash_dest += 8;
        src += 2;
    }
    if ((num_word32 & 0x01) == 1) {
        uint64_t val = *(uint64_t*)flash_dest;
        val = (val & 0xffffffff00000000uL) | (*src);
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) {
            // error occurred during flash write
            HAL_FLASH_Lock(); // lock the flash
            return;
        }
    }

    #else

    // program the flash word by word
    for (int i = 0; i < num_word32; i++) {
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, flash_dest, *src) != HAL_OK) {
            // error occurred during flash write
            HAL_FLASH_Lock(); // lock the flash
            return;
        }
        flash_dest += 4;
        src += 1;
    }

    #endif

    // lock the flash
    HAL_FLASH_Lock();
}
Example #2
0
void eeprom_write_byte(uint8_t *pos, unsigned char value) {
  uint16_t eeprom_address = (unsigned) pos;

  eeprom_init();

  HAL_FLASH_Unlock();
  __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);

  if (EE_WriteVariable(eeprom_address, (uint16_t) value) != EE_OK)
      for (;;) HAL_Delay(1); // Spin forever until watchdog reset

  HAL_FLASH_Lock();
}
Example #3
0
void eeprom_init() {
  if (!eeprom_initialized) {
    HAL_FLASH_Unlock();

    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);

    /* EEPROM Init */
    if (EE_Initialize() != EE_OK)
      for (;;) HAL_Delay(1); // Spin forever until watchdog reset

    HAL_FLASH_Lock();
    eeprom_initialized = true;
  }
}
Example #4
0
void flash_erase(uint32_t sector)
{
    // unlock
    HAL_FLASH_Unlock();

    #if defined(MCU_SERIES_H7)
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS_BANK1 | FLASH_FLAG_ALL_ERRORS_BANK2);
    #else
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
                           FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
    #endif

    // erase the sector(s)
    FLASH_EraseInitTypeDef EraseInitStruct;
    EraseInitStruct.TypeErase    = TYPEERASE_SECTORS;
    EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V
    #if defined(MCU_SERIES_H7)
    EraseInitStruct.Sector = (sector % 8);
    if (sector < 8) {
        EraseInitStruct.Banks = FLASH_BANK_1;
    } else {
        EraseInitStruct.Banks = FLASH_BANK_2;
    }
    #else
    EraseInitStruct.Sector = sector;
    #endif
    EraseInitStruct.NbSectors = 1;

    uint32_t SectorError = 0;
    if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) {
        // error occurred during sector erase
        HAL_FLASH_Lock(); // lock the flash
        __fatal_error();
    }

    HAL_FLASH_Lock(); // lock the flash
}
static int
stm32f3_flash_erase_sector(const struct hal_flash *dev, uint32_t sector_address)
{
    FLASH_EraseInitTypeDef erase;
    int rc = -1;
    uint32_t errorPage = -1;

    erase.TypeErase = FLASH_TYPEERASE_PAGES;
    erase.PageAddress = sector_address;
    erase.NbPages = 1;

    HAL_FLASH_Unlock();
    if (HAL_OK == HAL_FLASHEx_Erase(&erase, &errorPage)) {
      rc = 0;
    }
    HAL_FLASH_Lock();

    return rc;
}
Example #6
0
HAL_StatusTypeDef ee_format(SavedDomain_t* page) {
	HAL_StatusTypeDef status;
	
	status = HAL_FLASH_Unlock();
	if(status != HAL_OK) {
		return status;
	}
	
	//FLASH_PageErase(PAGE0_BASE_ADDRESS);
	FLASH_PageErase((uint32_t)page);
	
	status = FLASH_WaitForLastOperation(FLASH_TIMEOUT);
	if(status != HAL_OK) {
		return status;
	}
	
	CLEAR_BIT(FLASH->CR, FLASH_CR_PER);
	HAL_FLASH_Lock();
	
	return status;
}
Example #7
0
void flash_erase(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32) {
    // check there is something to write
    if (num_word32 == 0) {
        return;
    }

    // unlock
    HAL_FLASH_Unlock();

    FLASH_EraseInitTypeDef EraseInitStruct;

    #if defined(MCU_SERIES_L4)
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);

    // erase the sector(s)
    // The sector returned by flash_get_sector_info can not be used
    // as the flash has on each bank 0/1 pages 0..255
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.Banks       = get_bank(flash_dest);
    EraseInitStruct.Page        = get_page(flash_dest);
    EraseInitStruct.NbPages     = get_page(flash_dest + 4 * num_word32 - 1) - EraseInitStruct.Page + 1;;
    #else
    // Clear pending flags (if any)
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
                           FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);

    // erase the sector(s)
    EraseInitStruct.TypeErase = TYPEERASE_SECTORS;
    EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V
    EraseInitStruct.Sector = flash_get_sector_info(flash_dest, NULL, NULL);
    EraseInitStruct.NbSectors = flash_get_sector_info(flash_dest + 4 * num_word32 - 1, NULL, NULL) - EraseInitStruct.Sector + 1;
    #endif

    uint32_t SectorError = 0;
    if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) {
        // error occurred during sector erase
        HAL_FLASH_Lock(); // lock the flash
        return;
    }
}
Example #8
0
HAL_StatusTypeDef SaveOptToFlash(SavedDomain_t* Src, SavedDomain_t* Dst) {
	uint16_t* SrcW = (uint16_t*)Src;
	__IO uint16_t* DstW = (uint16_t*)Dst;
	//uint32_t len = sizeof(SavedDomain_t);
	uint32_t len = sizeof(SavedDomain_t) / sizeof(uint16_t);
	
	HAL_StatusTypeDef status = HAL_ERROR;
	
	status = HAL_FLASH_Unlock();
	if(status != HAL_OK) {
		return status;
	}
	
	SET_BIT(FLASH->CR, FLASH_CR_PG); /* Programm the flash */
	
	while(len) {
		*DstW = *SrcW;
	  status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
		if(status != HAL_OK) {
		  return status;
	  }
    if (*DstW != *SrcW )
    {
      return HAL_ERROR;
    }
		
	  DstW++;
    SrcW++;
		len--;
	}
	CLEAR_BIT(FLASH->CR, FLASH_CR_PG);

	status = HAL_FLASH_Lock();
	if(status != HAL_OK) {
		return status;
	}
	
	return status;
}
Example #9
0
File: flash.c Project: ajithat/lk
static ssize_t stm32_flash_bdev_write_block(struct bdev *bdev, const void *buf, bnum_t block, uint count)
{
    LTRACEF("dev %p, buf %p, block 0x%x, count %u\n", bdev, buf, block, count);

    HAL_FLASH_Unlock();

    ssize_t written_bytes = 0;
    const uint32_t *buf32 = (const uint32_t *)buf;
    while (count > 0) {
        if (HAL_FLASH_Program(TYPEPROGRAM_WORD, FLASHAXI_BASE + block * bdev->block_size, *buf32) != HAL_OK) {
            written_bytes = ERR_IO;
            break;
        }

        buf32++;
        block++;
        count--;
    }

    HAL_FLASH_Lock();

    return written_bytes;
}
Example #10
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - 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();

  /* Initialize LED2 */
  BSP_LED_Init(LED2);

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();
  
  /* Unlock the Flash to enable the flash control register access *************/ 
  HAL_FLASH_Unlock();

  /* Unlock the Options Bytes *************************************************/
  HAL_FLASH_OB_Unlock();

  /* Get pages write protection status ****************************************/
  HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);

#ifdef WRITE_PROTECTION_DISABLE
  /* Get pages already write protected ****************************************/
  ProtectedPages = ~(OptionsBytesStruct.WRPPage | FLASH_PAGES_TO_BE_PROTECTED);

  /* Check if desired pages are already write protected ***********************/
  if((OptionsBytesStruct.WRPPage | (~FLASH_PAGES_TO_BE_PROTECTED)) != 0xFFFFFFFF )
  {
    /* Erase all the option Bytes *********************************************/
    if(HAL_FLASHEx_OBErase() != HAL_OK)
    {
      /* Error occurred while options bytes erase. ****************************/
      while (1)
      {
        /* Make LED2 blink (100ms on, 2s off) to indicate error in Erase operation */
        BSP_LED_On(LED2);
        HAL_Delay(100);
        BSP_LED_On(LED2);
        HAL_Delay(2000);
      }
    }
    
    /* Check if there is write protected pages ********************************/
    if(ProtectedPages != 0x0)
    {
      /* Restore write protected pages */
      OptionsBytesStruct.OptionType = OPTIONBYTE_WRP;
      OptionsBytesStruct.WRPState = WRPSTATE_ENABLE;
      OptionsBytesStruct.WRPPage = ProtectedPages;
      if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
      {
        /* Error occurred while options bytes programming. **********************/
        while (1)
        {
          /* Make LED2 blink (100ms on, 2s off) to indicate error in OB programming operation */
          BSP_LED_On(LED2);
          HAL_Delay(100);
          BSP_LED_Off(LED2);
          HAL_Delay(2000);
        }
      }
    }

    /* Generate System Reset to load the new option byte values ***************/
    HAL_FLASH_OB_Launch();
  }
#elif defined WRITE_PROTECTION_ENABLE
  /* Get current write protected pages and the new pages to be protected ******/
  ProtectedPages =  (~OptionsBytesStruct.WRPPage) | FLASH_PAGES_TO_BE_PROTECTED; 

  /* Check if desired pages are not yet write protected ***********************/
  if(((~OptionsBytesStruct.WRPPage) & FLASH_PAGES_TO_BE_PROTECTED )!= FLASH_PAGES_TO_BE_PROTECTED)
  {
    /* Erase all the option Bytes because if a program operation is 
      performed on a protected page, the Flash memory returns a 
      protection error */
    if(HAL_FLASHEx_OBErase() != HAL_OK)
    {
      /* Error occurred while options bytes erase. ****************************/
      while (1)
      {
        /* Make LED2 blink (100ms on, 2s off) to indicate error in Erase operation */
        BSP_LED_On(LED2);
        HAL_Delay(100);
        BSP_LED_Off(LED2);
        HAL_Delay(2000);
      }
    }

    /* Enable the pages write protection **************************************/
    OptionsBytesStruct.OptionType = OPTIONBYTE_WRP;
    OptionsBytesStruct.WRPState = WRPSTATE_ENABLE;
    OptionsBytesStruct.WRPPage = ProtectedPages;
    if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
    {
      /* Error occurred while options bytes programming. **********************/
      while (1)
      {
        /* Make LED2 blink (100ms on, 2s off) to indicate error in OB programming operation */
        BSP_LED_On(LED2);
        HAL_Delay(100);
        BSP_LED_Off(LED2);
        HAL_Delay(2000);
      }
    }

    /* Generate System Reset to load the new option byte values ***************/
    HAL_FLASH_OB_Launch();
  }
#endif /* WRITE_PROTECTION_DISABLE */

  /* Lock the Options Bytes *************************************************/
  HAL_FLASH_OB_Lock();

#ifdef FLASH_PAGE_PROGRAM  
  /* The selected pages are not write protected *******************************/
  if ((OptionsBytesStruct.WRPPage & FLASH_PAGES_TO_BE_PROTECTED) != 0x00)
  {
    /* Fill EraseInit structure************************************************/
    EraseInitStruct.TypeErase = TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = FLASH_USER_START_ADDR;
    EraseInitStruct.NbPages = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR)/FLASH_PAGE_SIZE;

    if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK)
    {
      /* 
        Error occurred while page erase. 
        User can add here some code to deal with this error. 
        PageError will contain the faulty page and then to know the code error on this page,
        user can call function 'HAL_FLASH_GetError()'
      */
      while (1)
      {
        /* Make LED2 blink (100ms on, 2s off) to indicate error in Erase operation */
        BSP_LED_On(LED2);
        HAL_Delay(100);
        BSP_LED_Off(LED2);
        HAL_Delay(2000);
      }
    }

    /* FLASH Half Word program of data 0x1753 at addresses defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR */
    Address = FLASH_USER_START_ADDR;
    while (Address < FLASH_USER_END_ADDR)
    {
      if (HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, Address, Data) == HAL_OK)
      {
        Address = Address + 2;
      }
      else
      {
        /* Error occurred while writing data in Flash memory. 
           User can add here some code to deal with this error */
        while (1)
        {
          /* Make LED2 blink (100ms on, 2s off) to indicate error in Write operation */
          BSP_LED_On(LED2);
          HAL_Delay(100);
          BSP_LED_Off(LED2);
          HAL_Delay(2000);
        }
      }
    }

    /* Check the correctness of written data */
    Address = FLASH_USER_START_ADDR;

    while (Address < FLASH_USER_END_ADDR)
    {
      if((*(__IO uint16_t*) Address) != Data)
      {
        MemoryProgramStatus = FAILED;
      }
      Address += 2;
    }
  }
  else
  { 
    /* Error to program the flash : The desired pages are write protected */ 
    MemoryProgramStatus = FAILED;
  }
#endif /* FLASH_PAGE_PROGRAM */

  /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();

  /*Check if there is an issue to program data*/
  if (MemoryProgramStatus == PASSED)
  {
    /* No error detected. Switch on LED2*/
    BSP_LED_On(LED2);
  }
  else
  {
    /* Error detected. LED2 will blink with 1s period */
    while (1)
    {
      BSP_LED_On(LED2);
      HAL_Delay(1000);
      BSP_LED_Off(LED2);
      HAL_Delay(1000);
    }
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #11
0
uint8_t flashProgram(uint32_t addr, uint32_t *data, uint32_t size)
/*++

Function Description:
  This function retriggers a oneshot which allows several of the protocol commands
  to be receive processed and the Variable Storage to be updated once instead of 
  after each protocol command. In addition, there are two different types of storage:
  one that is for critical information and is updated maybe only once on the 
  manufacturing floor (SPECIAL). And the other is for standard device variables and
  state information.  

Arguments:
  type - GENERIC_DATA (standard variables) or SPECIAL_DATA (manufacturing variables).

Returns: 
  NONE

--*/
{
	FLASH_EraseInitTypeDef EraseInitStruct;
	uint32_t Address = 0, *Data = 0, PageError = 0, result = 0, length = 0;
  /* Unlock the Flash to enable the flash control register access *************/
  HAL_FLASH_Unlock();

  /* Erase the user Flash area
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  /* Fill EraseInit structure*/
  EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
  EraseInitStruct.PageAddress = addr;
  EraseInitStruct.NbPages = 1;//(FLASH_USER_END_ADDR - addr) / FLASH_PAGE_SIZE;  

  if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK)
  {
    /*
      Error occurred while page erase.
      User can add here some code to deal with this error.
      PageError will contain the faulty page and then to know the code error on this page,
      user can call function 'HAL_FLASH_GetError()'
    */
    /* Infinite loop */
    return result; 
  }

  /* Program the user Flash area word by word
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  Address = addr;
  Data = data;
//  while (Address < FLASH_USER_END_ADDR)
  while (length < size)    
  { 
    if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, (uint64_t)*Data) == HAL_OK)
    {
      Address = Address + 4;
	    Data++;
      length = length +4;
    }
    else
    {
      /* Error occurred while writing data in Flash memory.
         User can add here some code to deal with this error */
      return result; 
    }
  }

  /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();
  return result=1;  
}
Example #12
0
int main(void)
{
    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

    /* Configure the system clock */
    SystemClock_Config();

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_DMA_Init();
    MX_ADC_Init();
    MX_SPI1_Init();
    MX_USB_DEVICE_Init();
    MX_TIM14_Init();

    HAL_FLASH_Unlock();
    EE_Init();

    EE_ReadVariable(VirtAddVarTab[0], &x_low_th);
    EE_ReadVariable(VirtAddVarTab[1], &x_high_th);
    EE_ReadVariable(VirtAddVarTab[2], &y_low_th);
    EE_ReadVariable(VirtAddVarTab[3], &y_high_th);

    HAL_FLASH_Lock();

    HAL_ADC_Start_DMA(&hadc, (uint32_t*)axis, 5);

    while (1)
    {
        HAL_GPIO_WritePin(SPI1_nCS_GPIO_Port, SPI1_nCS_Pin, GPIO_PIN_SET);

        HAL_TIM_Base_Start_IT(&htim14);
        while (!u100ticks) /* do nothing for 100 us */;
        HAL_TIM_Base_Stop_IT(&htim14);
        u100ticks = 0;

        HAL_StatusTypeDef status =
            HAL_SPI_Receive(&hspi1, rx_buffer, sizeof(rx_buffer), 3000);

        switch(status)
        {
        case HAL_OK:
            report.buttons[0] = 0x00;
            // report.buttons[1] = 0x00;
            report.buttons[2] = 0x00;

            if ((rx_buffer[0] & 0xff) != 0xff)   // if all bits of rx_buffer[0] is 1 assume shifter is disconnected
            {
                if (rx_buffer[0] & 4)   report.buttons[0] |= 1;         else report.buttons[0] &= ~1;
                if (rx_buffer[0] & 1)   report.buttons[0] |= (1 << 1);  else report.buttons[0] &= ~(1 << 1);
                if (rx_buffer[0] & 2)   report.buttons[0] |= (1 << 2);  else report.buttons[0] &= ~(1 << 2);
                if (rx_buffer[0] & 8)   report.buttons[0] |= (1 << 3);  else report.buttons[0] &= ~(1 << 3);

                if (rx_buffer[1] & 1)   report.buttons[2] |= 1;         else report.buttons[2] &= ~1;
                if (rx_buffer[1] & 2)   report.buttons[2] |= (1 << 1);  else report.buttons[2] &= ~(1 << 1);
                if (rx_buffer[1] & 4)   report.buttons[2] |= (1 << 2);  else report.buttons[2] &= ~(1 << 2);
                if (rx_buffer[1] & 8)   report.buttons[2] |= (1 << 3);  else report.buttons[2] &= ~(1 << 3);

                if (rx_buffer[1] & 32)  report.buttons[0] |= (1 << 4);  else report.buttons[0] &= ~(1 << 4);
                if (rx_buffer[1] & 128) report.buttons[0] |= (1 << 5);  else report.buttons[0] &= ~(1 << 5);
                if (rx_buffer[1] & 64)  report.buttons[0] |= (1 << 6);  else report.buttons[0] &= ~(1 << 6);
                if (rx_buffer[1] & 16)  report.buttons[0] |= (1 << 7);  else report.buttons[0] &= ~(1 << 7);
            }
            break;

        case HAL_TIMEOUT:
        case HAL_BUSY:
        case HAL_ERROR:
            Error_Handler();
        default:
            report.buttons[0] = 0xff;
            break;
        }

        HAL_GPIO_WritePin(SPI1_nCS_GPIO_Port, SPI1_nCS_Pin, GPIO_PIN_RESET);
        report.id = 0x01;

        x_axis = ((X_AXIS << 2) + x_axis * 96) / 100;
        y_axis = ((Y_AXIS << 2) + y_axis * 96) / 100;

        if (rx_buffer[0] & 16)
        {
            if (y_axis < y_low_th)   // stick towards player
            {
                report.buttons[1] = 128;
                report.buttons[2] &= ~(1 << 4);
            }
            else if (y_axis > y_high_th)   // stick opposite to player
            {
                report.buttons[1] = 0; // neutral
                report.buttons[2] |= (1 << 4);
            }
            else
            {
                report.buttons[1] = 0; // neutral
                report.buttons[2] &= ~(1 << 4);
            }
        }
        else
        {
            report.buttons[1] &= ~(1 << 7);
            report.buttons[2] &= ~(1 << 4);

            if (y_axis < y_low_th)   // stick towards player
            {
                if (x_axis < x_low_th)
                {
                    if (!report.buttons[1]) report.buttons[1] = 2; // 2nd gear
                }
                else if (!report.buttons[1])
                {
                    report.buttons[1] = (x_axis > x_high_th) ? ((rx_buffer[0] & 64) ? 64 : 32) : 8;
                }
            }
            else
            {
                if (y_axis > y_high_th)   // stick opposite to player
                {
                    if (x_axis < x_low_th)
                    {
                        if (!report.buttons[1]) report.buttons[1] = 1; // 1st gear
                    }
                    else if (!report.buttons[1])
                    {
                        report.buttons[1] = (x_axis > x_high_th) ? 16 : 4;
                    }
                }
                else
                {
                    report.buttons[1] = 0; // neutral
                }
            }
        }

        report.axis[0] = x_axis;
        report.axis[1] = y_axis;

        if (report2send == 2)
        {
            HAL_FLASH_Unlock();

            EE_WriteVariable(VirtAddVarTab[0], x_low_th);
            EE_WriteVariable(VirtAddVarTab[1], x_high_th);
            EE_WriteVariable(VirtAddVarTab[2], y_low_th);
            EE_WriteVariable(VirtAddVarTab[3], y_high_th);

            HAL_FLASH_Lock();
            report2send = 0;
        }

        if (hUsbDeviceFS.pClassData
                && ((USBD_HID_HandleTypeDef *)hUsbDeviceFS.pClassData)->state == HID_IDLE)
        {
            USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t *)&report, sizeof(report));
        }
    }
}
Example #13
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();

  /* Initialize LED2 */
  BSP_LED_Init(LED2);

  /* Configure the system clock to 64 MHz */
  SystemClock_Config();

  /* Unlock the Flash to enable the flash control register access *************/
  HAL_FLASH_Unlock();

  /* Erase the user Flash area
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  /* Fill EraseInit structure*/
  EraseInitStruct.TypeErase   = TYPEERASE_PAGES;
  EraseInitStruct.PageAddress = FLASH_USER_START_ADDR;
  EraseInitStruct.NbPages     = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR) / FLASH_PAGE_SIZE;

  if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)
  {
    /*
      Error occurred while page erase.
      User can add here some code to deal with this error.
      PAGEError will contain the faulty page and then to know the code error on this page,
      user can call function 'HAL_FLASH_GetError()'
    */
    /* Infinite loop */
    while (1)
    {
      /* Make LED2 blink (100ms on, 2s off) to indicate error in Erase operation */
      BSP_LED_On(LED2);
      HAL_Delay(100);
      BSP_LED_Off(LED2);
      HAL_Delay(2000);
    }
  }

  /* Program the user Flash area word by word
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  Address = FLASH_USER_START_ADDR;

  while (Address < FLASH_USER_END_ADDR)
  {
    if (HAL_FLASH_Program(TYPEPROGRAM_WORD, Address, DATA_32) == HAL_OK)
    {
      Address = Address + 4;
    }
    else
    {
      /* Error occurred while writing data in Flash memory.
         User can add here some code to deal with this error */
      while (1)
      {
        /* Make LED2 blink (100ms on, 2s off) to indicate error in Write operation */
        BSP_LED_On(LED2);
        HAL_Delay(100);
        BSP_LED_Off(LED2);
        HAL_Delay(2000);
      }
    }
  }

  /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();

  /* Check if the programmed data is OK
      MemoryProgramStatus = 0: data programmed correctly
      MemoryProgramStatus != 0: number of words not programmed correctly ******/
  Address = FLASH_USER_START_ADDR;
  MemoryProgramStatus = 0x0;

  while (Address < FLASH_USER_END_ADDR)
  {
    data32 = *(__IO uint32_t *)Address;

    if (data32 != DATA_32)
    {
      MemoryProgramStatus++;
    }
    Address = Address + 4;
  }

  /*Check if there is an issue to program data*/
  if (MemoryProgramStatus == 0)
  {
    /* No error detected. Switch on LED2*/
    BSP_LED_On(LED2);
  }
  else
  {
    /* Error detected. LED2 will blink with 1s period */
    while (1)
    {
      BSP_LED_On(LED2);
      HAL_Delay(1000);
      BSP_LED_Off(LED2);
      HAL_Delay(1000);
    }
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #14
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - 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 48 MHz */
  SystemClock_Config();

  /* Initialize LED1, LED2 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED2);
  BSP_LED_Init(LED3);
  
  /* Initialize test status */
  MemoryProgramStatus = PASSED;
  
  /* Unlock the Flash to enable the flash control register access *************/ 
  HAL_FLASH_Unlock();

  /* Unlock the Options Bytes *************************************************/
  HAL_FLASH_OB_Unlock();

  /* Get pages write protection status ****************************************/
  HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);

#ifdef WRITE_PROTECTION_DISABLE
  /* Check if desired pages are already write protected ***********************/
  if((OptionsBytesStruct.WRPPage & FLASH_PAGE_TO_BE_PROTECTED) != FLASH_PAGE_TO_BE_PROTECTED)
  {
    /* Restore write protected pages */
    OptionsBytesStruct.OptionType   = OPTIONBYTE_WRP;
    OptionsBytesStruct.WRPState     = OB_WRPSTATE_DISABLE;
    OptionsBytesStruct.WRPPage = FLASH_PAGE_TO_BE_PROTECTED;
    if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
    {
      /* Error occurred while options bytes programming. **********************/
      while (1)
      {
        BSP_LED_On(LED3);
      }
    }

    /* Generate System Reset to load the new option byte values ***************/
    HAL_FLASH_OB_Launch();
  }
#elif defined WRITE_PROTECTION_ENABLE
  /* Check if desired pages are not yet write protected ***********************/
  if(((~OptionsBytesStruct.WRPPage) & FLASH_PAGE_TO_BE_PROTECTED )!= FLASH_PAGE_TO_BE_PROTECTED)
  {
    /* Enable the pages write protection **************************************/
    OptionsBytesStruct.OptionType = OPTIONBYTE_WRP;
    OptionsBytesStruct.WRPState   = OB_WRPSTATE_ENABLE;
    OptionsBytesStruct.WRPPage    = FLASH_PAGE_TO_BE_PROTECTED;
    if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
    {
      /* Error occurred while options bytes programming. **********************/
      while (1)
      {
        BSP_LED_On(LED3);
      }
    }

    /* Generate System Reset to load the new option byte values ***************/
    HAL_FLASH_OB_Launch();
  }
#endif /* WRITE_PROTECTION_DISABLE */

  /* Lock the Options Bytes *************************************************/
  HAL_FLASH_OB_Lock();

#ifdef FLASH_PAGE_PROGRAM  
  /* The selected pages are not write protected *******************************/
  if ((OptionsBytesStruct.WRPPage & FLASH_PAGE_TO_BE_PROTECTED) != 0x00)
  {
    /* Fill EraseInit structure************************************************/
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = FLASH_USER_START_ADDR;
    EraseInitStruct.NbPages     = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR)/FLASH_PAGE_SIZE;

    if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK)
    {
      /* 
        Error occurred while page erase. 
        User can add here some code to deal with this error. 
        PageError will contain the faulty page and then to know the code error on this page,
        user can call function 'HAL_FLASH_GetError()'
      */
      while (1)
      {
        BSP_LED_On(LED3);
      }
    }

    /* FLASH Word program of DATA_32 at addresses defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR */
    Address = FLASH_USER_START_ADDR;
    while (Address < FLASH_USER_END_ADDR)
    {
      if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, DATA_32) == HAL_OK)
      {
        Address = Address + 4;
      }
      else
      {
        /* Error occurred while writing data in Flash memory. 
           User can add here some code to deal with this error */
        while (1)
        {
          BSP_LED_On(LED3);
        }
      }
    }

    /* Check the correctness of written data */
    Address = FLASH_USER_START_ADDR;

    while (Address < FLASH_USER_END_ADDR)
    {
      if((*(__IO uint32_t*) Address) != DATA_32)
      {
        MemoryProgramStatus = FAILED;
      }
      Address += 4;
    }
  }
  else
  { 
    /* The desired pages are write protected */ 
    /* Check that it is not allowed to write in this page */
    Address = FLASH_USER_START_ADDR;
    if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, DATA_32) != HAL_OK)
    {
      /* Error returned during programmation. */
      /* Check that WRPERR flag is well set */
      if (HAL_FLASH_GetError() == HAL_FLASH_ERROR_WRP) 
      {
        MemoryProgramStatus = FAILED;
      }
      else
      {
        /* Another error occurred.
           User can add here some code to deal with this error */
        while (1)
        {
          BSP_LED_On(LED3);
        }
      }
    }
    else
    {
      /* Write operation is successful. Should not occur
         User can add here some code to deal with this error */
      while (1)
      {
        BSP_LED_On(LED3);
      }
    }
  }
#endif /* FLASH_PAGE_PROGRAM */

  /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();

  /*Check if there is an issue to program data*/
  if (MemoryProgramStatus == PASSED)
  {
    /* No error detected. Switch on LED1*/
    BSP_LED_On(LED1);
  }
  else
  {
    /* Error detected. Switch on LED2*/
    BSP_LED_On(LED2);
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #15
0
uint32_t
TpmUtilClearAndProvision(
    void
    )
{
    uint32_t retVal = 0;
    ANY_OBJECT appPayloadAuthority = {0};
    ANY_OBJECT platformAuthority = {0};
    TPM2B_MAX_NV_BUFFER rawPolicy = {0};
    TPMT_SIGNATURE authorizationSignature = {0};

    if((retVal = TpmClearControl(0x00)) != TPM_RC_SUCCESS)
    {
        printf("TpmClearControl() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmClearControl() complete.\r\n");

    if((retVal = TpmClear()) != TPM_RC_SUCCESS)
    {
        printf("TpmClear() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmClear() complete.\r\n");

    if((retVal = TpmUtilCreateSrk()) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilCreateSrk() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilCreateSrk() complete.\r\n");

    if((retVal = TpmUtilCreateEk()) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilCreateEk() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilCreateEk() complete.\r\n");

    if((retVal = TpmUtilCreateCounters()) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilCreateCounters() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilCreateCounters() complete.\r\n");

    if((retVal = TpmUtilCreateAuthority("PlatformAuthority", &platformAuthority)) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilCreateAuthority(PlatformAuthority) failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilCreateAuthority(PlatformAuthority) complete.\r\n");
    persistedData.platformAuthorityName = platformAuthority.obj.name;

    if((retVal = TpmUtilCreateAuthority("AppPayloadAuthority", &appPayloadAuthority)) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilCreateAuthority(AppPayloadAuthority) failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilCreateAuthority(AppPayloadAuthority) complete.\r\n");

    if((retVal = TpmUtilBuildSamplePolicy(&appPayloadAuthority, &rawPolicy)) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilBuildSamplePolicy() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilBuildSamplePolicy() complete.\r\n");

    if((retVal = TpmUtilIssueBootPolicy(&platformAuthority, &rawPolicy, &persistedData.ekName, &authorizationSignature)) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilIssueBootPolicy() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilIssueBootPolicy() complete.\r\n");

    if((retVal = TpmUtilWriteBootPolicy(&rawPolicy, &platformAuthority.obj.publicArea, &authorizationSignature)) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilWriteBootPolicy() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilWriteBootPolicy() complete.\r\n");

    if((retVal = StartEkSeededSession()) != TPM_RC_SUCCESS)
    {
        printf("StartEkSeededSession() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("StartEkSeededSession() complete.\r\n");

    HAL_FLASH_Unlock();
    FLASH_Erase_Sector(FLASH_SECTOR_23, FLASH_VOLTAGE_RANGE_3);
    persistedData.magic = RAZORCLAMPERSISTEDDATA;
    persistedData.version = RAZORCLAMPERSISTEDVERSION;
    persistedData.size = sizeof(RazorClamPersistentDataType);
    persistedData.compoundIdentity.t.size = CryptGenerateRandom(SHA256_DIGEST_SIZE, persistedData.compoundIdentity.t.buffer);

    if((retVal = TpmUtilSignAppPayload(&appPayloadAuthority)) != TPM_RC_SUCCESS)
    {
        printf("TpmUtilSignAppPayload() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("TpmUtilSignAppPayload() complete.\r\n");

    if((retVal = SetTpmAuthValues()) != TPM_RC_SUCCESS)
    {
        printf("SetTpmAuthValues() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("SetTpmAuthValues() complete.\r\n");

    if((retVal = MeasureEventConfidential(HR_PCR + 0, persistedData.compoundIdentity.t.size, persistedData.compoundIdentity.t.buffer)) != TPM_RC_SUCCESS)
    {
        printf("MeasureEventConfidential() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }

    if((retVal = CreatePlatformDataProtectionKey()) != TPM_RC_SUCCESS)
    {
        printf("CreatePlatformDataProtectionKey() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }
    printf("CreatePlatformDataProtectionKey() complete.\r\n");

    // Encrypt the authValues to be persisted
    if(((retVal = ProtectPlatformData(persistedData.lockoutAuth.t.buffer, persistedData.lockoutAuth.t.size, NO)) != TPM_RC_SUCCESS) ||
       ((retVal = ProtectPlatformData(persistedData.endorsementAuth.t.buffer, persistedData.endorsementAuth.t.size, NO)) != TPM_RC_SUCCESS) ||
       ((retVal = ProtectPlatformData(persistedData.storageAuth.t.buffer, persistedData.storageAuth.t.size, NO)) != TPM_RC_SUCCESS))
    {
        printf("ProtectPlatformData() failed with 0x%03x.\r\n", retVal);
        goto Cleanup;
    }

    // Persist the data in flash
    for(uint32_t n = 0; n < sizeof(persistedData); n++)
    {
        if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, ADDR_FLASH_SECTOR_23 + n, ((uint8_t*)&persistedData)[n]) != HAL_OK)
        {
            printf("Flash Write Error @ 0x%08x\r\n", ADDR_FLASH_SECTOR_23 + n);
        }
    }
    HAL_FLASH_Lock();

Cleanup:
    if(platformAuthority.obj.handle != 0)
    {
        FlushContext(&platformAuthority);
    }
    if(appPayloadAuthority.obj.handle != 0)
    {
        FlushContext(&appPayloadAuthority);
    }
    if(volatileData.ekSeededSession.handle != 0)
    {
        FlushContext((ANY_OBJECT*)&volatileData.ekSeededSession);
        MemorySet(&volatileData.ekSeededSession, 0x00, sizeof(volatileData.ekSeededSession));
    }
    return retVal;
}
Example #16
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data 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.
       - Set NVIC Group Priority to 4
       - Low Level Initialization: global MSP (MCU Support Package) initialization
     */
  HAL_Init();

  /* Configure the system clock to 180 MHz */
  SystemClock_Config();

  /* Initialize LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);

  /* Unlock the Flash to enable the flash control register access *************/
  HAL_FLASH_Unlock();

  /* Erase the user Flash area
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  /* Get the 1st sector to erase */
  FirstSector = GetSector(FLASH_USER_START_ADDR);
  /* Get the number of sector to erase from 1st sector*/
  NbOfSectors = GetSector(FLASH_USER_END_ADDR) - FirstSector + 1;
  /* Fill EraseInit structure*/
  EraseInitStruct.TypeErase     = FLASH_TYPEERASE_SECTORS;
  EraseInitStruct.VoltageRange  = FLASH_VOLTAGE_RANGE_3;
  EraseInitStruct.Sector        = FirstSector;
  EraseInitStruct.NbSectors     = NbOfSectors;
  if (HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError) != HAL_OK)
  {
    /*
      Error occurred while sector erase.
      User can add here some code to deal with this error.
      SECTORError will contain the faulty sector and then to know the code error on this sector,
      user can call function 'HAL_FLASH_GetError()'
    */
    /* Infinite loop */
    while (1)
    {
      /* Make LED3 blink (1s period) to indicate error in Erase operation */
      BSP_LED_On(LED3);
      HAL_Delay(1000);
      BSP_LED_Off(LED3);
      HAL_Delay(1000);
    }
  }

  /* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache,
     you have to make sure that these data are rewritten before they are accessed during code
     execution. If this cannot be done safely, it is recommended to flush the caches by setting the
     DCRST and ICRST bits in the FLASH_CR register. */
  __HAL_FLASH_DATA_CACHE_DISABLE();
  __HAL_FLASH_INSTRUCTION_CACHE_DISABLE();

  __HAL_FLASH_DATA_CACHE_RESET();
  __HAL_FLASH_INSTRUCTION_CACHE_RESET();

  __HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
  __HAL_FLASH_DATA_CACHE_ENABLE();

  /* Program the user Flash area word by word
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  Address = FLASH_USER_START_ADDR;

  while (Address < FLASH_USER_END_ADDR)
  {
    if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, DATA_32) == HAL_OK)
    {
      Address = Address + 4;
    }
   else
    {
      /* Error occurred while writing data in Flash memory.
         User can add here some code to deal with this error */
      while (1)
      {
        /* Make LED3 blink (1s period) to indicate error in Write operation */
        BSP_LED_On(LED3);
        HAL_Delay(1000);
        BSP_LED_Off(LED3);
        HAL_Delay(1000);
      }
    }
  }

  /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();

  /* Check if the programmed data is OK
      MemoryProgramStatus = 0: data programmed correctly
      MemoryProgramStatus != 0: number of words not programmed correctly ******/
  Address = FLASH_USER_START_ADDR;
  MemoryProgramStatus = 0x0;

  while (Address < FLASH_USER_END_ADDR)
  {
    data32 = *(__IO uint32_t *)Address;

    if (data32 != DATA_32)
    {
      MemoryProgramStatus++;
    }
    Address = Address + 4;
  }

  /*Check if there is an issue to program data*/
  if (MemoryProgramStatus == 0)
  {
    /* No error detected. Switch on LED1*/
    BSP_LED_On(LED1);
  }
  else
  {
    /* Error detected. Switch on LED3*/
    BSP_LED_On(LED3);
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #17
0
/**
  * @brief  De-Initializes Memory.
  * @param  None
  * @retval 0 if operation is successeful, MAL_FAIL else.
  */
uint16_t Flash_If_DeInit(void)
{ 
  /* Lock the internal flash */
  HAL_FLASH_Lock();  
  return 0;
}
Example #18
0
// get the bank of a given flash address
static uint32_t get_bank(uint32_t addr) {
    #if defined(STM32H7)
    if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_SWAP_BANK) == 0) {
    #else
    if (READ_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_FB_MODE) == 0) {
    #endif
        // no bank swap
        if (addr < (FLASH_BASE + FLASH_BANK_SIZE)) {
            return FLASH_BANK_1;
        } else {
            return FLASH_BANK_2;
        }
    } else {
        // bank swap
        if (addr < (FLASH_BASE + FLASH_BANK_SIZE)) {
            return FLASH_BANK_2;
        } else {
            return FLASH_BANK_1;
        }
    }
}

#if (defined(STM32L4) && defined(SYSCFG_MEMRMP_FB_MODE))
// get the page of a given flash address
static uint32_t get_page(uint32_t addr) {
    if (addr < (FLASH_BASE + FLASH_BANK_SIZE)) {
        // bank 1
        return (addr - FLASH_BASE) / FLASH_PAGE_SIZE;
    } else {
        // bank 2
        return (addr - (FLASH_BASE + FLASH_BANK_SIZE)) / FLASH_PAGE_SIZE;
    }
}
#endif

#elif defined(STM32L4) && !defined(SYSCFG_MEMRMP_FB_MODE)

static uint32_t get_page(uint32_t addr) {
    return (addr - FLASH_BASE) / FLASH_PAGE_SIZE;
}

#endif

uint32_t flash_get_sector_info(uint32_t addr, uint32_t *start_addr, uint32_t *size) {
    if (addr >= flash_layout[0].base_address) {
        uint32_t sector_index = 0;
        for (int i = 0; i < MP_ARRAY_SIZE(flash_layout); ++i) {
            for (int j = 0; j < flash_layout[i].sector_count; ++j) {
                uint32_t sector_start_next = flash_layout[i].base_address
                    + (j + 1) * flash_layout[i].sector_size;
                if (addr < sector_start_next) {
                    if (start_addr != NULL) {
                        *start_addr = flash_layout[i].base_address
                            + j * flash_layout[i].sector_size;
                    }
                    if (size != NULL) {
                        *size = flash_layout[i].sector_size;
                    }
                    return sector_index;
                }
                ++sector_index;
            }
        }
    }
    return 0;
}

void flash_erase(uint32_t flash_dest, uint32_t num_word32) {
    // check there is something to write
    if (num_word32 == 0) {
        return;
    }

    // unlock
    HAL_FLASH_Unlock();

    FLASH_EraseInitTypeDef EraseInitStruct;

    #if defined(STM32F0)
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR);
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = flash_dest;
    EraseInitStruct.NbPages     = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
    #elif  (defined(STM32L4) && !defined(SYSCFG_MEMRMP_FB_MODE))
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.Page        = get_page(flash_dest);
    EraseInitStruct.NbPages     = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE;
    #elif defined(STM32L4)
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);

    // erase the sector(s)
    // The sector returned by flash_get_sector_info can not be used
    // as the flash has on each bank 0/1 pages 0..255
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.Banks       = get_bank(flash_dest);
    EraseInitStruct.Page        = get_page(flash_dest);
    EraseInitStruct.NbPages     = get_page(flash_dest + 4 * num_word32 - 1) - EraseInitStruct.Page + 1;;
    #else
    // Clear pending flags (if any)
    #if defined(STM32H7)
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS_BANK1 | FLASH_FLAG_ALL_ERRORS_BANK2);
    #else
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
                           FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
    #endif

    // erase the sector(s)
    EraseInitStruct.TypeErase = TYPEERASE_SECTORS;
    EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V
    #if defined(STM32H7)
    EraseInitStruct.Banks = get_bank(flash_dest);
    #endif
    EraseInitStruct.Sector = flash_get_sector_info(flash_dest, NULL, NULL);
    EraseInitStruct.NbSectors = flash_get_sector_info(flash_dest + 4 * num_word32 - 1, NULL, NULL) - EraseInitStruct.Sector + 1;
    #endif

    uint32_t SectorError = 0;
    if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) {
        // error occurred during sector erase
        HAL_FLASH_Lock(); // lock the flash
        return;
    }
}

/*
// erase the sector using an interrupt
void flash_erase_it(uint32_t flash_dest, uint32_t num_word32) {
    // check there is something to write
    if (num_word32 == 0) {
        return;
    }

    // unlock
    HAL_FLASH_Unlock();

    // Clear pending flags (if any)
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
                           FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR);

    // erase the sector(s)
    FLASH_EraseInitTypeDef EraseInitStruct;
    EraseInitStruct.TypeErase = TYPEERASE_SECTORS;
    EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V
    EraseInitStruct.Sector = flash_get_sector_info(flash_dest, NULL, NULL);
    EraseInitStruct.NbSectors = flash_get_sector_info(flash_dest + 4 * num_word32 - 1, NULL, NULL) - EraseInitStruct.Sector + 1;
    if (HAL_FLASHEx_Erase_IT(&EraseInitStruct) != HAL_OK) {
        // error occurred during sector erase
        HAL_FLASH_Lock(); // lock the flash
        return;
    }
}
*/

void flash_write(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32) {
    #if defined(STM32L4)

    // program the flash uint64 by uint64
    for (int i = 0; i < num_word32 / 2; i++) {
        uint64_t val = *(uint64_t*)src;
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) {
            // error occurred during flash write
            HAL_FLASH_Lock(); // lock the flash
            return;
        }
        flash_dest += 8;
        src += 2;
    }
    if ((num_word32 & 0x01) == 1) {
        uint64_t val = *(uint64_t*)flash_dest;
        val = (val & 0xffffffff00000000uL) | (*src);
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) {
            // error occurred during flash write
            HAL_FLASH_Lock(); // lock the flash
            return;
        }
    }

    #elif defined(STM32H7)

    // program the flash 256 bits at a time
    for (int i = 0; i < num_word32 / 8; i++) {
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, flash_dest, (uint64_t)(uint32_t)src) != HAL_OK) {
            // error occurred during flash write
            HAL_FLASH_Lock(); // lock the flash
            return;
        }
        flash_dest += 32;
        src += 8;
    }

    #else

    // program the flash word by word
    for (int i = 0; i < num_word32; i++) {
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, flash_dest, *src) != HAL_OK) {
            // error occurred during flash write
            HAL_FLASH_Lock(); // lock the flash
            return;
        }
        flash_dest += 4;
        src += 1;
    }

    #endif

    // lock the flash
    HAL_FLASH_Lock();
}
Example #19
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F2xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 120 MHz */
  SystemClock_Config();
  
  /* Configure TAMPER/KEY button */
  BSP_PB_Init(BUTTON_TAMPER, BUTTON_MODE_GPIO);

  /*##-1- Initialize the LCD #################################################*/
  /* Initialize the LCD */
  BSP_LCD_Init();
  
  /* Set LCD font */
  BSP_LCD_SetFont(&Font20);
   
  /*##-2- Display messages on LCD ############################################*/  
  /* Clear the LCD */ 
  BSP_LCD_Clear(LCD_COLOR_WHITE);

  /* Set the LCD Text Color */
  BSP_LCD_SetTextColor(LCD_COLOR_BLUE);  

  /* Display test name on LCD */  
  BSP_LCD_DisplayStringAtLine(0,(uint8_t*)"     Flash Write    ");
  BSP_LCD_DisplayStringAtLine(1,(uint8_t*)"   protection test  ");
  BSP_LCD_DisplayStringAtLine(2,(uint8_t*)"      Press User    ");
  BSP_LCD_DisplayStringAtLine(3,(uint8_t*)"     Tamper-button  ");

  /* Infinite loop */  
  while (1)
  {
    /* Wait for TAMPER button to be pushed */
    while(BSP_PB_GetState(BUTTON_TAMPER) != RESET)
    {
    }
    
    /* Get FLASH_WRP_SECTORS write protection status */
    HAL_FLASHEx_OBGetConfig(&OBInit);
    SectorsWRPStatus = OBInit.WRPSector & FLASH_WRP_SECTORS;
    
    if (SectorsWRPStatus == 0)
    {
      /* If FLASH_WRP_SECTORS are write protected, disable the write protection */
      
      /* Allow Access to option bytes sector */ 
      HAL_FLASH_OB_Unlock();
    
      /* Allow Access to Flash control registers and user Flash */
      HAL_FLASH_Unlock();
      
      /* Disable FLASH_WRP_SECTORS write protection */
      OBInit.OptionType = OPTIONBYTE_WRP;
      OBInit.WRPState   = OB_WRPSTATE_DISABLE;
      OBInit.Banks      = FLASH_BANK_1;
      OBInit.WRPSector  = FLASH_WRP_SECTORS;
      HAL_FLASHEx_OBProgram(&OBInit); 
      
      /* Start the Option Bytes programming process */  
      if (HAL_FLASH_OB_Launch() != HAL_OK)
      {
        /* User can add here some code to deal with this error */
        while (1)
        {
        }
      }
      
      /* Prevent Access to option bytes sector */ 
      HAL_FLASH_OB_Lock();
    
      /* Disable the Flash option control register access (recommended to protect 
      the option Bytes against possible unwanted operations) */
      HAL_FLASH_Lock();
      
      /* Get FLASH_WRP_SECTORS write protection status */
      HAL_FLASHEx_OBGetConfig(&OBInit);
      SectorsWRPStatus = OBInit.WRPSector & FLASH_WRP_SECTORS;
      
      /* Check if FLASH_WRP_SECTORS write protection is disabled */
      if (SectorsWRPStatus == FLASH_WRP_SECTORS)
      {
         /* Set the LCD Text Color */
         BSP_LCD_SetTextColor(LCD_COLOR_GREEN);  

         BSP_LCD_DisplayStringAtLine(5,(uint8_t*)"        Write         ");
         BSP_LCD_DisplayStringAtLine(6,(uint8_t*)"    protection is     ");
         BSP_LCD_DisplayStringAtLine(7,(uint8_t*)"       disabled       ");
      }
      else
      {
         /* Set the LCD Text Color */
         BSP_LCD_SetTextColor(LCD_COLOR_RED);  

         BSP_LCD_DisplayStringAtLine(5,(uint8_t*)"        Write         ");
         BSP_LCD_DisplayStringAtLine(6,(uint8_t*)"    protection is     ");
         BSP_LCD_DisplayStringAtLine(7,(uint8_t*)"     not disabled     ");
      }
    }
    else
    { /* If FLASH_WRP_SECTORS are not write protected, enable the write protection */
      
      /* Allow Access to option bytes sector */ 
      HAL_FLASH_OB_Unlock();
    
      /* Allow Access to Flash control registers and user Flash */
      HAL_FLASH_Unlock();
      
      /* Enable FLASH_WRP_SECTORS write protection */
      OBInit.OptionType = OPTIONBYTE_WRP;
      OBInit.WRPState   = OB_WRPSTATE_ENABLE;
      OBInit.Banks      = FLASH_BANK_1;
      OBInit.WRPSector  = FLASH_WRP_SECTORS;
      HAL_FLASHEx_OBProgram(&OBInit);   
      
      /* Start the Option Bytes programming process */  
      if (HAL_FLASH_OB_Launch() != HAL_OK)
      {
        /* User can add here some code to deal with this error */
        while (1)
        {
        }
      }
      
      /* Prevent Access to option bytes sector */ 
      HAL_FLASH_OB_Lock();
    
      /* Disable the Flash option control register access (recommended to protect 
      the option Bytes against possible unwanted operations) */
      HAL_FLASH_Lock();

      /* Get FLASH_WRP_SECTORS write protection status */
      HAL_FLASHEx_OBGetConfig(&OBInit);
      SectorsWRPStatus = OBInit.WRPSector & FLASH_WRP_SECTORS;      
      
      /* Check if FLASH_WRP_SECTORS are write protected */
      if (SectorsWRPStatus == 0)
      {
         /* Set the LCD Text Color */
         BSP_LCD_SetTextColor(LCD_COLOR_GREEN);  

         BSP_LCD_DisplayStringAtLine(5,(uint8_t*)"        Write         ");
         BSP_LCD_DisplayStringAtLine(6,(uint8_t*)"    protection is     ");
         BSP_LCD_DisplayStringAtLine(7,(uint8_t*)"       enabled        ");
      }
      else
      {
         /* Set the LCD Text Color */
         BSP_LCD_SetTextColor(LCD_COLOR_RED);  

         BSP_LCD_DisplayStringAtLine(5,(uint8_t*)"        Write         ");
         BSP_LCD_DisplayStringAtLine(6,(uint8_t*)"    protection is     ");
         BSP_LCD_DisplayStringAtLine(7,(uint8_t*)"       enabled        ");
      }
    }
  }
}
Example #20
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - 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.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();

  /* Initialize LED1, LED2 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED2);
  BSP_LED_Init(LED3);

  /* Configure the system clock to 72 MHz */
  SystemClock_Config();

  /* Unlock the Flash to enable the flash control register access *************/
  HAL_FLASH_Unlock();

  /* Erase the user Flash area
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  /* Fill EraseInit structure*/
  EraseInitStruct.TypeErase = TYPEERASE_PAGES;
  EraseInitStruct.PageAddress = FLASH_USER_START_ADDR;
  EraseInitStruct.NbPages = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR) / FLASH_PAGE_SIZE;

  if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK)
  {
    /*
      Error occurred while page erase.
      User can add here some code to deal with this error.
      PageError will contain the faulty page and then to know the code error on this page,
      user can call function 'HAL_FLASH_GetError()'
    */
    /* Infinite loop */
    while (1)
    {
      BSP_LED_On(LED3);
    }
  }

  /* Program the user Flash area word by word
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

  Address = FLASH_USER_START_ADDR;

  while (Address < FLASH_USER_END_ADDR)
  {
    if (HAL_FLASH_Program(TYPEPROGRAM_WORD, Address, DATA_32) == HAL_OK)
    {
      Address = Address + 4;
    }
    else
    {
      /* Error occurred while writing data in Flash memory.
         User can add here some code to deal with this error */
      while (1)
      {
        BSP_LED_On(LED3);
      }
    }
  }

  /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();

  /* Check if the programmed data is OK
      MemoryProgramStatus = 0: data programmed correctly
      MemoryProgramStatus != 0: number of words not programmed correctly ******/
  Address = FLASH_USER_START_ADDR;
  MemoryProgramStatus = 0x0;

  while (Address < FLASH_USER_END_ADDR)
  {
    data32 = *(__IO uint32_t *)Address;

    if (data32 != DATA_32)
    {
      MemoryProgramStatus++;
    }
    Address = Address + 4;
  }

  /*Check if there is an issue to program data*/
  if (MemoryProgramStatus == 0)
  {
    /* No error detected. Switch on LED1*/
    BSP_LED_On(LED1);
  }
  else
  {
    /* Error detected. Switch on LED2*/
    BSP_LED_On(LED2);
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #21
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  uint8_t  lcd_status = LCD_OK;

  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data 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.
       - Set NVIC Group Priority to 4
       - Low Level Initialization: global MSP (MCU Support Package) initialization
     */
  HAL_Init();

  /* Configure the system clock to 180 MHz */
  SystemClock_Config();

  /* Configure Tamper push-button */
  BSP_PB_Init(BUTTON_TAMPER, BUTTON_MODE_GPIO);

  /*##-1- Initialize the LCD #################################################*/
  /* Initialize the SDRAM */
  if (BSP_SDRAM_Init() != SDRAM_OK)
  {
    /* User can add here some code to deal with this error */
    while (1)
    {
    }
  }

  /* Initialize DSI LCD */
  lcd_status = BSP_LCD_Init();
  if (lcd_status != LCD_OK)
  {
    /* User can add here some code to deal with this error */
    while (1)
    {
    }
  }

  /* Set LCD Foreground Layer  */
  BSP_LCD_LayerDefaultInit(0, LCD_FB_START_ADDRESS);
  BSP_LCD_SelectLayer(0);

  /* Set LCD font */
  BSP_LCD_SetFont(&Font20);

  /*##-2- Display messages on LCD ############################################*/
  /* Clear the LCD */
  BSP_LCD_Clear(LCD_COLOR_WHITE);

  /* Set the LCD Text Color */
  BSP_LCD_SetTextColor(LCD_COLOR_BLUE);

  /* Display test name on LCD */
  BSP_LCD_DisplayStringAt(0, LINE(8),  (uint8_t *)"Flash Write", CENTER_MODE);
  BSP_LCD_DisplayStringAt(0, LINE(9),  (uint8_t *)"protection test", CENTER_MODE);
  BSP_LCD_DisplayStringAt(0, LINE(10), (uint8_t *)"Press User", CENTER_MODE);
  BSP_LCD_DisplayStringAt(0, LINE(11), (uint8_t *)"Tamper-button", CENTER_MODE);

  while (1)
  {
    /* Wait for Tamper push-button to be pushed */
    while (BSP_PB_GetState(BUTTON_TAMPER) != RESET)
    {
    }

    /* Wait for Tamper push-button to be released */
    while (BSP_PB_GetState(BUTTON_TAMPER) != SET)
    {
    }

    /* Get FLASH_WRP_SECTORS write protection status */
    HAL_FLASHEx_OBGetConfig(&OBInit);
    SectorsWRPStatus = OBInit.WRPSector & FLASH_WRP_SECTORS;

    if (SectorsWRPStatus == 0)
    {
      /* If FLASH_WRP_SECTORS are write protected, disable the write protection */

      /* Allow Access to option bytes sector */
      HAL_FLASH_OB_Unlock();

      /* Allow Access to Flash control registers and user Flash */
      HAL_FLASH_Unlock();

      /* Disable FLASH_WRP_SECTORS write protection */
      OBInit.OptionType = OPTIONBYTE_WRP;
      OBInit.WRPState   = OB_WRPSTATE_DISABLE;
      OBInit.WRPSector  = FLASH_WRP_SECTORS;
      HAL_FLASHEx_OBProgram(&OBInit);

      /* Start the Option Bytes programming process */
      if (HAL_FLASH_OB_Launch() != HAL_OK)
      {
        /* User can add here some code to deal with this error */
        while (1)
        {
        }
      }

      /* Prevent Access to option bytes sector */
      HAL_FLASH_OB_Lock();

      /* Disable the Flash option control register access (recommended to protect
      the option Bytes against possible unwanted operations) */
      HAL_FLASH_Lock();

      /* Get FLASH_WRP_SECTORS write protection status */
      HAL_FLASHEx_OBGetConfig(&OBInit);
      SectorsWRPStatus = OBInit.WRPSector & FLASH_WRP_SECTORS;

      /* Check if FLASH_WRP_SECTORS write protection is disabled */
      if (SectorsWRPStatus == FLASH_WRP_SECTORS)
      {
        /* Set the LCD Text Color */
        BSP_LCD_SetTextColor(LCD_COLOR_GREEN);

        BSP_LCD_DisplayStringAt(0, LINE(13), (uint8_t *)"Write", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(14), (uint8_t *)"protection is", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(15), (uint8_t *)"disabled", CENTER_MODE);
      }
      else
      {
        /* Set the LCD Text Color */
        BSP_LCD_SetTextColor(LCD_COLOR_RED);

        BSP_LCD_DisplayStringAt(0, LINE(13), (uint8_t *)"Write", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(14), (uint8_t *)"protection is", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(15), (uint8_t *)"not disabled", CENTER_MODE);
      }
    }
    else
    {
      /* If FLASH_WRP_SECTORS are not write protected, enable the write protection */

      /* Allow Access to option bytes sector */
      HAL_FLASH_OB_Unlock();

      /* Allow Access to Flash control registers and user Flash */
      HAL_FLASH_Unlock();

      /* Enable FLASH_WRP_SECTORS write protection */
      OBInit.OptionType = OPTIONBYTE_WRP;
      OBInit.WRPState   = OB_WRPSTATE_ENABLE;
      OBInit.WRPSector  = FLASH_WRP_SECTORS;
      HAL_FLASHEx_OBProgram(&OBInit);

      /* Start the Option Bytes programming process */
      if (HAL_FLASH_OB_Launch() != HAL_OK)
      {
        /* User can add here some code to deal with this error */
        while (1)
        {
        }
      }

      /* Prevent Access to option bytes sector */
      HAL_FLASH_OB_Lock();

      /* Disable the Flash option control register access (recommended to protect
      the option Bytes against possible unwanted operations) */
      HAL_FLASH_Lock();

      /* Get FLASH_WRP_SECTORS write protection status */
      HAL_FLASHEx_OBGetConfig(&OBInit);
      SectorsWRPStatus = OBInit.WRPSector & FLASH_WRP_SECTORS;

      /* Check if FLASH_WRP_SECTORS are write protected */
      if (SectorsWRPStatus == 0)
      {
        /* Set the LCD Text Color */
        BSP_LCD_SetTextColor(LCD_COLOR_GREEN);

        BSP_LCD_DisplayStringAt(0, LINE(13), (uint8_t *)"Write", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(14), (uint8_t *)"protection is", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(15), (uint8_t *)" enabled ", CENTER_MODE);
      }
      else
      {
        /* Set the LCD Text Color */
        BSP_LCD_SetTextColor(LCD_COLOR_RED);

        BSP_LCD_DisplayStringAt(0, LINE(13), (uint8_t *)"Write", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(14), (uint8_t *)"protection is", CENTER_MODE);
        BSP_LCD_DisplayStringAt(0, LINE(15), (uint8_t *)"not enabled", CENTER_MODE);
      }
    }
  }
}
//set word from a specific memory address: remote debug session.
void EPS_set_memory_word(uint32_t memory_address, uint32_t *memory_data){


	uint32_t flash_write_value = *memory_data;

	/* write to memory the proper status true value */
	HAL_FLASH_Unlock();
	HAL_FLASH_Program(TYPEPROGRAM_WORD, memory_address, flash_write_value);
	HAL_FLASH_Lock();

}
Example #23
-1
HAL_StatusTypeDef WriteFlash(int32_t* table, uint32_t Address, uint32_t lenth)  
{
  HAL_StatusTypeDef res;
  HAL_FLASH_Unlock();
  __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | 
                         FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); 
    /* Erase the user Flash area
  (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/
  EraseFlash(Address);
  
  for(int i=0;i<lenth;i++)
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,Address+4*i,*(table+i));
  res = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,Address+4*lenth-4,table[lenth-1]);
  HAL_FLASH_Lock(); 
  return res;
}
Example #24
-1
/**
  * @brief  Save Access Point parameters to FLASH
  * @param  None
  * @retval System_Status_t (MODULE_SUCCESS/MODULE_ERROR)
  */
System_Status_t SaveSSIDPasswordToMemory(void)
{
  System_Status_t status = MODULE_ERROR;

  /* Reset Before The data in Memory */
  status = ResetSSIDPasswordInMemory();

  if (status) {
    /* Store in Flash Memory */
    uint32_t Address = BLUEMSYS_FLASH_ADD;
    int32_t WriteIndex;

    /* Unlock the Flash to enable the flash control register access *************/
    HAL_FLASH_Unlock();

    /* Write the Magic Number */
    {
      uint32_t MagicNumber = WIFI_CHECK_SSID_KEY;
      if (HAL_FLASH_Program(TYPEPROGRAM_WORD, Address,MagicNumber) == HAL_OK) {
        Address = Address + 4;
      } else {
        printf("\r\nError while writing in FLASH");
        status = MODULE_ERROR;
      }
    }

    /* Write the Wifi */
    for (WriteIndex=0;WriteIndex<UNION_DATA_SIZE;WriteIndex++) {
      if (HAL_FLASH_Program(TYPEPROGRAM_WORD, Address,UnionWifiToken.Data[WriteIndex]) == HAL_OK){
        Address = Address + 4;
      } else {
        printf("\r\nError while writing in FLASH");
        status = MODULE_ERROR;
      }
    }

    /* Lock the Flash to disable the flash control register access (recommended
    to protect the FLASH memory against possible unwanted operation) *********/
    HAL_FLASH_Lock();

    printf("\n\rSaveSSIDPasswordToMemory OK");
  } else {
    printf("\n\rError while resetting FLASH memory");
  }

  return status;
}
Example #25
-1
HAL_StatusTypeDef
TpmUtilStorePersistedData(
    void
    )
{
    HAL_StatusTypeDef retVal = HAL_OK;
    HAL_FLASH_Unlock();
    FLASH_Erase_Sector(FLASH_SECTOR_23, FLASH_VOLTAGE_RANGE_3);
    for(uint32_t n = 0; n < sizeof(persistedData); n++)
    {
        if((retVal = HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, ADDR_FLASH_SECTOR_23 + n, ((uint8_t*)&persistedData)[n])) != HAL_OK)
        {
            printf("Flash Write Error @ 0x%08x\r\n", ADDR_FLASH_SECTOR_23 + n);
            goto Cleanup;
        }
    }
Cleanup:
    HAL_FLASH_Lock();
}
Example #26
-1
void EE_WriteVariable(EepromAddress32 virtAddress, uint32_t data)
{
	uint16_t length=EE_LastUnusedVariable;
	uint32_t address = FLASH_USER_START_ADDR;
	for (uint16_t varIndex = 0;varIndex < length;varIndex++)
	{
		uint32_t data32 = *(__IO uint32_t *)address;
		EE_storage[varIndex] = data32;
		address = address + 4;
	}
	EE_storage[virtAddress] = data; //write the new data

	HAL_FLASH_Unlock();
	/* Get the 1st page to erase */
	uint32_t FirstPage = GetPage(FLASH_USER_START_ADDR);
	/* Get the number of pages to erase from 1st page */
	uint32_t NbOfPages = GetPage(FLASH_USER_END_ADDR) - FirstPage + 1;
	/* Get the bank */
	uint32_t BankNumber = GetBank(FLASH_USER_START_ADDR);
	uint32_t PAGEError;
	/* Fill EraseInit structure*/
	FLASH_EraseInitTypeDef EraseInitStruct;
	EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
	EraseInitStruct.Banks       = BankNumber;
	EraseInitStruct.Page        = FirstPage;
	EraseInitStruct.NbPages     = NbOfPages;
	HAL_Error_Handler(HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError));
	address = FLASH_USER_START_ADDR;
	for (uint16_t varIndex = 0;varIndex < length;varIndex+=2)
	{
		uint64_t toWrite=EE_storage[varIndex];
		if (varIndex+1<length)
		{
			toWrite|= ((uint64_t)EE_storage[varIndex+1])<<32;
		}
		HAL_Error_Handler(HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, address, toWrite));
		address = address + 8;
	}
	HAL_FLASH_Lock();

}
Example #27
-1
void saveState()
{
	HAL_FLASH_Unlock();
	if (HAL_OK != erase((uint32_t) &_loader_state_addr, (uint32_t) &_loader_state_addr))
	{
		printf("Error while loader state saving: cannot erase state page. Rebooting...\n");
		reboot();
	}
	//FLASH_PageErase((uint32_t) &_loader_state_addr);
	for (uint32_t i=0; i < sizeof(LoaderState) / 4; i++)
	{
		uint32_t targetAddress = (uint32_t) &_loader_state_addr + 4*i;
		uint32_t* pWord = ((uint32_t*) &state) + i;
		if (HAL_OK != HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, targetAddress, *pWord))
		{
			printf("Error while loader state saving: cannot program state page. Rebooting...\n");
			reboot();
		}
	}
	HAL_FLASH_Lock();
}
Example #28
-1
uint8_t setNetworkUpgradeTarg(uint8_t targ)
  {
	uint32_t   i;  
	/*Unlock the Flash to enable the flash control register access*/ 
	HAL_FLASH_Unlock();
	/* Fill EraseInit structure ,Here just SECTOR_11 need to be erased*/
    EraseInitStruct.TypeErase = TYPEERASE_SECTORS;
    EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3;
    EraseInitStruct.Sector = FLASH_SECTOR_2;
    EraseInitStruct.NbSectors = 1;
	if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK)
	{
      /*Erase failed*/
	  printf("Set network Upgrade error\n\r");
	  return 0;
    }
	/*Program the selected FLASH area byte by byte*/
	Address = FLASH_TARG_START_ADDR;
	if (HAL_FLASH_Program(TYPEPROGRAM_BYTE, Address,targ) != HAL_OK)
	{
	  printf("Set network Upgrade error\n\r");
	  return 0; 						
	}
	/*Lock the flash to ensure the security of my program*/
	HAL_FLASH_Lock();
	Address = FLASH_TARG_START_ADDR;
	MemoryProgramStatus = 0;
	data8 = *(__IO uint8_t*)Address;
	if ( data8 != targ )
	{
	  MemoryProgramStatus++;  
	}
/*Check if there is an issue to program data*/
	if (MemoryProgramStatus != 0)
	{
	  printf("Set network Upgrade error\n\r");
	  return 0;
	}
	return 1;
  }
static int
stm32f3_flash_write(const struct hal_flash *dev, uint32_t address,
        const void *src, uint32_t num_bytes)
{
    const uint16_t *sptr;
    uint32_t i, half_words;
    int rc;

    sptr = src;
    half_words = (num_bytes + 1) / 2;

    HAL_FLASH_Unlock();
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR);

    for (i = 0, rc = HAL_OK; i < half_words && rc == HAL_OK; ++i) {
        rc = HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, address, sptr[i]);
        address += 2;
    }
    HAL_FLASH_Lock();

    return rc == HAL_OK ? 0 : rc;
}
Example #30
-1
File: main.c Project: thiemar/mucan
static void set_dfu_option_bytes(uint8_t force_bootloader) {
    FLASH_OBProgramInitTypeDef ob_cfg;
    uint8_t selected_cfg;

    HAL_FLASHEx_OBGetConfig(&ob_cfg);

    if (force_bootloader) {
        /*
        From ST AN2606, pattern 6:
        nBoot0(bit) = 0, nBoot1(bit) = 1 and nBoot0_SW(bit) = 0
        */
        selected_cfg = OB_BOOT_SEL_RESET | OB_RAM_PARITY_CHECK_RESET |
                       OB_VDDA_ANALOG_ON | OB_BOOT1_SET |
                       OB_BOOT0_RESET | OB_STDBY_NO_RST | OB_STOP_NO_RST |
                       OB_WDG_SW;
    } else {
        /* Set option bytes to the default value */
        selected_cfg = OB_BOOT_SEL_SET | OB_RAM_PARITY_CHECK_RESET |
                       OB_VDDA_ANALOG_ON | OB_BOOT1_SET |
                       OB_BOOT0_SET | OB_STDBY_NO_RST | OB_STOP_NO_RST |
                       OB_WDG_SW;
    }

    if (selected_cfg != ob_cfg.USERConfig) {
        ob_cfg.OptionType = OPTIONBYTE_USER;
        ob_cfg.USERConfig = selected_cfg;

        HAL_FLASH_Unlock();
        HAL_FLASH_OB_Unlock();
        HAL_FLASHEx_OBErase();
        HAL_FLASHEx_OBProgram(&ob_cfg);
        HAL_FLASH_OB_Lock();
        HAL_FLASH_Lock();
        HAL_FLASH_OB_Launch();
    }
}