📄 uart2iic.c
字号:
//
// www.dainau.com
//
#include <AT892051.H>
#include "intrins.h"
#define IIC_init 0xC1
#define IIC_start 0xC2
#define IIC_send 0xC3
#define IIC_read 0xC4
#define IIC_stop 0xC5
#define IIC_ack 0xC6
#define IIC_nack 0xC7
sbit ISDA = P1^0;
sbit ISCL = P1^1;
sbit LED = P1^2;
unsigned char buffcount;
unsigned char buffer[64];
void init(void);
void delay(int d);
void waitRI(int t);
char sendbyte (char c);
bit I2cSentByte(SBUF);
unsigned char I2cReceiveByte(void);
main()
{
int i;
unsigned char iicmd;
init();
while(1){
waitRI(0);
iicmd=SBUF;
RI=0;
switch (iicmd) {
case IIC_init:
ISDA = 1;
ISCL = 1;
break;
case IIC_start:
ISDA = 0;
delay(5);
ISCL = 0;
break;
case IIC_send:
waitRI(0);
iicmd=SBUF;
RI=0;
iicmd=I2cSentByte(iicmd); //out IIc
sendbyte(iicmd); //response ack to PC
break;
case IIC_read:
iicmd=sendbyte(I2cReceiveByte());
sendbyte(iicmd); //response ack to PC
break;
case IIC_stop:
ISDA = 0;
delay(5);
ISCL = 1;
delay(5);
ISDA = 1;
break;
case IIC_ack:
ISDA = 0;
delay(1);
ISCL = 1;
delay(1);
ISCL = 0;
delay(1);
ISDA = 1;
break;
case IIC_nack:
ISCL = 1;
delay(1);
ISCL = 0;
break;
default:
break;
}
}
}
void waitRI(int t)
{
if(t==0)
while(RI==0){
LED=!LED;
}
else
while(--t>0){
if(RI==1) break;
LED=!LED;
}
}
void init(void)
{
PCON = 0x80;
TMOD = 0x21;
TH1 = 0xFF;
TCON = 0x55;
SCON = 0x50;
EA=1;
ES=0;
TI=1;
}
void uartint (void) interrupt 4
{
if(TI==1){
if(RI==1){
buffer[buffcount++]=SBUF;
RI=0;
}
}
}
void delay(int d)
{
int i;
for(i=0;i<d;i++);
}
char sendbyte (char c)
{
while (!(SCON & 0x02)); /* while (!TI); */
SCON &= 0xFD; /* TI = 0 */
return (SBUF = c);
}
bit I2cSentByte(unsigned char bytedata)
{
unsigned char i;
bit ack;
for(i=0; i<8; i++)
{
bytedata=_crol_(bytedata,1);
if (bytedata & 0x01)
ISDA=1;
else
ISDA=0;
ISCL=1;
delay(1);
ISCL=0;
}
ISDA=1;
delay(1);
ISCL=1;
ack=ISDA;
delay(1);
ISCL=0;
return ack;
}
unsigned char I2cReceiveByte(void)
{
unsigned char i;
unsigned char bytedata=0;
// Receive byte (MSB first)
for(i=0; i<8; i++)
{
ISCL=1;
delay(1);
bytedata <<= 1;
if ( ISDA ) bytedata |= 0x01;
ISCL=0;
delay(1);
}
return bytedata;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -