在Arduino中存储最后的阅读

时间:2017-03-10 21:22:33

标签: c++ c arduino

您好我正在尝试编写一个草图,该草图读取超声波距离传感器的距离,并且只有在先前和当前读数为不同(20cm)时才发送数据。下面是我的草图;

const int TRIG_PIN = 12;
const int ECHO_PIN = 11;

#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;

void setup() {

  // The Trigger pin will tell the sensor to range find
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);

  // We'll use the serial monitor to view the sensor output
  Serial.begin(9600);
  BTserial.begin(9600); 
}

void loop() {

  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm;
  float inches;
  float lastcm;
  float diff;

  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin
  while ( digitalRead(ECHO_PIN) == 0 );

  // Measure how long the echo pin was held high (pulse width)
  // Note: the () microscounter will overflow after ~70 min
  t1 = micros();
  while ( digitalRead(ECHO_PIN) == 1);
  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters and inches. The constants
  // are found in the datasheet, and calculated from the assumed speed 
  //of sound in air at sea level (~340 m/s).
  cm = pulse_width / 58.0;
  diff = cm - lastcm;
  lastcm = cm;

  // Print out results
  if ( pulse_width > MAX_DIST ) {
    BTserial.write("Out of range");
    lastcm = cm;
  } else {
    Serial.println(diff);
    Serial.println("Or act value");
    Serial.println(cm);
    lastcm = cm;
    if (abs(diff)>20) {
      BTserial.println(cm);
      }


  }

  // Wait at least 60ms before next measurement
  delay(150);
}

然而,这并没有正确计算这两个值之间的差异 - 因为串行监视器只返回

29.24
Or act value
29.24
29.31
Or act value
29.31
28.83
Or act value
28.83

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

你的变量&#39; lastcm&#39;在循环函数内声明。你有两个选择。要么将它声明为循环外部,要么将其声明为你所做的,但要将其设置为静态(在任何一种情况下,你还必须处理它包含的初始无效读数)

答案 1 :(得分:1)

您可以使用NewPing库简化此草图并使其不易出错: http://playground.arduino.cc/Code/NewPing