你好,我试图写一个草图,从超声波距离传感器读取距离,并只发送数据,如果以前和当前的读数是不同的(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”在循环函数中声明。你有两个选择。要么在循环外部声明它,要么在声明它的地方声明它,但使其成为静态的(在这两种情况下,还必须处理它包含的初始无效读取)