Read/Write Flash Program Memory for PIC16F886

Compiler: Hi-Tech V9.60
Body: PIC16F886
Flash memory: 0x0000~0x1FFF

The PIC16F886 devices support reading and writing to program memory. Read operations occur at the word level (2 bytes). Write operations are performed on multiples of 4 words (8 bytes). Since write operations are erase-before-write, the erase command is not supported. The bootloader area, from 000h to 0FFh, should be write protected to prevent overwriting itself.

Function:
Read:
FLASH_READ(unsigned int Address);
 Write:
  FLASH_WRITE (unsigned int Address, unsigned int Data)

Notice:
In MPLAB SIM Mode:
Before FLASE_WRITE( ) operation, please erase the memory manually (Fill 0x3FFF),otherwise you can’t see the right data in “Program Memory Windows”

In MPLAB ICD2 Mode:
After FLASE_WRITE( ) operation, please re-read target device to update the data of  flash memory. The Address 0x1F00~0x1FFF is used on-chip resources when debugging, please don’t modify the data in this range.

 

===================================================================================================

#include "pic.h"
///////////////////////////////////////////////////////////
//Compiler: Hi-Tech V9.60
//Body: PIC16F886
//Describe: Read/Write Read/Write Flash Program Memory
//////////////////////////////////////////////////////////

const unsigned char s[9]={0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69};
unsigned int s1[9],i,RC_IF;

void interrupt isr(void)
{
 int temp;
    if(RCIF){
  temp = RCREG;
  // when get the 'r' from UART,
  //then Read the string => shift string => Write string => send the string to UART
  if(temp=='r')
   RC_IF=1;
 }
}

void Init()
{
 OSCCON=0x70; //internal RC: 8Mhz
 RC_IF=0;
 TXSTA = 0x20; //low speed BRGH:0
 RCSTA = 0x80;
 SPBRG = 12;  //baud-rate 9600,8,N,1
 CREN = 1;
 RCIE=1;
 PEIE=1;
 GIE=1;
}

main()
{
unsigned int StrAdd;
 StrAdd=s;
 Init();

 //read the string and send out to UART
 for(i=0;i<9;i++){
  s1[i]=FLASH_READ(StrAdd+i);
 }
 for(i=0;i<9;i++){
  while(!TXIF);
  TXREG=s1[i];
 }
 while(!TXIF);
 TXREG=0x0A;
 while(1){
  if(RC_IF==1){
   RC_IF=0;
   //disable interrupt during the Read/Write Read/Write Flash Program Memory
   GIE=0;

   //shift the string and write back to flash memory
   FLASH_WRITE(StrAdd+8,s1[0]);
   for(i=0;i<8;i++){
    FLASH_WRITE(StrAdd+i,s1[i+1]);
   }

   
   //read the string
   for(i=0;i<9;i++){
    s1[i]=FLASH_READ(StrAdd+i);
   }
   // Send the string out to UART
   for(i=0;i<9;i++){
    while(!TXIF);
    TXREG=s1[i];
   }
   while(!TXIF);
   TXREG=0x0A;
  }
  while(!TXIF);
  //enable interrupt
  GIE=1;
 }
}

 

文章標籤
全站熱搜
創作者介紹
創作者 iamqq 的頭像
iamqq

iAmqq

iamqq 發表在 痞客邦 留言(0) 人氣(324)