下面是我编的一段程序,奇怪的是只读到传感器的高8位信号,低8位的信号总是0xff,不知道程序那里出了问题,求解!
#include <STM8S105C_S.h>
#define uchar unsigned char
#define uint unsigned int
uint date2;
uint date1;
uint lx;
#define data_out PG_DDR|=0X01
#define data_in PG_DDR&=~0X01
_Bool SCL @PG_ODR : 1; //SCL
_Bool SDA @PG_ODR : 0; //SDA
_Bool SDA_IN @PG_IDR : 0; //SDA
#define power_down 0x00
#define power_on 0x01
#define reset 0x07
#define h_resolution_mod 0x10
#define m_resolution_mod 0x13
#define l_resolution_mod 0x16
#define onetime_h 0x20
#define onetime_m 0x23
#define onetime_l 0x26
#define write_1710 0x46
#define read_1710 0x47
void delay120ms(void)
{
unsigned char a,b,c;
for(c=199;c>0;c--)
for(b=120;b>0;b--)
for(a=3;a>0;a--);
}
void gpio_init(void)
{
PG_DDR|=0X02; //PG1(SCL)为输出
PG_CR1|=0X03;
PG_CR2&=~0X03;
}
void delayus(void)
{
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
_asm("NOP");
}
void BH_start(void)
{
data_out;
SDA=1;
delayus();
SCL=1;
delayus();
SDA=0;
delayus();
}
void BH_stop(void)
{
data_out;
SDA=0;
delayus();
SCL=1;
delayus();
SDA=1;
}
void BH_respons(void)
{
uchar i;
data_in;
SDA=1;
delayus();
SCL=1;
delayus();
while((SDA_IN==1));
SCL=0;
delayus();
}
void init_BH(void)
{
data_out;
SDA=1;
delayus();
SCL=1;
delayus();
}
void BH_write_byte(uchar date)
{
uchar i,temp;
data_out;
for(i=0;i<8;i++)
{
temp=date&0x80;
SCL=0;
delayus();
SDA=temp;
delayus();
SCL=1;
delayus();
date=date<<1;
}
SCL=0;
delayus();
SDA=1;
delayus();
}
uchar BH_read_byte(void)
{
uchar i,k;
data_in;
SCL=0;
delayus();
SDA=1;
delayus();
for(i=0;i<8;i++)
{
SCL=1;
delayus();
k=(k<<1)|SDA_IN;
SCL=0;
delayus();
}
return k;
}
void write_reg(uchar address,uchar shuju)
{
BH_start();
BH_write_byte(address);
BH_respons();
BH_write_byte(shuju);
BH_respons();
BH_stop();
}
uint read_reg(uchar address)
{
uint date;
BH_start();
BH_write_byte(address);
BH_respons();
date1=BH_read_byte();
data_out;
SCL=0;
delayus();
SDA=0;
delayus();
SCL=1;
delayus();
date2=BH_read_byte();
data_out;
SCL=0;
delayus();
SDA=0;
delayus();
SCL=1;
delayus();
BH_stop();
date=date1*256+date2;
return date;
}
uint bh1710_read(void)
{
uint bh;
write_reg(write_1710,power_down);
write_reg(write_1710,power_on);
write_reg(write_1710,0x52);
write_reg(write_1710,0x78);
write_reg(write_1710,h_resolution_mod);
delay120ms();
delay120ms();
bh=read_reg(read_1710);
write_reg(write_1710,reset);
write_reg(write_1710,power_down);
return bh;
}
void main(void)
{
gpio_init();
init_BH();
while(1)
{
delay120ms();
init_BH();
lx= bh1710_read();
}
} |