/*
* AD PCF8591
*
* Dy×aμçλÆ÷£¬′®¿úÖúêÖ½«êÕμ½2»í¬μÄêy¾Y
*/
#include <reg51.h>
#include <intrins.h>
typedef unsigned char uint8;
typedef unsigned int uint16;
#define SLAVEADDR 0x90 //¶¨òåÆ÷¼tμØÖ·
#define nops() do{_nop_();_nop_();_nop_();_nop_();_nop_();} while(0) //¶¨òå¿ÕÖ¸áî
sbit SCL = P2^1; //I2C ê±Öó
sbit SDA = P2^0; //I2C êy¾Y
sbit DS1302 = P2^4;
void delay(uint16 n)
{
while (n--);
}
/**
* oˉêy: i2c_start()
* 1|Äü: Æô¶ˉi2c Æeê¼DÅoÅ
*/
void i2c_start()
{
SCL = 1;
nops();
SDA = 1;
nops();
SDA = 0;
nops();
SCL = 0;
}
/**
* oˉêy: i2c_stop()
* 1|Äü: í£Ö1i2c
*/
void i2c_stop()
{
SCL = 0;
nops();
SDA = 0;
nops();
SCL = 1;
nops();
SDA = 1;
nops();
}
/**
* oˉêy: i2c_ACK(bit ck)
* 1|Äü: ckÎa1ê±·¢Ëíó|′eDÅoÅACK,
* ckÎa0ê±2»·¢ËíACK
*/
void i2c_ACK(bit ck)
{
if (ck)
SDA = 0;
else
SDA = 1;
nops();
SCL = 1;
nops();
SCL = 0;
nops();
SDA = 1;
nops();
}
/**
* oˉêy: i2c_waitACK()
* 1|Äü: ·μ»ØÎa0ê±êÕμ½ACK
* ·μ»ØÎa1ê±Ã»êÕμ½ACK
*/
bit i2c_waitACK()
{
SDA = 1;
nops();
SCL = 1;
nops();
if (SDA)
{
SCL = 0;
i2c_stop();
return 1;
}
else
{
SCL = 0;
return 0;
}
}
/**
* oˉêy: i2c_sendbyte(uint8 bt)
* 1|Äü: ½«êäèëμÄò»×Ö½úêy¾Ybt·¢Ëí
*/
void i2c_sendbyte(uint8 bt)
{
uint8 i;
for(i=0; i<8; i++)
{
if (bt & 0x80)
SDA = 1;
else
SDA = 0;
nops();
SCL = 1;
bt <<= 1;
nops();
SCL = 0;
}
}
/**
* oˉêy: i2c_recbyte( )
* 1|Äü: ′ó×üÏßéϽóêÕ1×Ö½úêy¾Y
*/
uint8 i2c_recbyte()
{
uint8 dee, i;
for (i=0; i<8; i++)
{
SCL = 1;
nops();
dee <<= 1;
if (SDA)
dee = dee | 0x01;
SCL = 0;
nops();
}
return dee;
}
/**
* oˉêy: i2c_readbyte
* êäèë: addr
* 1|Äü: ¶á3öò»×Ö½úêy¾Y
* ·μ»ØÖμ: 0->3é1| 1->꧰ü
*/
bit i2c_readbyte(uint8 com, uint8 *dat)
{
i2c_start();
i2c_sendbyte(SLAVEADDR); //μØÖ·
if (i2c_waitACK())
return 1;
i2c_sendbyte(com); //¿ØÖÆ×Ö½ú
if (i2c_waitACK())
return 1;
i2c_start();
i2c_sendbyte(SLAVEADDR+1); //μØÖ·
if (i2c_waitACK())
return 1;
*dat = i2c_recbyte(); //¶áêy¾Y
i2c_ACK(0); //òòÎaÖ»¶áò»×Ö½úêy¾Y£¬2»·¢ËíACKDÅoÅ
i2c_stop();
return 0;
}
/**
* UART3õê¼»ˉ
* 2¨ìØÂê£o9600
*/
void uart_init(void)
{
ET1=0;
TMOD = 0x21; // ¶¨ê±Æ÷11¤×÷Ôú·½ê½2£¨×Ô¶ˉÖØ×°£©
SCON = 0x50; // 10λuart£¬ÔêDí′®DD½óêü
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
}
/**
* UART ·¢Ëíò»×Ö½ú
*/
void UART_Send_Byte(uint8 dat)
{
SBUF = dat;
while (TI == 0);
TI = 0;
}
main()
{
uint8 ans;
uart_init();
DS1302 = 0;
while(1)
{
i2c_readbyte(0x42, &ans);
UART_Send_Byte(ans);
delay(50000);
}
}
|