#include <STM8S105C_S.h>
#define uchar unsigned char
#define uint unsigned int
#define data_out PB_DDR|=0X04;
#define data_in PB_DDR&=~0X04;
#define scl_H PB_ODR|=0X02;
#define scl_L PB_ODR&=~0X02;
#define sda_H PB_ODR|=0X04;
#define sda_L PB_ODR&=~0X04;
uchar low1,low2,high1,high2;
void wait(uint t)
{
uint x=0,y=0;
for(x=t;x>0;x--)
for(y=2000;y>0;y--)
{
_asm("NOP");
}
}
void delay1(uchar x)
{
uchar a=0,b=0;
for(a=x;a>0;a--)
for(b=100;b>0;b--);
}
void delay(void)
{
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
}
void gpio_init(void)
{
PB_DDR|=0X02;//PE1(scl)为输出,PE2(data)输入输出状态不确定
PB_CR1=0Xff;
PB_CR2=0X00;
}
void start(void)
{
data_out;
sda_H;
delay();
scl_H;
delay();
sda_L;
delay();
}
void stop(void)
{
data_out;
sda_L;
delay();
scl_H;
delay();
sda_H;
delay();
}
void respons(void)
{
uchar i=0;
sda_H;
delay();
scl_H;
delay();
data_in;
delay();
while(PB_IDR&0X04);
// i++;
scl_L;
delay();
data_out;
}
void mnack(void)
{
sda_H;
delay();
scl_H;
delay();
scl_L;
delay();
sda_L;
delay();
}
void init(void)
{
data_out;
sda_H;
delay();
scl_H;
delay();
}
void write_byte(uchar data)
{
uchar i=0;
data_out;
for(i=0;i<8;i++)
{
//scl_L;
//delay();
if(data&0x80)
{
sda_H;
delay();
scl_H;
delay();
scl_L;
delay();
}
else
{
sda_L;
delay();
scl_H;
delay();
scl_L;
delay();
}
data=data<<1;
}
sda_H;
delay();
}
uchar read_byte(void)
{
uchar i=0,data=0;
/*scl_L;
delay();
data_in;
delay();*/
for(i=0;i<8;i++)
{
// data=data<<1;
sda_H;
delay();
scl_H;
data_in;
delay();
if(PB_IDR&0x04)
{
data=(data<<1)+1;
}
else
data=data<<1;
data_out;
scl_L;
delay();
}
return data;
}
void write_add(uchar address,uchar date)
{
start();
write_byte(0xa0);
respons();
write_byte(address);
respons();
write_byte(date);
respons();
stop();
}
uchar read_add(uchar address)
{
uchar date=0;
start();
write_byte(0xa0);
respons();
write_byte(address);
respons();
start();
write_byte(0xa1);
respons();
date=read_byte();
mnack();
stop();
return date;
}
void main()
{
uchar i=0;
gpio_init();
init();
write_add(23,0xaa);
//wait(10);
delay1(50);
high1=read_add(23);
while(1);
}
编译的时候,应答无效,不知道为什么? |