main.c

来自「pic30f6012I2C的程序」· C语言 代码 · 共 177 行

C
177
字号
#include "p30f6012a.h"
#define  start_cb   0x0001
#define  stop_cb    0x0004
#define  receive_cb 0x0008
#define  trans_cb   0x0000
#define  rstart_cb  0x0002
#define  ack_cb		0x0010
unsigned char datax[7];
unsigned char date;
unsigned int i_t=0;

struct Time
	{
	 unsigned char second;
	 unsigned char min;
	 unsigned char hour;
	 unsigned char date;
	 unsigned char mon;
	 unsigned char year;
     unsigned char week;
	}time;
struct Time org_time={30,17,10,8,8,9,1};



void i2c_org()
{
I2CCON=0x9020;
I2CBRG=0x0048;
}

void t_start()
{
i2c_waitForIdle();
I2CCON=I2CCON&0xffe0;
I2CCON=I2CCON|start_cb;
}

void t_stop()
{
i2c_waitForIdle();
I2CCON=I2CCON&0xffe0;
I2CCON=I2CCON|stop_cb;
}

void t_ack()
{
i2c_waitForIdle();
I2CCON=I2CCON&0xffe0;
I2CCON=I2CCON|ack_cb;
}

void t_trans()
{
i2c_waitForIdle();
I2CCON=I2CCON&0xffe0;
I2CCON=I2CCON|trans_cb;

}

void t_rstart()
{
i2c_waitForIdle();
I2CCON=I2CCON&0xffe0;
I2CCON=I2CCON|rstart_cb;

}

void t_receive()
{
i2c_waitForIdle();
I2CCON=I2CCON&0xffe0;
I2CCON=I2CCON|receive_cb;
}


void t_write(unsigned char addr,unsigned char datax)
{
 t_start();
 i2c_waitForIdle();
 I2CTRN=0xde;
while(I2CSTATbits.TRSTAT==1);
 i2c_waitForIdle();
 I2CTRN=addr;
while(I2CSTATbits.TRSTAT==1);
 i2c_waitForIdle();
 I2CTRN=datax;
while(I2CSTATbits.TRSTAT==1);

 t_stop();
}

unsigned char t_read1(unsigned char addr)
{
 unsigned char data3;
 t_start();
 i2c_waitForIdle();
 I2CTRN=0xde;
while(I2CSTATbits.TRSTAT==1);
 i2c_waitForIdle();
 I2CTRN=addr;
while(I2CSTATbits.TRSTAT==1);
 t_rstart();
 i2c_waitForIdle();
 I2CTRN=0xdf;
 i2c_waitForIdle();
//while(I2CSTATbits.TRSTAT==1);
//while((I2CCON&0x001f)!=0x0000);
 t_receive();
//while(I2CSTATbits.RBF==0);
//if(PORTGbits.RG3==0)i2c_error();
 data3=I2CRCV;
 t_ack();
 t_stop();
 return data3;
}

void t_readn(unsigned char addr,unsigned char n)
{
 unsigned char i;
 t_start();
 i2c_waitForIdle();
 I2CTRN=0xde;
 i2c_waitForIdle();
 I2CTRN=addr;
 t_rstart();
 i2c_waitForIdle();
 I2CTRN=0xdf;
for (i=0;i<n;i++) 
    {
 	 t_receive();
	 datax[i]=I2CRCV; 
 	 t_ack();
    }
 t_stop();
}
void delay() 
{ 
 unsigned int d=99; 
 while (--d); 
} 

void i2c_waitForIdle()
{
 while (( I2CCON & 0x001f ) | I2CSTATbits.TRSTAT ) {}; // wait for idle and not writing
}

void i2c_error()
{
 while(1);
}
void init_ISL1208()
{
 t_write(0x07,0x11);
 t_write(0x00,org_time.second);
 t_write(0x01,org_time.min);
 t_write(0x02,org_time.hour);
 t_write(0x03,org_time.date);
 t_write(0x04,org_time.mon);
 t_write(0x05,org_time.year);
 t_write(0x06,org_time.week);
 t_write(0x07,0x00); 
}

main()
{
 while(1
 i2c_org();
 init_ISL1208();

{

t_readn(0x00,7);

}
)
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?