|
#include "pic.h"
#define nop() asm("nop")
#define SCL RA4
#define SDA RA5
#define SCL_DIR TRISA4
#define SDA_DIR TRISA5
#define SCL_OUTPUT SCL_DIR=0
#define SCL_HIGH() SCL=1
#define SCL_LOW() SCL=0
#define SDA_HIGH() SDA_DIR=1
#define SDA_LOW() SDA=0; SDA_DIR=0 //以上本来是个INCLUDE文件,为了分析,我把它分解了!
extern void randomRead(char addr,char counter,char *p);
extern void writeByteIIC(char addr, char counter,char *p);
void BSTART();
void BSTART() // IIC start
{ SCL_LOW();
ADCON1=0x07; // set PORTA as digital port
SDA_HIGH();
SCL_HIGH();
SCL_DIR=0;
nop();
nop();
SDA_LOW();
nop();
nop();
SCL_LOW();
}
void BSTOP()
{
SDA_LOW();
SCL_HIGH();
nop();
nop();
SDA_HIGH();
nop();
nop();
nop();
SCL_LOW();
}
// single bit receive
bit BITIN(void)
{
static bit DQ;
SDA_HIGH(); //SDA as input
SCL_HIGH();
nop();
nop();
DQ=SDA;
SCL_LOW();
return(DQ);
}
// receive one byte from IIC device,output:value
unsigned char byteReceive(void)
{
unsigned char i,value;
for(i=8;i!=0;i--)
{ value<<=1;
if(BITIN()) value|=0x01;
}
return(value);
}
// single bit transmit
void BITOUT(unsigned char bitval)
{
if(bitval) {SDA_HIGH();}
else {SDA_LOW();}
SCL_HIGH();
nop();
nop();
nop();
SCL_LOW();
}
// signle byte transmit
void byteTrans(unsigned char val)
{
char i;
for (i=8;i!=0;i--)
{
val<<=1;
BITOUT(CARRY);
}
i=BITIN(); // recevie ACK bit
}
void randomRead(char addr,char counter,char *p)
{
BSTART();
byteTrans(0xa0); // slave addr write
byteTrans(addr);
BSTART();
byteTrans(0xa1);
for(;counter!=0;counter--)
{ *p=byteReceive();
p++;
if(counter>1)
BITOUT(0);
}
BSTOP();
}
// write byte(s) to addr
void writeByteIIC(char addr, char counter,char *p)
{ BSTART();
//testCounter=20;
byteTrans(0xa0);
byteTrans(addr);
for( ;counter!=0;counter--)
{
byteTrans(*p);
p++;
}
BSTOP();
}
//函数和函数之间都没有直接的联系都是通过间接的方式通信,想必把实参与形参发挥的较高境界。哈哈,大概看了一下觉得有用就给大家看看,希望对初学C的人有用 |
|