1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
#include "flash.h"

static uint32_t GetSector(uint32_t Address);


uint32_t FLASH_If_Erase(uint32_t startAddress, uint32_t endAddress)
{
    uint32_t startSector;
    uint32_t endSector;
    uint32_t SectorError;
    FLASH_EraseInitTypeDef pEraseInit;
    uint8_t sectorCount;
    uint32_t ret;

    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);

    startSector = GetSector(startAddress);
    endSector = GetSector(endAddress);
    sectorCount = endSector - startSector + 1;
    pEraseInit.TypeErase = TYPEERASE_SECTORS;
    pEraseInit.Sector = startSector;
    pEraseInit.NbSectors = sectorCount;
    pEraseInit.VoltageRange = VOLTAGE_RANGE_3;

    if (HAL_FLASHEx_Erase(&pEraseInit, &SectorError) != HAL_OK) {
        ret = FLASHIF_ERASE_ERROR;
        goto out;
    }
    ret = FLASHIF_OK;
out:
    HAL_FLASH_Lock();

    return ret;
}

uint32_t FLASH_If_Write(uint32_t FlashAddress, const uint8_t *Data, uint32_t DataLength)
{
    uint32_t i = 0;
    uint32_t dataLengthWord = DataLength / 4;
    uint32_t writeAddress = FlashAddress;
    uint32_t ret;

//	printf("addr = 0x%X, data = %s len = %d   word = %d\r\n",FlashAddress,Data,DataLength,dataLengthWord);
	
    /* Unlock the Flash to enable the flash control register access *************/
    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);

    for (i = 0; (i < dataLengthWord) && (writeAddress <= (FLASH_END_ADDRESS - 4)); i++) 
	{
        /* Device voltage range supposed to be [2.7V to 3.6V], the operation will
           be done by word */
		
//		printf("writeAddr = 0x%X   datalen = %x\r\n",writeAddress,*(uint32_t *) (Data + 4 * i));
		
        if (HAL_FLASH_Program(TYPEPROGRAM_WORD, writeAddress, *(uint32_t *) (Data + 4 * i)) == HAL_OK) 
		{
            /* Check the written value */
            if (*(uint32_t *) writeAddress != *(uint32_t *) (Data + 4 * i))
			{
                /* Flash content doesn't match SRAM content */
                ret = FLASHIF_WRITINGCTRL_ERROR;
//				printf("error 11111111111111111111111111111\r\n");
                goto out;
            }
            /* Increment FLASH destination address */
            writeAddress += 4;
        } 
		else 
		{
            /* Error occurred while writing data in Flash memory */
//			printf("error 22222222222222222222222222222\r\n");
            ret = FLASHIF_WRITING_ERROR;
            goto out;
        }
    }
	
    for (i = 0; i < DataLength % 4; i++) 
	{
//		printf("writeAddr = 0x%X   datalen = %x\r\n",writeAddress,*(uint8_t *) (Data + writeAddress - FlashAddress));
        if (HAL_FLASH_Program(TYPEPROGRAM_BYTE, writeAddress,
                              *(uint8_t *) (Data + writeAddress - FlashAddress)) == HAL_OK) 
		{
            if (*(uint8_t *) writeAddress != *(uint8_t *) (Data + writeAddress - FlashAddress)) 
			{
                ret = FLASHIF_WRITINGCTRL_ERROR;
//				printf("error 3333333333333333333333\r\n");
                goto out;
            }
            writeAddress += 1;
        } 
		else 
		{
//			printf("error 444444444444444444\r\n");
            ret = FLASHIF_WRITING_ERROR;
            goto out;
        }
    }
    ret = FLASHIF_OK;
out:
    HAL_FLASH_Lock();

    return ret;
}

//uint32_t FLASH_If_Write(uint32_t FlashAddress, const uint8_t *Data, uint32_t DataLength)
//{
//    uint32_t i = 0;
//    uint32_t dataLengthWord = DataLength / 4;
//    uint32_t writeAddress = FlashAddress;
//    uint32_t ret;

