//我也发一个IIC的程序吧,是IAR+24系列读写。支持24C01到24C512,直接粘贴即可以用。
#define uchar unsigned char
#define uint unsigned int
#include<iom16.h>
#include<ioavr.h>
#include<comp_a90.h>
#include"oil_include.h"
extern uchar iic_data[8];
extern volatile uchar temp_iic;
//设置IIC的延时时间
void delay_iic(void)
{
delay_1us();
}
//IIC初始化SCL SDA均为输出 "1"
void iic_init(void)
{
SETBIT(PORTIIC,SCL);
SETBIT(DDRIIC,SCL);
SETBIT(PORTIIC,SCL);
SETBIT(PORTIIC,SDA);
SETBIT(DDRIIC,SDA);
SETBIT(PORTIIC,SDA);
}
//IIC写一个字节
uchar iic_write_byte(uchar write_byte)
{
uchar i;
for(i=0;i<8;i++)
{
CLEARBIT(PORTIIC,SCL);
if(((write_byte<<i) & 0x80) == 0)CLEARBIT(PORTIIC,SDA);
else SETBIT(PORTIIC,SDA);
SETBIT(PORTIIC,SCL);
}
CLEARBIT(PORTIIC,SCL);
SETBIT(PORTIIC,SDA);
CLEARBIT(DDRIIC,SDA);
SETBIT(PORTIIC,SDA);
SETBIT(PORTIIC,SCL);
delay_1us();
i=TESTBIT(PINIIC,SDA);
CLEARBIT(PORTIIC,SCL);
SETBIT(DDRIIC,SDA);
return(i);
}
//IIC写N个字节
uchar iic_write_nbyte(uint data_address,uchar write_nbyte)
{
uchar chip_address=IIC_ADDRESS;
uchar data_addressh,data_addressl;
uchar iic_dpr=0x00;
data_addressl=data_address;
data_addressh=data_address>>8;
iic_start();
temp_iic=iic_write_byte(chip_address);
temp_iic=iic_write_byte(data_addressh);
temp_iic=iic_write_byte(data_addressl);
while(write_nbyte--)
{
temp_iic=iic_write_byte(iic_data[iic_dpr++]);
}
iic_stop();
return(temp_iic);
}
//IIC读一个字节
uchar iic_read_byte(void)
{
uchar i;
CLEARBIT(PORTIIC,SCL);
CLEARBIT(DDRIIC,SDA);
SETBIT(PORTIIC,SDA);
temp_iic=0x00;
for(i=0;i<8;i++)
{
SETBIT(PORTIIC,SCL);
if(TESTBIT(PINIIC,SDA))
{
SETBIT(temp_iic,(7-i));
}
else
{
CLEARBIT(temp_iic,(7-i));
}
CLEARBIT(PORTIIC,SCL);
}
SETBIT(DDRIIC,SDA);
return(temp_iic);
}
//IIC读N个字节
uchar iic_read_nbyte(uint data_address,uchar read_nbyte)
{
uchar chip_address=IIC_ADDRESS;
uchar data_addressh,data_addressl;
uchar iic_dpr=0x00;
data_addressl=data_address;
data_addressh=data_address>>8;
iic_start();
temp_iic=iic_write_byte(chip_address);
temp_iic=iic_write_byte(data_addressh);
temp_iic=iic_write_byte(data_addressl);
iic_start();
temp_iic=iic_write_byte(chip_address | 0x01);
while(read_nbyte--)
{
iic_data[iic_dpr++]=iic_read_byte();
if(read_nbyte != 0x00)
{
CLEARBIT(PORTIIC,SDA);
NOP;
NOP;
NOP;
NOP;
SETBIT(PORTIIC,SCL);
}
}
iic_stop();
return(temp_iic);
}
//IIC写命令
uchar iic_write_command(uchar write_byte)
{
return(0);
}
//IIC起始
uchar iic_start(void)
{
SETBIT(PORTIIC,SCL);
delay_1us();
SETBIT(PORTIIC,SDA);
SETBIT(DDRIIC,SDA);
CLEARBIT(PORTIIC,SDA);
delay_1us();
CLEARBIT(PORTIIC,SCL);
return(0);
}
//IIC结束
uchar iic_stop(void)
{
SETBIT(DDRIIC,SDA);
CLEARBIT(PORTIIC,SDA);
CLEARBIT(PORTIIC,SCL);
SETBIT(PORTIIC,SCL);
delay_1us();
SETBIT(PORTIIC,SDA);
delay_1us();
return(0);
}
|