BH1750FVI是光强度传感器,支持IIC接口。小弟最近欲做一个简单的光强度检测程序,将光强度用数码管显示出来,不过调试了好久一直无法工作。请各位大虾帮忙看下IIC的模拟哪里有错,不胜感激!
#include<msp430x14x.h> #define uchar unsigned char #define uint unsigned int #define SDA_1 P3OUT|=BIT1 // P3.1为SDA #define SDA_0 P3OUT&=~BIT1 #define SCL_1 P3OUT |= BIT0 //P3.0为SCL #define SCL_0 P3OUT &= ~BIT0 #define DIR_IN P3DIR &= ~BIT1 #define DIR_OUT P3DIR |= BIT1 #define SDA_IN ((P3IN >> 1) & 0x01) #define dis_data P5OUT //数码管输出 #define TIME 5 #define SlaveAddress 0xA6
uchar seg_bcd[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e}; //数码管
void delay_nms(unsigned int k) //延时k毫秒 { unsigned int i,j; for(i=0;i<k;i++) { for(j=0;j<121;j++) {;} } } void Delay(unsigned int n) //延时 { unsigned int i; for(i = 0;i < n;i++) { ; } }
void BH1750_Start() //起始信号 { DIR_OUT; SDA_1; delay_nms(5); SCL_1; Delay(TIME); SDA_0; Delay(TIME); SCL_0; }
void BH1750_Stop() //结束信号 { DIR_OUT; SDA_0; Delay(TIME); SCL_1; Delay(TIME); SDA_1; }
void BH1750_SendACK() //发送Ack { SCL_0; DIR_OUT; SDA_0; Delay(TIME); SCL_1; Delay(TIME); SCL_0; }
void BH1750_RecvACK() //接受ACK { SCL_1; Delay(TIME); DIR_IN; while(SDA_IN); DIR_OUT; SCL_0; Delay(TIME); }
void BH1750_SendByte(uchar dat) //发送一个字节 { DIR_OUT; unsigned int i; for(i = 0;i < 8;i++) { SCL_0; Delay(TIME); if((dat >> 7) & 0x01) SDA_1; else SDA_0; Delay(TIME); SCL_1; Delay(TIME); dat <<= 1; //数据左移一位,进入下一轮送数 } Delay(TIME); }
uchar BH1750_RecvByte() //接受一个字节 { uchar i; uchar dat = 0; uchar datbit=0; SCL_0; Delay(TIME); SDA_1; DIR_IN; for (i=0; i<8; i++) { SCL_1; Delay(TIME); datbit = SDA_IN; Delay(TIME); dat = ((dat << 1) | datbit); SCL_0; Delay(TIME); } return dat; }
void Single_Write_BH1750(uchar REG_Address) //写入 { BH1750_Start(); BH1750_SendByte(SlaveAddress); BH1750_SendByte(REG_Address); // BH1750_SendByte(REG_data); BH1750_Stop(); }
void main() { uchar tmp; float temp; int t; WDTCTL = WDTPW + WDTHOLD; P5DIR |= 0Xff; P4DIR |= 0x01; P5OUT |= 0x00; delay_nms(200); Single_Write_BH1750(0x01); Single_Write_BH1750(0x10); while(1) { Single_Write_BH1750(0x01); Single_Write_BH1750(0x10); delay_nms(180); tmp=BH1750_RecvByte(); temp=(float)tmp; t=temp/100; dis_data=seg_bcd[t]; } }
|