//    /* Unlock the Flash to enable the flash control register access *************/
//    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);

//    for (i = 0; (i < dataLengthWord) && (writeAddress <= (FLASH_END_ADDRESS - 4)); i++) {
//        /* Device voltage range supposed to be [2.7V to 3.6V], the operation will
//           be done by word */
//        if (HAL_FLASH_Program(TYPEPROGRAM_WORD, writeAddress, *(uint32_t *) (Data + 4 * i)) == HAL_OK) {
//            /* Check the written value */
//            if (*(uint32_t *) writeAddress != *(uint32_t *) (Data + 4 * i)) {
//                /* Flash content doesn't match SRAM content */
//                ret = FLASHIF_WRITINGCTRL_ERROR;
//                goto out;
//            }
//            /* Increment FLASH destination address */
//            writeAddress += 4;
//        } else {
//            /* Error occurred while writing data in Flash memory */
//            ret = FLASHIF_WRITING_ERROR;
//            goto out;
//        }
//    }

//    for (i = 0; i < DataLength % 4; i++) {
//        if (HAL_FLASH_Program(TYPEPROGRAM_BYTE, writeAddress,
//                              *(uint8_t *) (Data + writeAddress - FlashAddress)) == HAL_OK) {
//            if (*(uint8_t *) writeAddress != *(uint8_t *) (Data + writeAddress - FlashAddress)) {
//                ret = FLASHIF_WRITINGCTRL_ERROR;
//                goto out;
//            }
//            writeAddress += 1;
//        } else {
//            ret = FLASHIF_WRITING_ERROR;
//            goto out;
//        }
//    }
//    ret = FLASHIF_OK;
//out:
//    HAL_FLASH_Lock();

//    return ret;
//}
/**
  * @brief  Returns the write protection status of user flash area.
  * @param  None
  * @retval 0: No write protected sectors inside the user flash area
  *         1: Some sectors inside the user flash area are write protected
  */
uint16_t FLASH_If_GetWriteProtectionStatus(void)
{
    uint32_t ProtectedSECTOR = 0xFFF;
    FLASH_OBProgramInitTypeDef OptionsBytesStruct;

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

    /* Check if there are write protected sectors inside the user flash area ****/
    HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);

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

    /* Get pages already write protected ****************************************/
    ProtectedSECTOR = ~(OptionsBytesStruct.WRPSector) & FLASH_SECTOR_TO_BE_PROTECTED;

    /* Check if desired pages are already write protected ***********************/
    if (ProtectedSECTOR != 0) {
        /* Some sectors inside the user flash area are write protected */
        return FLASHIF_PROTECTION_WRPENABLED;
    } else {
        /* No write protected sectors inside the user flash area */
        return FLASHIF_PROTECTION_NONE;
    }
}

/**
  * @brief  Gets the sector of a given address
  * @param  Address: Flash address
  * @retval The sector of a given address
  */
