发布时间:2025-10-17 11:22:28    次浏览
/**********************************硬件宏定义***********************************/#defineSelectMemory1()(PORTA=~0X01)#defineDeselectMemory1()(PORTA|=0X01)#defineClrHoldMemory1()(PORTA=~(0X012))#defineSetHoldMemory1()(PORTA|=(0X012))/***********************************初始化SPI***********************************/void SPI_Masterinit(void){PORTB=~(0x016); //set bit MISOPORTB=~0xa0; // clear bits MOSI, SCKDDRA=0xff;DDRB|=0xa0; // Set SCK, MOSI SS as outputs//SPCR=BIT(MSTR)|BIT(SPR1)|BIT(CPOL)|BIT(CPHA);SPCR=BIT(SPE)|BIT(MSTR);SPSR=0x01;}/*****************************SPI数据传递函数***********************************/void SPI_WriteByte(unsigned char data){SPDR = data; // 启动数据传输while(!(SPSR (1SPIF))); //等待传输结束}unsigned char SPI_ReadByte(void){SPDR = 0x00;while(!(SPSR (1SPIF))); // 等待接收结束return SPDR; //返回数据}/****************************** 25C256初始化*************************************/void eeprom_Init(void){SetHoldMemory1();SelectMemory1(); //片选eeprom SPI_WriteByte(0x06);DeselectMemory1(); //取消片选eeprom}/*******************************读字节函数**************************************/unsigned char ReadData(unsigned int address){unsigned char buffer;unsigned char addressH;unsigned char addressL;addressH =((unsigned char *)address)[1]; //取出双字节的高8位addressL =((unsigned char *)address)[0]; //取出双字节的低8位SelectMemory1(); //片选eepromSPI_WriteByte(0x03); //发送读eeprom指令SPI_WriteByte(addressH); //发送地址高8位SPI_WriteByte(addressL); //发送地址低8位buffer=SPI_ReadByte(); //接受8位的数据DeselectMemory1(); //取消片选eepromreturn buffer;}/*****************************写字节函数****************************************/void WriteData(unsigned int address,unsigned char data){unsigned char addressH;unsigned char addressL;SelectMemory1(); //片选eepromSPI_WriteByte(0x06); //写使能DeselectMemory1(); //取消片选eepromaddressH =((unsigned char *)address)[1]; //取出双字节的高8位addressL =((unsigned char *)address)[0]; //取出双字节的低8位SelectMemory1(); //片选eepromSPI_WriteByte(0x02); //发送写eeprom指令SPI_WriteByte(addressH); //发送地址高8位SPI_WriteByte(addressL); //发送地址低8位SPI_WriteByte(data); //发送8位的数据DeselectMemory1(); //取消片选eepromdelay_ms(5);}原文链接:http://www.eeworld.com.cn/mcu/article_2016102530858.html