c++ - 在 Arduino 中存储上次读数

标签 c++ c arduino

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

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

有什么想法吗?

最佳答案

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

关于c++ - 在 Arduino 中存储上次读数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727923/

相关文章:

c - 移动平均算法问题

arduino - 为什么我的指纹传感器不响应我的 arduino 代码?

c++ - 如何检查简单的 C++ 标准库迭代器是否可以被推进?

c++ - 多重定义[...] 先在这里定义

c++ - shared_ptr 与 unique_ptr 与数组

c - ALSA:扬声器周期大小与麦克风的关系

c - 如何测量在 Pentium 4 处理器上运行时 C 算法消耗的功率?

c++ - 嵌套 if 循环跳转到第二个,即使第一个不是真的

c++ - Winapi 定时器回调线程,永不返回

c++ - 如何在 VisualDsp++ 5 中为 Blackfin BF537 使用 *.cpp 文件中的 asm 实现的函数?