My purpose is read data from BH1750 light intensity sensor one time after two second. I using Timer1 to counter time. But, it did not work. When I copy body of callback and paste to loop function then my program work correctly. Help me please. Thank so much.
#include <Wire.h>
#include <TimerOne.h>
#define BH175_ADDRESS 0x23
byte buff[2];
void setup() {
// initialize the digital pin as an output:
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // set the LED off
Timer1.initialize(2000000); // initialize timer1, and set a 1/2 second period
Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
Serial.begin(9600);
Serial.println("Testing");
}
// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
//callback();
}
void callback()
{
Serial.println("check");
BH1750_Init(BH175_ADDRESS);
if(BH1750_Read(BH175_ADDRESS) != 2)
{
//Light sensor has problem!
Serial.println("Light sensor has problem!");
return;
}
int lightIntensity = ((buff[0]<<8)|buff[1])/1.2;
Serial.println(lightIntensity);
}
int BH1750_Read(int address) //
{
int count = 0;
Wire.beginTransmission(address);
Wire.requestFrom(address, 2);
while(Wire.available()) //
{
buff[count] = Wire.read(); // receive one byte
count++;
}
Wire.endTransmission();
return count;
}
void BH1750_Init(int address)
{
Wire.beginTransmission(address);
Wire.write(0x10);//1lx reolution 120ms
Wire.endTransmission();
}