static uint32_t GetSector(uint32_t Address)
{
    uint32_t sector = 0;

    if ((Address < ADDR_FLASH_SECTOR_1) && (Address >= ADDR_FLASH_SECTOR_0)) {
        sector = FLASH_SECTOR_0;
    } else if ((Address < ADDR_FLASH_SECTOR_2) && (Address >= ADDR_FLASH_SECTOR_1)) {
        sector = FLASH_SECTOR_1;
    } else if ((Address < ADDR_FLASH_SECTOR_3) && (Address >= ADDR_FLASH_SECTOR_2)) {
        sector = FLASH_SECTOR_2;
    } else if ((Address < ADDR_FLASH_SECTOR_4) && (Address >= ADDR_FLASH_SECTOR_3)) {
        sector = FLASH_SECTOR_3;
    } else if ((Address < ADDR_FLASH_SECTOR_5) && (Address >= ADDR_FLASH_SECTOR_4)) {
        sector = FLASH_SECTOR_4;
    } else if ((Address < ADDR_FLASH_SECTOR_6) && (Address >= ADDR_FLASH_SECTOR_5)) {
        sector = FLASH_SECTOR_5;
    } else if ((Address < ADDR_FLASH_SECTOR_7) && (Address >= ADDR_FLASH_SECTOR_6)) {
        sector = FLASH_SECTOR_6;
    } else if ((Address < ADDR_FLASH_SECTOR_8) && (Address >= ADDR_FLASH_SECTOR_7)) {
        sector = FLASH_SECTOR_7;
    } else if ((Address < ADDR_FLASH_SECTOR_9) && (Address >= ADDR_FLASH_SECTOR_8)) {
        sector = FLASH_SECTOR_8;
    } else if ((Address < ADDR_FLASH_SECTOR_10) && (Address >= ADDR_FLASH_SECTOR_9)) {
        sector = FLASH_SECTOR_9;
    } else if ((Address < ADDR_FLASH_SECTOR_11) && (Address >= ADDR_FLASH_SECTOR_10)) {
        sector = FLASH_SECTOR_10;
    } else /*(Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_11))*/
    {
        sector = FLASH_SECTOR_11;
    }
    return sector;
}

/**
  * @brief  Configure the write protection status of user flash area.
  * @param  modifier DISABLE or ENABLE the protection
  * @retval HAL_StatusTypeDef HAL_OK if change is applied.
  */
HAL_StatusTypeDef FLASH_If_WriteProtectionConfig(uint32_t modifier)
{
    uint32_t ProtectedSECTOR = 0xFFF;
    FLASH_OBProgramInitTypeDef config_new, config_old;
    HAL_StatusTypeDef result = HAL_OK;

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

    /* The parameter says whether we turn the protection on or off */
    config_new.WRPState = modifier;

    /* We want to modify only the Write protection */
    config_new.OptionType = OPTIONBYTE_WRP;

    /* No read protection, keep BOR and reset settings */
    config_new.RDPLevel = OB_RDP_LEVEL_0;
    config_new.USERConfig = config_old.USERConfig;
    /* Get pages already write protected ****************************************/
    ProtectedSECTOR = config_old.WRPSector | FLASH_SECTOR_TO_BE_PROTECTED;

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

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

    config_new.WRPSector = ProtectedSECTOR;
    result = HAL_FLASHEx_OBProgram(&config_new);

    return result;
}



