ADXL345通讯程序(IIC)
0赞
发表于 7/20/2012 1:01:00 PM
阅读(4770)
如果有现成的程序模块,那么编程将会变得更加简单,而且可以直接改程序实现自己想要的功能。下面我给大家发一个ADXL345的通讯源程序。
#include//Device Address for ADXL345 //#define I2CWRITEADDR 0x3A //I2C Address for Wirte, Highing the SDO of ADXL345 //#define I2CREADADDR 0x3B //I2C Address for Read #define I2CWRITEADDR 0xA6 //I2C Address for Wirte, Grouding the SDO of ADXL345 #define I2CREADADDR 0xA7 //I2C Address for Read //I2C Process Step, Used for ADuC702X I2C Master #define I2C_IDLE 0 //I2C Idle #define I2C_WRITE_ADDRESS 1 //Write 1 Byte #define I2C_WRITE_DATA 2 //Write 2 Byte #define I2C_SET_ADDRESS 3 //Set I2C Read Register Address unsigned char I2CWriteValue; //Data to Write unsigned char ReadRegister; //data read back from register unsigned char Status = I2C_IDLE; //I2C process step, initialize with Idle unsigned char DataBuffer[8]; unsigned char CountReceiveNumber; //write "WriteValue" to "RegisterAddr" of ADXL345 void I2C_WRITE_REGISTER(unsigned char RegisterAddr, unsigned char WriteValue) { Status = I2C_WRITE_ADDRESS; //Write Device Address I2CWriteValue = WriteValue; //Set Writevalue I2C1ADR = I2CWRITEADDR; //Set device address for I2C write I2C1MTX = RegisterAddr; //Set regsiter address while(I2C_IDLE != Status) //Wait until I2C command finish {;} } // Set register address for I2C read command void I2C_SET_READ_ADDR(unsigned char RegisterAddr) { Status = I2C_SET_ADDRESS; //Set I2C read register address I2C1ADR = I2CWRITEADDR; //Set device address for I2C write I2C1MTX = RegisterAddr; //Set regsiter address while (I2C_IDLE != Status) //Wait until I2C command finish {;} } //Read register from ADXL345 void I2C_READ_REGISTER(unsigned char RegisterStartAddress, unsigned char NumberOfRegisters) { I2C1CNT = NumberOfRegisters - 1; // Read NumberOfRegisters bytes one time. CountReceiveNumber = 0; I2C_SET_READ_ADDR(RegisterStartAddress);//Set I2C read register start address Status = NumberOfRegisters; //I2C read I2C1ADR = I2CREADADDR; //Set device address for I2C read while (I2C_IDLE != Status) //Wait until I2C command finish {;} } //I2C Interrupt void FIQ_Handler(void) __fiq { // Master Transmit if(((I2C1MSTA & 0x4) == 0x4) && (Status == I2C_WRITE_ADDRESS)) //Register address has been send out, then send the configuration data { Status = I2C_WRITE_DATA; I2C1MTX = I2CWriteValue; } else if(((I2C1MSTA & 0x4) == 0x4) && (Status == I2C_WRITE_DATA))//Register data has been send out, write command finished { Status = I2C_IDLE; } else if(((I2C1MSTA & 0x4) == 0x4) && (Status == I2C_SET_ADDRESS))//Set I2C read register address finished { Status = I2C_IDLE; } // Master Receive else if (((I2C1MSTA & 0x8) == 0x8) && (Status != 0)) //Receive a byte { Status--; DataBuffer[CountReceiveNumber] = I2C1MRX; CountReceiveNumber++; } } void xl345Write(unsigned char count, unsigned char regaddr, unsigned char *buf) { unsigned char iTemp = 0; for(iTemp=0;iTemp
