/*******************************************************************************
16位I2C接口A/D芯片ADS1100驱动
*******************************************************************************/
/******************************常用TWI操作*************************************/
#define Start() (TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN))
#define Stop() (TWCR=(1<<TWINT)|(1<<TWSTO)|(1<<TWEN))
#define Wait() {while(!(TWCR&(1<<TWINT)));}
#define TestAck() (TWSR&0xf8)
#define SetAck() (TWCR|=(1<<TWEA))
#define SetNoAck() (TWCR&=~(1<<TWEA))
#define Twi() (TWCR=(1<<TWINT)|(1<<TWEN))
#define Write8Bit(x) {TWDR=(x);TWCR=(1<<TWINT)|(1<<TWEN);}
/***************************单片机TWI模块初始化********************************/
void twi_init(void)
{
TWCR= 0X00; //disable twi
TWBR= 0x00; //set bit rate
TWSR= 0x01; //set prescale
TWAR= 0x00; //set slave address
TWCR= 0x44; //enable twi
}
/*********************************启动TWI**************************************/
unsigned char I2C_start(void)
{
TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while(!(TWCR&(1<<TWINT))){};
return 1;
}
/*************主模式写入一个字节,并检查从机的应答信号(ACK)******************/
unsigned char I2C_write(unsigned char data)
{
unsigned char ack=1;
unsigned char TW_MT_SLA_ACK=0x18;
TWDR=data;
TWCR=(1<<TWINT)|(1<<TWEN);
while(!(TWCR&(1<<TWINT))){};
if((TWSR&0xF8)!=TW_MT_SLA_ACK)
ack=1;
return ack;
}
/*****************主模式读出一个字节,并可设置主机的应答信号(ACK)************/
unsigned char I2C_read(unsigned char ack)
{
if(ack) //ack置1,将返回应答信号(ack)
TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWEA); //ack置0,将不返回应答信号(nack)
else
TWCR=(1<<TWINT)|(1<<TWEN);
while(!(TWCR&(1<<TWINT))){};
return TWDR;
}
unsigned char volt_high,volt_low,define;
unsigned int i2c_volate_Read(void)
{
unsigned int volate; //为电压值
I2C_start(); //I2C启动
I2C_write(0X91); //写I2C从器件地址和写方式
volt_high = I2C_read(1); //读取ADS1100电压值高8位
volt_low = I2C_read(1); //读取ADS1100电压值低8位
define = I2C_read(0); //读取ADS1100设置参数
Stop(); //I2C停止
volate=volt_high; //将两个字节的数据整合为双字节
volate=(volate<<8);
volate+=volt_low;
return volate; //返回电压值
}
/*********************ADS1100初始化函数(死循环中要写入,防止跑飞)************/
void init_ADS1100(void)
{
I2C_start(); //I2C启动
I2C_write(0X90); //写I2C从器件地址和写方式
I2C_write(0X0f); //设置ADS1100为差分模式、分辨率为16位、8倍增益
Stop(); //I2C停止
}
|