今天刚把在TI的温度传感器TMP101调试成功。这个传感器是IIC接口的,很好控制。下面是mega128的程序:
#include<iom128v.h>
#define RS_0 PORTB&=~(1<<PB2)
#define RS_1 PORTB|=(1<<PB2)
#define RW_0 PORTB&=~(1<<PB4)
#define RW_1 PORTB|=(1<<PB4)
#define E_0 PORTB&=~(1<<PB5)
#define E_1 PORTB|=(1<<PB5)
#define IIC_start() TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN)
#define IIC_wait() while(!(TWCR&(1<<TWINT)))
#define IIC_stop() TWCR=(1<<TWINT)|(1<<TWSTO)|(1<<TWEN)
#define IIC_noneack() TWCR=(1<<TWINT)|(1<<TWEN)
#define IIC_ack() TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWEA)
#define CHIPADDR 0x92
#define uint unsigned int
#define uchar unsigned char
float f_temp;
unsigned int temperature;
unsigned int d1,d2=0,T_L;
float f_temp;
void delayms(uchar ms)
{
uchar i=100;
while(ms--)
{
while(i--);
}
}
void IIC_write(uchar ad,uchar da)
{
IIC_start();
IIC_wait();
TWDR=CHIPADDR;
IIC_ack();
IIC_wait();
TWDR=ad;
IIC_ack();
IIC_wait();
TWDR=da;
IIC_ack();
IIC_wait();
IIC_stop();
delayms(3);
}
void IIC_read(uchar add)
{
IIC_start();
IIC_wait();
TWDR=CHIPADDR;
IIC_ack();
IIC_wait();
TWDR=(add);
IIC_ack();
IIC_wait();
IIC_start();
IIC_wait();
TWDR=CHIPADDR+1;
IIC_ack();
IIC_wait();
IIC_ack();
IIC_wait();
d1=TWDR;
IIC_ack();
IIC_wait();
d2=TWDR;
IIC_ack();
IIC_wait();
IIC_stop();
}
void TWI_init(void)
{
TWCR=0;
TWBR=0x02;
TWSR=0x02;
TWAR=0x02;
TWCR=0x44;
}
void delay1(void)
{
volatile int x;
for(x=5;x>0;x--);
}
void write_com(unsigned char com)
{
RS_0;
RW_0;
PORTA=com;
E_0;
delay1();
E_1;
delay1();
E_0;
}
void write_data(unsigned char dat)
{
RS_1;
RW_0;
PORTA=dat;
E_0;
delay1();
E_1;
delay1();
E_0;
}
void init_1602(void)
{
write_com(0x38);
write_com(0x0C);
write_com(0x06);
}
void write_num(unsigned int num)
{
write_data('0'+num%100/10);
write_data('0'+num%10);
}
void main(void)
{
unsigned int temp;
DDRA=0xff;
DDRB=0xff;
init_1602();
while(1)
{
TWI_init();
IIC_write(0x01,0x60);
IIC_read(0x00);
f_temp=d2*0.0625;
T_L=f_temp*10+0.5;
if(T_L>99)
{
d1++;
T_L=T_L*100;
}
write_com(0x80);
write_num(d1);
write_data('.');
write_num(T_L);
}
}
用户1569902 2011-8-4 15:06