基于C51的M25P16驱动程序
|
转载至:http://bbs.elecfans.com/blog-423957-366079.html
//-------------------------------------------------------------------------------
#ifndef _FLASH_HAL_H
#define _FLASH_HAL_H
#include <reg51.h>
#include "public.h"
sbit FLASH_SPI_CS = P3^3;
sbit FLASH_SPI_CLK = P3^4;
sbit FLASH_SPI_MOSI = P3^5;
sbit FLASH_SPI_MISO = P3^6;
void flash_init(void);
uint8 flash_read_byte(uint8 addr);
void flash_write_byte(uint8 addr,uint8 wd);
#endif
//-----------------------------------------------------------------------
#include <reg51.h>
#include "flash_hal.h"
uint8 spi_read_byte(void)
{
uint8 i,rxdata;
rxdata = 0x00;
for (i = 0;i < 8;i++)
{
rxdata = rxdata<<1;
FLASH_SPI_CLK = 1;
if (FLASH_SPI_MISO)
{
rxdata |= 0x01;
}
else
{
rxdata &= ~0x01;
}
FLASH_SPI_CLK = 0;
}
return rxdata;
}
void spi_write_byte(uint8 txdata)
{
uint8 i;
for (i = 0;i < 8;i++)
{
if (txdata&0x80)
{
FLASH_SPI_MOSI = 1;
}
else
{
FLASH_SPI_MOSI = 0;
}
FLASH_SPI_CLK = 1;
txdata = txdata<<1;
FLASH_SPI_CLK = 0;
}
}
void flash_init(void)
{
uint8 read_state = 0x00;
FLASH_SPI_CS = 0;
spi_write_byte(0x06);
FLASH_SPI_CS = 1;
while(!(read_state & 0x02))
{
FLASH_SPI_CS = 0;
spi_write_byte(0x05);
read_state = spi_read_byte();
FLASH_SPI_CS = 1;
}
read_state = 0x00;
FLASH_SPI_CS = 0;
spi_write_byte(0x01);
spi_write_byte(0x00);
FLASH_SPI_CS = 1;
FLASH_SPI_CS = 0;
spi_write_byte(0x06);
FLASH_SPI_CS = 1;
while(!(read_state & 0x02))
{
FLASH_SPI_CS = 0;
spi_write_byte(0x05);
read_state = spi_read_byte();
FLASH_SPI_CS = 1;
}
read_state = 0x01;
FLASH_SPI_CS = 0;
spi_write_byte(0xD8);
spi_write_byte(0x01);
spi_write_byte(0x00);
spi_write_byte(0x00);
FLASH_SPI_CS = 1;
while((read_state & 0x01))
{
FLASH_SPI_CS = 0;
spi_write_byte(0x05);
read_state = spi_read_byte();
FLASH_SPI_CS = 1;
}
read_state = 0x00;
}
void flash_write_byte(uint8 addr,uint8 wd)
{
uint8 read_state = 0x00;
FLASH_SPI_CS = 0;
spi_write_byte(0x06);
FLASH_SPI_CS = 1;
while(!(read_state & 0x02))
{
FLASH_SPI_CS = 0;
spi_write_byte(0x05);
read_state = spi_read_byte();
FLASH_SPI_CS = 1;
}
FLASH_SPI_CS = 0;
spi_write_byte(0x02);
spi_write_byte(0x01);
spi_write_byte(0x00);
spi_write_byte(addr);
spi_write_byte(wd);
FLASH_SPI_CS = 1;
}
uint8 flash_read_byte(uint8 addr)
{
uint8 rx_data;
FLASH_SPI_CS = 0;
spi_write_byte(0x03);
spi_write_byte(0x01);
spi_write_byte(0x00);
spi_write_byte(addr);
rx_data = spi_read_byte();
FLASH_SPI_CS = 1;
return rx_data;
}
//----------------------------------------------------------------
#include <reg51.h>
#include "flash_hal.h"
void main(void)
{
uint8 i = 0x00;
flash_init();
while ( 1 )
{
flash_write_byte(0x03,0x30);
i = flash_read_byte(0x03);
i = 0x01;
}
}