电路原理图如下:
#include<reg52.h>
#include<intrins.h>
#include <absacc.h>
#include <math.h>
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
sbit rs=P2^2;
sbit rw=P2^1;
sbit e =P2^0;
sbit SCL=P1^3;
sbit SDA =P1^4;
uint weight;
bit ACKFlag;
void delayms(uint z)
{
uchar i,j;
for(i=z;i>0;i--)
for(j=114;j>0;j--);
}
void write_com(uchar com)
{
rs=0;
P2=com;
delayms(1);
e=1;
delayms(1);
e=0;
}
void write_data(uchar date)
{
rs=1;
P2=date;
delayms(1);
e=1;
delayms(1);
e=0;
}
void write_string(uchar line,uchar add,uchar *p)
{
if(line==1)
write_com(0x80+add);
else
write_com(0x80+0x40+add);
while(1)
{
if(*p == '\0') break;
write_data(*p);
p++;
}
}
void init_1602()
{
rw=0;
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
delayms(1);
}
void delay5us()
{
_nop_();
}
void I2cStart()
{
SDA=1;
SCL=1;
delay5us();
SDA=0;
delay5us();
}
void I2cStop()
{
SDA=0;
delay5us();
SCL=1;
delay5us();
SDA=1;
delay5us();
}
bit ReadACK()
{
SCL=0;
SCL=0;
delay5us();
if(SDA)
{
SCL=0;
return(1);
}
else
{
SCL=0;
return(0);
}
}
void SendACK(bit i)
{
SCL=0;
if(i)
SDA=1;
else
SDA=0;
SCL=1;
delay5us();
SCL=0;
SDA=1; //释放总线 fasong yingda
}
void I2cSendByte(uchar DAT)
{
uchar i;
for(i=0;i<8;i++)
{
SCL=0;
if(DAT& 0x80 )
SDA=1;
else
SDA=0;
SCL=1;
DAT<<=1;
}
SCL=0;
SDA=1;
}
uchar I2cReadByte( )
{
uchar i, DAT;
for(i=0;i<8;i++)
{ DAT<<=1;
SCL=0;
SCL=1;
if(SDA)
DAT|=0x10;
}
return(DAT);
}
void mcp3421write(ADDR,DAT)
{
I2cStart();
I2cSendByte(0xD0+0);
if(ReadACK())
ACKFlag=1;
else
ACKFlag=0;
I2cSendByte(ADDR);
if(ReadACK())
ACKFlag=1;
else
ACKFlag=0;
I2cStop();
}
uchar mcp3421Read(void)
{
uchar v;
uchar step,temp=0;
I2cStart();
I2cSendByte(0xD0+1);
if(ReadACK())
ACKFlag=1;
else
ACKFlag=0;
for(step=0;step<3;step++)
{
temp=I2cSendByte;
if(step<2)
{
if(ReadACK())
ACKFlag=1;
else
ACKFlag=0;
}
v=(v<<8)|temp;
v&=0x03ffff;
}
if(ReadACK())
ACKFlag=1;
else
ACKFlag=0;
I2cStop();
return v;
}
uchar Get_ADC(void)
{
uchar v1=0;
mcp3421write(0x8c);
v1=mcp3421Read( )+1;
return v1;
}
void display()
{
uint y;
y=Get_ADC;
weight=((float)(y/(4.3/8.8*128*(2^24)/4.3/100)+50)*10)-5005;
write_com(0x80+0x40);
write_data(weight/10000+0x30);
write_data((weight%10000)/1000+0x30);
write_data(((weight%10000)%1000)/100+0x30);
write_data((((weight%10000)%1000)%100)/10+0x30);
write_com(0x80+0x40);
}
void main()
{
init_1602( );
delayms(10);
write_string(1,0,"welcome to use!");
write_string(2,0,"000.00kg");
while(1)
{
display();
}
}
|