NANDFLASH的关键的三个驱动函数
--参考朱有鹏ARM裸机
1、NANDFLASH的关键的三个驱动函数:
(1)NANDFLASH 的檫除的函数
(2)NANDFLASH 的编程的函数,也就是往里面写东西
(3)NANDFLASH 的读的函数,也就是往里面读数据
2、读的函数和檫除的函数:
unsigned char nand_read_status(void)
{
unsigned char ch;
int i;
// 1. 发出片选信号
nand_select_chip();
// 2. 读状态
nand_send_cmd(NAND_CMD_READ_STATUS);
for(i=0; i<10; i++);
ch = nand_read8();
// 3. 取消片选
nand_deselect_chip();
return ch;
}
// 等待就绪
void nand_wait_idle(void)
{
unsigned long i;
while( !(rNFSTAT & (1<<4)) ) //等待这个位
for(i=0; i<10; i++);
}
// 发片选
void nand_select_chip(void)
{
unsigned long i;
rNFCONT &= ~(1<<1); //当这个寄存器的位1等于0的时候,选择片选NANDFLASH
for(i=0; i<10; i++);
}
// 擦除块,参数为块号(0 ~ MAX_NAND_BLOCK-1)
int nand_block_erase(unsigned long block_num)
{
unsigned long i = 0;
// 获得row地址,即页地址
unsigned long row = block_num * NAND_BLOCK_SIZE;
// 1. 发出片选信号
nand_select_chip();
// 2. 擦除:第一个周期发命令0x60,第二个周期发块地址,第三个周期发命令0xd0
nand_send_cmd(NAND_CMD_BLOCK_ERASE_1st);
for(i=0; i<10; i++);
// Row Address A12~A19
rNFADDR = row & 0xff;
for(i=0; i<10; i++);
// Row Address A20~A27
rNFADDR = (row >> 8) & 0xff;
for(i=0; i<10; i++);
// Row Address A28~A30
rNFADDR = (row >> 16) & 0xff;
rNFSTAT |= (1<<4); // clear RnB bit
nand_send_cmd(NAND_CMD_BLOCK_ERASE_2st);
for(i=0; i<10; i++);
// 3. 等待就绪
nand_wait_idle();
// 4. 读状态
unsigned char status = nand_read_status();
if (status & 1 )
{
// statas[0] = 1,表示擦除失败,详见NAND Flash数据手册中 READ STATUS一节的描述
// 取消片选信号
nand_deselect_chip();
printf("masking bad block %d\r\n", block_num);
return -1;
}
else
{
// status[0] = 0,表示擦除成功,返回0
nand_deselect_chip();
return 0;
}
}
int nand_page_read(unsigned int pgaddr, unsigned char *buf, unsigned int length)
{
int i = 0;
// 1 发出片选信号
nand_select_chip();
// 2 写页读命令1st
nand_send_cmd(NAND_CMD_READ_1st);
// 3 写入页地址
rNFADDR = 0;
rNFADDR = 0;
rNFADDR = pgaddr&0xff;
rNFADDR = (pgaddr>>8)&0xff;
rNFADDR = (pgaddr>>16)&0xff;
// 4 clear RnB
rNFSTAT |= (1<<4);
// 5 写页读命令2st
nand_send_cmd(NAND_CMD_READ_2st);
// 6 等待空闲
nand_wait_idle();
// 7 连续读取2KB的Page main区数据 (继续读取可读出64B的spare area数据)
for (i=0; (i<NAND_PAGE_SIZE) && (length!=0); i++,length--)
*buf++ = nand_read8();
// 8 读状态
unsigned char status = nand_read_status();
if (status & 1 )
{
// 读出错,取消片选信号,返回错误码-1
nand_deselect_chip();
printf("nand random read fail\r\n");
return -1;
}
else
{
// 读正确,取消片选,返回0
nand_deselect_chip();
return 0;
}
}