c++ - 使用 I2C 协议(protocol)从磁力计读取值

标签 c++ arduino microcontroller

我对这一切还很陌生。如果有什么明显的地方,请原谅。

我一直在为磁力仪随附的数据表苦苦挣扎。出于某种原因,似乎一切正常,但当我向它挥动磁铁时,我实际上并没有在序列中得到任何响应。

所以这里有一些信息。

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
  Serial.begin(9600); // start serial communication at 9600bps
}

void loop() {
  int reading = 0;
  int Address = 30;
  Wire.beginTransmission(Address);
  Wire.write(byte(0x03));
  Wire.write(byte(0x04));
  Wire.endTransmission();

  Wire.requestFrom(Address, 2);
  delay(10);
  if (2 <= Wire.available()) {
    reading = Wire.read();
    reading = reading << 8;
    reading |= Wire.read();
    Serial.println(int(reading));
  }

  delay(250); // wait a bit since people have to read the output :)
}

使用此代码,我会收到一个号码。

-5637
-5637
-5637
-5637
-5637

但是如果我删除以下行 Wire.write(byte(0x03));,我的输出不会改变。来自设备的值应该表示为二进制补码。

所以起初我以为我不知道如何向设备发送多个字节,但经过一些研究我发现我做对了(我认为)。

然后,如果我只输入 Wire.write(byte(0x03));,我会收到“0”作为响应。阅读数据表,我看到响应 0 表示命令无效。

我在这篇文章中包含了数据表。有人可以指出我正确的方向吗?我正在使用的 IC 是 LSM303DLHC,我正在使用这个“sheild”。

这是 datasheet .

下图为总线通信图

enter image description here

最佳答案

我相信下面的代码可以做到这一点,它类似于数据表中的表 11:

  Wire.beginTransmission(Address);  // START and write to device address 0x1E
  Wire.write(byte(0x03));           // Set the register pointer to sub-address 0x03
  Wire.write(byte(0x04));           // Write a value of 0x04 to sub-address 0x3
  Wire.endTransmission();           // STOP.

然后我怀疑设备的寄存器指针自动从寄存器 0x​​03 递增到 0x04。然后您的其余代码可能会从子地址 0x04 和 0x05 读取两个字节。

您没有表达您对代码的意图,但我怀疑以上内容不是您的意图。我的猜测是您打算从设备地址 0x1E、子地址 0x03 和子地址 0x04 中读取 两个字节。是吗?

您应该执行表 13 中描述的操作。

  Wire.beginTransmission(Address);  // START and write to device address 0x1E
  Wire.write(byte(0x03));           // Set the register pointer to sub-address 0x03
  Wire.requestFrom(Address, 2);     // REPEAT-START and read 2 bytes from sub-address 0x03 and 0x04

关于c++ - 使用 I2C 协议(protocol)从磁力计读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255383/

相关文章:

c++ - 如何轻松解析来自 GSM 模块的 AT 命令响应?

sockets - Easy Button to UDP 数据包 - 控制板术语

c++ - Arduino 上有不同的 I2C 地址吗?

c - 内置函数的位置 Microchip C30 编译器

c++ - 使用作用域 queue::swap 清空 std::queue 是否违反任何规则?

c++ - 使用 cv::undistort 取消扭曲和居中图像

python - 如何将 C++ 指针传递给其他 cython 对象

c++ - 生成具有偶数汉明权重的整数(popcount)c++

c# - BTLE 4.0 负载