⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test0_2_pass.c

📁 SPI C51 模拟
💻 C
字号:
//   本程序主要用来测试 遥控器电路版上的 Flash 读写操作。
//Flash 型号: M250P
//容量: 4M bits
//接口方式: SPI串行接口,协议由C51程序软件模拟
//原理现象:存储一个字节,然后在读出来,正确则LED始终保持亮。
//          在Flash擦写期间,LED亮,完成后熄灭。
//
//
#include<reg51.h>
#include "test.h"

//************在时钟SCK的配合下,并串转换,由数据线SI输出*************
void WriteByte(uchar dat)
{
	uchar count;
	for(count=0;count<8;count++)
	{
		if((dat&0x80)==0x00)   //由最高位输出
		{
			SI=0;
		}
		else SI=1;
		SCK=0;							   //SPI时钟信号
		Nop();
		SCK=1;

		dat<<=1;
	}
}

//************在时钟SCK的配合下,串并转换,由数据线SO读入*************
uchar ReadByte(void)
{
	uchar count;
	uchar dat;
	dat=0x00;
	for(count=0;count<8;count++)
	{
		dat<<=1;
		SCK=0;						//时钟
		Nop();
		SCK=1;
		if(SO==1)							//读入
		{
			dat=dat|0x01;
		}
		else
		{
			dat=dat&0xfe;
		}
	}
	return dat;				// 返回收到的值
}


//************向地址为{addr2,addr1,addr0}的Flash中写入数据字节dat********
void WriteData(uchar addr2,uchar addr1,uchar addr0,uchar dat)
{
	uchar temp;
Busy:
	CS=0;
	WriteByte(0x05);
	temp=ReadByte();
	CS=1;
	if((temp&0x01)!=0x00)
	{
		goto Busy;
	}													//检查状态
	CS=0;												
	WriteByte(0x06);					//写使能指令, WREN
	CS=1;
        Nop();
	CS=0;
	WriteByte(0x02);          //页编程指令,PP
	WriteByte(addr2);
	WriteByte(addr1);
	WriteByte(addr0);         //传地址码 3 Bytes
	WriteByte(dat);           //写数据内容
	CS=1;
}

//************从地址为{addr2,addr1,addr0}的Flash中读出数据字节********
uchar ReadData(uchar addr2,uchar addr1,uchar addr0)
{
	uchar temp;
	Busy:
		CS=0;
		WriteByte(0x05);
		temp=ReadByte();
		CS=1;
		if((temp&0x01)!=0x00)
	{
		goto Busy;
	}												//检查状态
	
	CS=0;                  
	WriteByte(0x03);				//读指令,READ
	WriteByte(addr2);
	WriteByte(addr1);
	WriteByte(addr0);				//传地址码  3 Bytes
	temp=ReadByte();				// 读数据
	CS=1;
	return temp;
}

//*********************整块擦写*******************
void Bulk_erase(void)
{
 	uchar temp;
	Busy:
		CS=0;
		WriteByte(0x05);
		temp=ReadByte();
		CS=1;
		if((temp&0x01)!=0x00)
	{
		goto Busy;
	}													//检查状态
        CS=0;
	WriteByte(0x06);				//写使能指令,WREN		
	CS=1;
        Nop();
        CS=0;
        WriteByte(0xC7);       //整块擦写指令
        CS=1;       
}

//***********************主控函数,存写、读取字节***********************
void main(void)
{
	uchar temp;

//---------------检查Flash状态,是否可用------------------
Busy:
	CS=0;
	WriteByte(0x05);
	temp=ReadByte();
	CS=1;
	if((temp&0x01)!=0x00)
	{
		goto Busy;
	}
//-----------------擦——写,采用整块擦除指令,写一字节,LED亮-------
P4=0;
        Bulk_erase();
 WriteData(0x00,0x00,0x00,0x96);
P4=0xf; 
//----------------------读数据出来-------------------------
temp=0xee;
 temp=ReadData(0x00,0x00,0x00);

//----------------------判断读出数据正确与否-------------------
 if(temp==0x96)
 			while(1){P4=0x0;}
 else
		while(1){P4=0xf;}
}


//*****************延时程序**********************
void Nop(void)
{
	uchar i,j;
	for(i=0;i<100;i++)
	for(j=0;j<100;j++);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -