c_cpp PIC16器件上的闪存
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp PIC16器件上的闪存相关的知识,希望对你有一定的参考价值。
#include <assert.h>
#include <p24Fxxxx.h>
#include <xc.h>
#include <p24FJ64GA102.h>
#include "flash.h"
BOOL __attribute__ ((address(0xA200))) flashErasePage(DWORD address)
{
assert((address & 0x3FF) == 0);
DWORD_VAL a = { address };
NVMCON = 0x4042; // Erase page
TBLPAG = a.byte.UB;
__builtin_tblwtl(a.word.LW, 0xFFFF);
__builtin_disi(5);
__builtin_write_NVM();
while(NVMCONbits.WR);
NVMCONbits.WREN = 0;
return NVMCONbits.WRERR == 0;
}
BOOL __attribute__ ((address(0xA400))) flashWriteDWORD(DWORD address, DWORD value)
{
assert((address & 0x1) == 0);
DWORD_VAL a = { address };
DWORD_VAL v = { value };
NVMCON = 0x4003; // Word write
TBLPAG = a.word.HW;
__builtin_tblwtl(a.word.LW, v.word.LW); //Write the low word to the latch
__builtin_tblwth(a.word.LW, v.word.HW); //Write the high word to the latch (8 bits of data + 8 bits of "phantom data")
__builtin_disi(5);
__builtin_write_NVM();
while (NVMCONbits.WR);
NVMCONbits.WREN = 0;
return NVMCONbits.WRERR == 0;
}
BOOL flashWriteBlock(DWORD address, const BYTE block[192])
{
assert((address & 0x7F) == 0);
unsigned int i = 0;
DWORD_VAL a = { address };
DWORD_VAL v;
NVMCON = 0x4001; // Block write
TBLPAG = a.word.HW;
while (i < 192)
{
v.byte.LB = block[i++];
v.byte.HB = block[i++];
v.byte.UB = block[i++];
__builtin_tblwtl(a.word.LW, v.word.LW); // Write the low word to the latch
__builtin_tblwth(a.word.LW, v.word.HW); // Write the high word to the latch (8 bits of data + 8 bits of "phantom data")
a.word.LW += 2;
}
asm("DISI #5");
__builtin_write_NVM();
while (NVMCONbits.WR);
NVMCONbits.WREN = 0;
return NVMCONbits.WRERR == 0;
}
DWORD __attribute__ ((address(0xA300))) flashReadDWORD(DWORD address)
{
DWORD_VAL a = { address };
DWORD_VAL res;
TBLPAG = a.word.HW;
res.word.HW = __builtin_tblrdh(a.word.LW);
res.word.LW = __builtin_tblrdl(a.word.LW);
return res.Val;
}
BOOL writeFrame(DWORD addr, BYTE* data, BYTE length) {
int i;
for (i = 0; i < length / 4; ++i) {
DWORD_VAL dw = {0};
dw.byte.LB = *data++;
dw.byte.HB = *data++;
dw.byte.UB = *data++;
data++; //Ignore the last byte because this processor work with 24 bits instructions (always 0)
if (!flashWriteDWORD(addr, dw.Val))
return FALSE;
addr += 2;
}
if((length % 4) == 1)
{
DWORD_VAL dw = {0};
dw.byte.LB = *data++;
dw.byte.HB = 0;
dw.byte.UB = 0;
if (!flashWriteDWORD(addr, dw.Val))
return FALSE;
}
if((length % 4) == 2)
{
DWORD_VAL dw = {0};
dw.byte.LB = *data++;
dw.byte.HB = *data++;
dw.byte.UB = 0;
if (!flashWriteDWORD(addr, dw.Val))
return FALSE;
}
if((length % 4) == 3)
{
DWORD_VAL dw = {0};
dw.byte.LB = *data++;
dw.byte.HB = *data++;
dw.byte.UB = *data++;;
if (!flashWriteDWORD(addr, dw.Val))
return FALSE;
}
return TRUE;
}
以上是关于c_cpp PIC16器件上的闪存的主要内容,如果未能解决你的问题,请参考以下文章