用不了那么复杂,给你一个PIC24 的程序参考
#include <p24FJ32GA002.h>
#define USE_AND_OR // To enable AND_OR mask setting for I2C.
#include <i2c.h>
#define Fosc (16000000)
#define Fcy (Fosc/2)
//#define Fsck 400000 //400k
#define Fsck 100000 //100k
//#define I2C_BRG 79
#define I2C_BRG ((Fcy/2/Fsck)-1)
#define uchar unsigned
#define uint16 unsigned int
void __delay32(unsigned long cycles);
void DelayMS(unsigned int ms);
void i2c_init(void)
{
TRISBbits.TRISB8 = 0; // SCL1
TRISBbits.TRISB9 = 0; //SDA1
OpenI2C1( I2C_ON, I2C_BRG );
}
//写2402,值写到指定的地址
void AT2402_Write(uchar address,uchar val) //AT2402寄存器地址0-255h
{
StartI2C1(); //Send the Start Bit
IdleI2C1(); //Wait to complete
MasterWriteI2C1(0XA0); // addresses the chip
IdleI2C1();
MasterWriteI2C1(address); // mem address
IdleI2C1();
MasterWriteI2C1( val ); // write value into minutes register
IdleI2C1();
StopI2C1(); //Send the Stop condition
IdleI2C1();
}
//读2402,存储器地址的值****************************************
uchar AT2402_Read(uchar address) //AT2402存储器地址0-255h
{
uchar ret;
StartI2C1(); //Send the Start Bit
IdleI2C1(); //Wait to complete
MasterWriteI2C1(0xa0); // addresses the chip
IdleI2C1();
MasterWriteI2C1(address); // addresses the chip
IdleI2C1();
RestartI2C1(); //Send the Restart condition
__delay32(40);
IdleI2C1();
MasterWriteI2C1(0XA1); // addresses the chip
IdleI2C1();
ret = MasterReadI2C1(); // read one byte
StopI2C1(); //Send the Stop condition
IdleI2C1(); //Wait to complete
return ret;
}
#include <p24FJ32GA002.h>
#define USE_AND_OR // To enable AND_OR mask setting for I2C.
#include <i2c.h>
#define Fosc (16000000)
#define Fcy (Fosc/2)
//#define Fsck 400000 //400k
#define Fsck 100000 //100k
//#define I2C_BRG 79
#define I2C_BRG ((Fcy/2/Fsck)-1)
#define uchar unsigned
#define uint16 unsigned int
void __delay32(unsigned long cycles);
void DelayMS(unsigned int ms);
void i2c_init(void)
{
TRISBbits.TRISB8 = 0; // SCL1
TRISBbits.TRISB9 = 0; //SDA1
OpenI2C1( I2C_ON, I2C_BRG );
}
//写2402,值写到指定的地址
void AT2402_Write(uchar address,uchar val) //AT2402寄存器地址0-255h
{
StartI2C1(); //Send the Start Bit
IdleI2C1(); //Wait to complete
MasterWriteI2C1(0XA0); // addresses the chip
IdleI2C1();
MasterWriteI2C1(address); // mem address
IdleI2C1();
MasterWriteI2C1( val ); // write value into minutes register
IdleI2C1();
StopI2C1(); //Send the Stop condition
IdleI2C1();
}
//读2402,存储器地址的值****************************************
uchar AT2402_Read(uchar address) //AT2402存储器地址0-255h
{
uchar ret;
StartI2C1(); //Send the Start Bit
IdleI2C1(); //Wait to complete
MasterWriteI2C1(0xa0); // addresses the chip
IdleI2C1();
MasterWriteI2C1(address); // addresses the chip
IdleI2C1();
RestartI2C1(); //Send the Restart condition
__delay32(40);
IdleI2C1();
MasterWriteI2C1(0XA1); // addresses the chip
IdleI2C1();
ret = MasterReadI2C1(); // read one byte
StopI2C1(); //Send the Stop condition
IdleI2C1(); //Wait to complete
return ret;
}
一周热门 更多>