BH1750FVI是IIC总线协议的数字型光强度传传感器集成电路,以下是它程序:
#include “io430x14x.h”
typedef unsigned int uint;
typedef unsignedchar uchar;
#define SCL_H P3OUT |= BIT6//此IO在硬件上需求更改
#define SCL_L P3OUT &= ~BIT6
#define SDA_H P3OUT |= BIT7
#define SDA_L P3OUT &= ~BIT7
#define SDA_INP3DIR &= ~BIT7//SDA改成输入形式
#define SDA_OUT P3DIR |= BIT7//SDA变回输出形式
#define SDA_VAL P3IN&BIT7//SDA的位值
#define DataDirP4DIR
#define DataPortP4OUT
#define Busy0x80
#define CtrlDirP5DIR
#define CLR_RS P5OUT&=~BIT0//RS = P5.0
#define SET_RS P5OUT|=BIT0
#define CLR_RW P5OUT&=~BIT1//RW = P5.1
#define SET_RW P5OUT|=BIT1
#define CLR_EN P5OUT&=~BIT2//EN = P5.2
#define SET_EN P5OUT|=BIT2
#define _NOP()__no_operation()
#defineSlaveAddress0x46//界说器材在IIC总线中的从地址,依据ALTADDRESS地址引脚不同修正
//ALTADDRESS引脚接地时地址为0xA6,接电源时地址为0x3A
unsigned char ge,shi,bai,qian,wan;//显现变量
int dis_data;
uchar BUF[8];
void Delay5us(void)
{
uchar i;
for(i = 0;i < 15;i++);
_NOP();
}
void Delay5ms(void)
{
uint i=40000;
while (i != 0)
{
i–;
}
}
void delay(uint x)
{
uchar i;
while(x–)for(i=0;i<125;i++);
}
void BH1750_Start()
{
SDA_H;//拉高数据线
SCL_H;//拉高时钟线
Delay5us();//延时
SDA_L;//发生下降沿
Delay5us();//延时
SCL_L;//拉低时钟线
}
void BH1750_Stop()
{
SDA_L;//拉低数据线
SCL_H;//拉高时钟线
Delay5us();//延时
SDA_H;//发生上升沿
Delay5us();//延时
}
void BH1750_SendACK(void)
{
SDA_L;//写应对信号
_NOP();_NOP();
SCL_H;//拉高时钟线
Delay5us();//延时
SCL_L;//拉低时钟线
_NOP();_NOP();
SDA_H;
Delay5us();//延时
}
void mnack(void)
{
SDA_H;
_NOP(); _NOP();
SCL_H;
Delay5us();
SCL_L;
_NOP(); _NOP();
SDA_L;
Delay5us();
}
uchar BH1750_RecvACK()
{
uchar ack;
SDA_H;
_NOP(); _NOP();
SCL_H;
_NOP(); _NOP();
SDA_IN;
_NOP(); _NOP();
ack = SDA_VAL;//读入SDA数值
SCL_L;
Delay5us();
SDA_OUT;
if(ack)return 0;
elsereturn1;
}
void write1(void)
{
SDA_H;
//Delay5us();
SCL_H;
Delay5us();
SCL_L;
Delay5us();
}
void write0(void)
{
SDA_L;
// Delay5us();
SCL_H;
Delay5us();
SCL_L;
Delay5us();
}
void BH1750_SendByte(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{//8位计数器
if(dat&0x80)
write1();
else
write0();
dat <<= 1;//移出数据的最高位
}
BH1750_RecvACK();
}
unsigned char BH1750_RecvByte()
{
unsigned char i;
unsigned char dat = 0,flag;
SDA_H;//使能内部上拉,预备读取数据,
for (i = 0; i < 8; i++)
{//8位计数器
//SDA_H;
//Delay5us();
SCL_H;
SDA_IN;
Delay5us();
flag=SDA_VAL;
dat <<= 1;
if(flag)
dat|=0x01;
SDA_OUT;
SCL_L;
Delay5us();
}
return dat;
}
声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/fangan/257772.html