c++ - 如何使用移位运算符 << 分配 BH1750 光传感器中的值?

标签 c++ arduino bit-shift light-sensor

<分区>

我使用带有 arduino 的 BH1750 光传感器在 LCD 上显示勒克斯值。但是在代码中,我无法获得公式。谁能给我解释一下公式?

我试图在 BH1750 的数据表中找到它,但我无法理解这一行:

value = ((buff[0]<<8)|buff[1])/1.2;

完整代码:

#include<Wire.h>
#include<LiquidCrystal.h>

int BH1750address = 0x23;
byte buff[2];
LiquidCrystal lcd (7,6,5,4,3,2); //RS, E, D4, D5, D6, D7

void setup()
{
  Wire.begin();
  lcd.begin(16,2);
  lcd.print("  BH1750 Light  ");
  lcd.setCursor(0,1);
  lcd.print("Intensity Sensor");
  delay(2000);
}

void loop()
{
  int i;
  uint16_t value=0;
  BH1750_Init(BH1750address);
  delay(200);

  if(2==BH1750_Read(BH1750address))
  {
    value=((buff[0]<<8)|buff[1])/1.2; //This is where the problem is
    lcd.clear();
    lcd.print("Intensity in LUX");
    lcd.setCursor(6,1);
    lcd.print(value);
  }
  delay(150);
}

int BH1750_Read(int address) 
{
  int i=0;
  Wire.beginTransmission(address);
  Wire.requestFrom(address, 2);
  while(Wire.available()) 
  {
    buff[i] = Wire.read();
    i++;
  }
  Wire.endTransmission();  
  return i;
}

void BH1750_Init(int address) 
{
  Wire.beginTransmission(address);
  Wire.write(0x10);
  Wire.endTransmission();
}

最佳答案

<<是一个移位运算符,因此 buff[0] 中的值向左移动 8 位,然后该值由 函数链接。最后将结果值除以 1.2

例子:

buff[0] = 0000 0001              // assume this value for buff[0] (1 in decimal)
buff[1] = 0110 1000              // assume this value for buff[1] (104 in decimal)

buff[0]<<8:                      // move 8 bit to the left
0000 0001 0000 0000

buff[0]<<8 | buff[1]:            // link by or function
0000 0001 0000 0000 | 0000 0000 0110 1000 = 0000 0001 0110 1000     // 360 in decimal

所以

value = 360 / 1.2 = 300 

请注意 value是一个 int 因此它会忽略小数位

关于c++ - 如何使用移位运算符 << 分配 BH1750 光传感器中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471826/

相关文章:

c++ - 如何在 g++ 中抑制 ' left shift count >= width of type' 警告

c# - << 运算符的奇怪行为

.Net GetHashcode 位移操作

iphone - 将 C++ 代码重写为 Objective C

c++ - 将多态 unique_ptr 作为参数传递时发生内存泄漏

arduino - 同一引脚上的多个 Arduino 中断

python - 串行通信 Python 到 Arduino - 无法识别回车

c++ - 为什么字符串没有在 C++ 中打印所需的输出?

c++ - 为什么我在打印这个结构指针时出错?

python - RFM69 radio 收发器 : Arduino is not registering acknowledgement for transmission sent by Raspberry Pi