1

我正在尝试使用 I2C 将 Arduino Uno 连接到温度传感器。起初,Arduino 可以发送数据流,但几分钟后就停止了……

如果我重新启动开发板,Arduino 可以发送数据流,但几分钟后又会停止。我想知道我的代码是否错误。请帮我。

/*
 Program akses DT-SENSE Temp SENSOR - Arduino
 Vizard Vision @ 2013 
*/
#include <Wire.h>
void setup() {
  Wire.begin();            
  Serial.begin(38400);     
}
int buffer = 0;
int count = 0;
void loop() {
  if(count >= 6000) {
    count = 0;
  }
  Wire.beginTransmission(112); // transmit to device #112 (0x70)
  // the address specified in the datasheet is 224 (0xE0) --> 1110 0000 = E0H
  // but i2c adressing uses the high 7 bits so it's 112 --> 0111 0000 = 70H
  Wire.send(0x00);
  // command sensor to measure 16 Byte of Temperature Data
  Wire.endTransmission();    
  delay(100);               

  Wire.requestFrom(112, 2);
  // request 2 bytes from slave device #112
  if(2 <= Wire.available()) {
    // if two bytes were received
    buffer = Wire.receive();
    // receive high byte (overwrites previous reading)
    buffer = buffer << 8;
    // shift high byte to be high 8 bits
    buffer |= Wire.receive();
    // receive low byte as lower 8 bits
    buffer = (buffer - 400)/10;
    // Conversion data to Temperature (from datasheet)
    Serial.print(count);
    Serial.print(" Suhu = ");
    Serial.print(buffer);
    Serial.write(176);
    // Unicode value of Degree Symbol
    Serial.println("Celsius");
    count ++;
    Serial.flush();
  }
  delay(40);
}
4

1 回答 1

1

这里可能有问题:

  if(2 <= Wire.available())    // if two bytes were received
  {
    buffer = Wire.receive();  // receive high byte (overwrites previous reading)
    buffer = buffer << 8;    // shift high byte to be high 8 bits
    buffer |= Wire.receive(); // receive low byte as lower 8 bits

如果有 1 或 2 个字节可用,它将进入块。如果有 2 个字节,它将通过两个字节,Wire.receive()并且您的buffer变量将正确设置,并且您很高兴。如果只有 1 个字节,它将首先通过Wire.receive(),然后Wire.receive()您将遇到意外行为(文档没有说明发生这种情况时它会做什么)。所以我希望它在一个字节到来之前一直阻塞,但由于它永远不会到来,它会无限阻塞。

然后你会想“为什么这会返回一个字节? ”。可能有很多原因:

  • 数据表可能会撒谎,并且在非常特定的情况下,您的 i2c 从站可能会返回一个字节,
  • 您的连接在某一时刻处理不当,并且从站以不正确的速度写入两个字节,使您的库相信它只有一个字节,
  • 您的 i2c 线路中存在错误联系,并且在奇怪的情况下(温度、压力、振动、尼加拉瓜的风暴),两个字节中只有一个字节通过连接...

因此,您应该执行以下操作:

  if(Wire.available() == 2)    // if two bytes were received
  {
    buffer = Wire.receive();  // receive high byte (overwrites previous reading)
    buffer = buffer << 8;    // shift high byte to be high 8 bits
    buffer |= Wire.receive(); // receive low byte as lower 8 bits

这将使您避免经历意外的行为!

于 2013-06-25T18:45:04.050 回答