//优化写flash操作,提高写入速度 
/*
注:	flash 以 Word 方式写数据时, 地址值要是 4的整数倍,不然写入出错
		  以 Byte 的方式写入对地址没要求,但写入速度较慢

例:   往 0x08080003	写入 一个 uint8_t buff[6] 的数组
	  0x08080003  地址写 buff[0];						Byte 方式写入
	  0x08080004 ~ 0x08080007 地址写 buff[1]~buff[4]	Word 方式写入
	  0x08080008  地址写 buff[5]						Byte 方式写入

*/
int8_t My_Flash_Write(uint32_t FlashAddress, const uint8_t *Data, uint32_t DataLength)
{
    uint32_t i = 0;
    uint32_t dataLengthWord = DataLength / 4;
    uint32_t writeAddress = FlashAddress;
    uint32_t ret;
	
	uint32_t dataLen = DataLength;
	uint8_t writeByteCount;			//
	
	//上锁
    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);
	
	//step 1 (地址补齐): 当传入的数据超过 四个字节 时,先判断地址是否是 4的整数倍,不是的话先以 Byte的方式 写入补齐
	if(dataLengthWord)	
	{	
		//判断地址是否是 4 的整数倍
		if(writeAddress%4)		//地址不能被 4 整除
		{
			dataLen = dataLen - 4 + (writeAddress%4); 	//更新数据长度
			writeByteCount = 4 - (writeAddress%4);		//获得要写入的单字节数
			dataLengthWord = dataLen/4;					//更新 dataLengthWord
			
			for (i = 0; i < writeByteCount; i++) 
			{
				//单次写入 一个数据									 *(uint8_t *) (Data + i) = Data[i]
				if (HAL_FLASH_Program(TYPEPROGRAM_BYTE, writeAddress,*(uint8_t *) (Data + i)) == HAL_OK) 
				{
					//写入之后读取flash 的值与数组进行比较,判断是否写入成功
					if (*(uint8_t *) writeAddress != *(uint8_t *) (Data + i)) 
					{
						ret = 1;
						goto out;
					}
					writeAddress += 1;
				} 
				else 
				{
					ret = 2;
					goto out;
				}
			}
		}
	}
	
	//一个字(四字节)写入
    for (i = 0; (i < dataLengthWord) && (writeAddress <= (FLASH_END_ADDRESS - 4)); i++) 
	{		
		//一次写入四个字节的数据											下标要加上前面 以Byte 补齐的个数
        if (HAL_FLASH_Program(TYPEPROGRAM_WORD, writeAddress, *(uint32_t *) (Data + 4 * i + writeByteCount)) == HAL_OK) 
		{
            /* Check the written value */
            if (*(uint32_t *) writeAddress != *(uint32_t *) (Data + 4 * i + writeByteCount))
			{
                /* Flash content doesn't match SRAM content */
                ret = 3;
                goto out;
            }
            /* Increment FLASH destination address */
            writeAddress += 4;
        } 
		else 
		{
            /* Error occurred while writing data in Flash memory */
            ret = 4;
            goto out;
        }
    }
	
	//剩余不足四字节的数据采用单字节写入
    for (i = 0; i < dataLen % 4; i++) 
	{
		//单次写入 一个字节 的数据
        if (HAL_FLASH_Program(TYPEPROGRAM_BYTE, writeAddress,
                              *(uint8_t *) (Data + writeAddress - FlashAddress)) == HAL_OK) 
		{
            if (*(uint8_t *) writeAddress != *(uint8_t *) (Data + writeAddress - FlashAddress)) 
			{
                ret = 1;
                goto out;
            }
            writeAddress += 1;
        } 
		else 
		{
            ret = 2;
            goto out;
        }
    }
    ret = 0;
out:
    HAL_FLASH_Lock();

    return ret;
}


//写四个字节
int8_t Flash_Write_Word(uint32_t addr, uint32_t* buff, uint32_t len)
{
    volatile HAL_StatusTypeDef FLASHStatus;
	
    uint8_t k=0;
    uint32_t Address;
	Address = addr;
	
	//要写入的数据地址超过地址限制
	if((Address+(len*4))>(FLASH_END_ADDRESS - 4))
		return 1;
	
    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);//清除所有标志
	
	for(k=0;k<len;k++)
	{
		if(HAL_FLASH_Program(TYPEPROGRAM_WORD,Address, buff[k])==HAL_OK)//写入一个字(32位)的数据入指定地址
			Address = Address + 4;//地址偏移4个字节
		else
			return 2;
	}        
	HAL_FLASH_Lock();//重新上锁,防止误写入
	
	return 0;
}


//写一个字节
int8_t Flash_Write_Byte(uint32_t addr, uint8_t *buff, uint32_t len)
{	
    uint8_t k=0;
    uint32_t Address;
    Address = addr;
	
	//要写入的数据地址超过地址限制
	if((Address+len)>(FLASH_END_ADDRESS - 1))
		return 1;
	
    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);//清除所有标志
	
	for(k=0;k<len;k++)
	{
		if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, Address, buff[k])==HAL_OK)//写入一个字节(8位)的数据入指定地址
			Address =  Address + 1;//地址偏移1个字节
		else
			return 2;
	} 
	
	HAL_FLASH_Lock();//重新上锁,防止误写入
	
	return 0;
}


/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/