STM32 AT24CXX代码

来源:互联网 发布:社交网络电影 编辑:程序博客网 时间:2024/05/17 03:20
/***************
 ****************
 Time:2017.1.4
 Name:MichaelBeechan
 Dress:Chongqing university of science and technology
****************
****************/
#ifndef _AT24cxx_H
#define _AT24cxx_
#include "stm32f10x.h"
//#include "Systick.h"
#include "IIC.h"


#define AT24C01 127
#define AT24C02 255
#define AT24C04 511
#define AT24C08 1023
#define AT24C16 2047
#define AT24C32 4095
#define AT24C64 8191
#define AT24C128 16383
#define AT24C256 32767


#define EE_TYPE AT24C02
u8 AT24Cxx_ReadOneByte(u8 addr); //read one byte
void AT24Cxx_WriteOneByte(u8 addr,u8 dat);  //write one byte
u16 AT24Cxx_ReadTwoByte(u16 addr); //read two byte
void AT24Cxx_WriteTwoByte(u16 addr,u16 dat);  //write two byte




#endif


#include "AT24cxx.h"


u8 AT24Cxx_ReadOneByte(u8 addr) //read one byte
{
u8 temp;
I2C_Start(); //Start signal
if(EE_TYPE > AT24C16)
{
I2C_Send_Byte(0xa0); //A0,A1,A2 = 0;
I2C_Wait_Ack();
I2C_Send_Byte(addr >> 8); //I2C_Send_Byte(addr/256); send high byte
}
else 
{
I2C_Send_Byte(0xa0+(addr/256) << 1); //send device addr and data addr
}
I2C_Wait_Ack();
I2C_Send_Byte(addr%256); //low byte
I2C_Wait_Ack();

I2C_Start(); //Start signal
I2C_Send_Byte(0xa1);
I2C_Wait_Ack();
temp = I2C_Read_Byte(0);  //No ack
I2C_Stop();
return temp;
}


void AT24Cxx_WriteOneByte(u8 addr,u8 dat)  //write one byte
{
I2C_Start(); //Start signal
if(EE_TYPE > AT24C16)
{
I2C_Send_Byte(0xa0); //A0,A1,A2 = 0;
I2C_Wait_Ack();
I2C_Send_Byte(addr >> 8); //I2C_Send_Byte(addr/256); send high byte
}
else 
{
I2C_Send_Byte(0xa0+(addr/256) << 1); //send device addr and data addr
}
I2C_Wait_Ack();
I2C_Send_Byte(addr%256); //low byte
I2C_Wait_Ack();

I2C_Send_Byte(dat); 
I2C_Wait_Ack();
I2C_Stop();

delay_ms(10);
}


u16 AT24Cxx_ReadTwoByte(u16 addr) //read two byte
{
u16 temp;
I2C_Start(); //Start signal
if(EE_TYPE > AT24C16)
{
I2C_Send_Byte(0xa0); //A0,A1,A2 = 0;
I2C_Wait_Ack();
I2C_Send_Byte(addr >> 8); //I2C_Send_Byte(addr/256); send high byte
}
else 
{
I2C_Send_Byte(0xa0+(addr/256) << 1); //send device addr and data addr
}
I2C_Wait_Ack();
I2C_Send_Byte(addr%256); //low byte
I2C_Wait_Ack();

I2C_Start(); //Start signal
I2C_Send_Byte(0xa1);
I2C_Wait_Ack();
temp = I2C_Read_Byte(1);  //ack
temp <<= 8;
temp |= I2C_Read_Byte(0);  //No ack
I2C_Stop();
return temp;
}


void AT24Cxx_WriteTwoByte(u16 addr,u16 dat)  //write two byte
{
I2C_Start(); //Start signal
if(EE_TYPE > AT24C16)
{
I2C_Send_Byte(0xa0); //A0,A1,A2 = 0;
I2C_Wait_Ack();
I2C_Send_Byte(addr >> 8); //I2C_Send_Byte(addr/256); send high byte
}
else 
{
I2C_Send_Byte(0xa0+(addr/256) << 1); //send device addr and data addr
}
I2C_Wait_Ack();
I2C_Send_Byte(addr%256); //low byte
I2C_Wait_Ack();

I2C_Send_Byte(dat >> 8); 
I2C_Wait_Ack();
I2C_Send_Byte(dat & 0xff); 
I2C_Wait_Ack();
I2C_Stop();

delay_ms(10);
}


0 0
原创粉丝点击