本文包含原理图、PCB、源代码、封装库、中英文PDF等资源
您需要 登录 才可以下载或查看,没有账号?注册会员
×
用51单片机控制TMP100芯片,读温度这个芯片用I2C通信。大神们帮我看看代码哪里错了。为什么工作不了了,刚刚测了ACL和SDA两根线说是I2C通信时序出了问题,哪位大神帮忙解决一下,小弟感激不尽。。。代码如下
#include <REG52.H>
#include <intrins.h>
#define nop() _nop_()
//-------------------------
unsigned char code table[]=
{
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71
};
sbit scl=P3^0; // SCL
sbit sda=P3^1; // SDA
sbit wela=P0^7;
sbit dula=P0^6;
static unsigned char tmp[2];//温度寄存器:tmp[0]为高八位,tmp[1]低八位。
void IIC_read(unsigned char address); //从IIC设备的地址address中读取2个字节数据
void IIC_write(unsigned char address,unsigned char info);
//向IIC设备的address地址中写入一字节数据info
void IIC_init(); //初始化子程序
void delay(unsigned char x);
void delay_ms(unsigned char n);
void IIC_init();
void start();
void stop();
void writex(unsigned char j);
//unsigned char readx();
void T_Ack();//检测回应
void S_Ack();//回应
void N_Ack();
void display(unsigned char);
void delay(unsigned char x)
{
unsigned int i;
for(i=0;i<x;i++);
_nop_();
}
void IIC_init()
{
scl=1; nop(); sda=1; nop();
}
void start()
{
sda=1; nop(); scl=1; nop(); sda=0; nop(); scl=0; nop();
}
void stop()
{
sda=0; nop(); scl=1; nop(); sda=1; nop();
}
void writex(unsigned char j)
{
unsigned char i,temp;
temp=j;
for (i=0;i<8;i++){
temp=temp<<1; scl=0; nop(); sda=CY; nop(); scl=1; nop();
}
scl=0; nop(); sda=1; nop();
}
void T_Ack()
{
scl=1;
nop();
scl=0;
nop();
}
void S_Ack()
{
sda=0;
nop();
scl=1;
nop();
scl=0;
nop();
}
void N_Ack()
{
sda=1;
nop();
scl=1;
nop();
scl=0;
nop();
}
void IIC_read(unsigned char address)
{
unsigned char x,j;
start();
writex(0x90); //器件地址,写入
T_Ack();
writex(address); //寄存器地址
T_Ack();
start();
writex(0x91); //器件地址,读出
T_Ack();
for(j=0;j<2;j++)
{
sda=1;
nop();
for (x=0;x<8;x++)
{
scl=1;
nop();
if (sda==1)
tmp[j]=(tmp[j]<<1)+1;
scl=0;
nop();
}
if(j==0)
S_Ack();
else
N_Ack();
}
stop();
delay(10);
}
void IIC_write(unsigned char address,unsigned char info)
{
start();
writex(0x90); //器件地址
T_Ack();
writex(address); //寄存器地址
T_Ack();
writex(info);
N_Ack();
stop();
delay(50);
}
void delay_ms(unsigned char n)
{
unsigned int i,j;
for(i=n;i>0;i--)
for(j=0;j<110;j++)
;
}
main ()
{
unsigned char c=0;
IIC_init();
IIC_write(0x01,0x00);//配置tmp100,精度为0.5,温度连续转换,
while(1)
{
IIC_read(0x00);
for(c=0;c<5;c++)
{
display(tmp[0]);
}
}
}
void display(unsigned char i)
{
wela=1;
P1=0xfe;
wela=0;
dula=1;
P1=table[i/10];
dula=0;
delay_ms(5);
wela=1;
P1=0xfd;
wela=0;
dula=1;
P1=table[i%10];
dula=0;
delay_ms(5);
} |
|