The buzzer starts as soon as the receivedChars is over 0. Otherwise it stops. After I push the button to zero the height being sent by the TX there is a little fluctuation but this is not a problem. The flutuation varies between - over 0 to plus a few decimal places as you can see on the printout.
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
#include <SoftwareSerial.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const byte piezoPin = 5;
float Height = 0;
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
SoftwareSerial mySerial(2, 3); // RX, TX
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (mySerial.available() > 0 && newData == false) {
rc = mySerial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
} else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
} else if (rc == startMarker) {
recvInProgress = true;
}
}
}
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
pinMode(7, OUTPUT);
digitalWrite(7, LOW);
mySerial.print(F("AT+C001\r\n"));
delay(100);
digitalWrite(7, HIGH);
display.begin(SSD1306_SWITCHCAPVCC, 0x3c); // initialize with the I2C addr 0x3D (for the 128x64)
noTone(piezoPin);
}
void loop() {
recvWithStartEndMarkers();
if (newData == true) {
Height = atof(receivedChars);
Serial.println(receivedChars);
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(20, 1);
display.println("Altitude");
display.setCursor(20, 20);
display.println("in Feet");
display.setTextSize(2);
display.setCursor(55, 50);
display.println(Height);
display.display();
Height = atof(receivedChars);
for (float h=0; h<Height; h+=100.0) {
tone(piezoPin, 3000, 200);
delay(300); // 200 for the tone duration and 100 for the silence
}
newData = false;
}
}
-0.04
0.13
0.03
0.13
0.19
0.13
0.19
0.09
-0.06
-0.16
-0.21
-0.10
-0.15
-0.15
-0.21
-0.20
-0.30
-0.24
-0.24
-0.23
-0.38
-0.43
-0.33
-0.27
-0.27
-0.22
-0.27
-0.37
-0.25
-0.30
-0.30
-0.35
-0.35
-0.30
-0.24
-0.04