Hi,
I am new to arduino.
I am trying to display a single reading from an ardiuno sensor (in this example the ultrasonic HC-SR04 sensor) and display it on the LCD after I press the button.
Equipment - Arduino Uno, 2x16 LCD screen (parallel), potentiometer, a single button and the HC-SR04 ultrasonic sensor.
The two readings that are being output are distance (top line) and speed (second line).
The code is included below.
The problems I keep running into are that when I press the button, I consistently get a "0.00 cm" on top line and "0.00 cm/s" on the bottom line.
- The double variables are still there from some troubleshooting I have tried
- The code works if I remove all the code associated with the button.
#include <NewPing.h>
#include <LiquidCrystal.h>
#define TRIGGER_PIN 8 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 9 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 500 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define LCD_LIGHT_PIN A4
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int buttonPin = 6; // the pin that the pushbutton is attached to,
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
double buttonState = 0; // current state of the button
double lastButtonState = 0; // previous state of the button
double uScm1 = 0;
double time1 = 0;
double speed1 = 0;
void setup() {
// initialize serial communication:
Serial.begin(115200);
// initialize the button pin as a input:
lcd.begin(16, 2);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, LOW);
pinMode(LCD_LIGHT_PIN, OUTPUT);
digitalWrite(LCD_LIGHT_PIN, HIGH);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
double uS1 = sonar.ping_median(); // Send ping, get ping time in microseconds (uS).
double uScm1 = sonar.convert_cm(uS1);
lcd.setCursor(0, 0);
lcd.print(uScm1);
lcd.print(" cm ");
double time1 = millis();
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
double uS2 = sonar.ping_median(); // Send ping, get ping time in microseconds (uS).
double uScm2 = sonar.convert_cm(uS2);
double time2 = millis();
double speed1 = abs((uScm2 - uScm1)) / ((time2 - time1) / 1000);
lcd.setCursor(0, 1);
lcd.print(speed1);
lcd.print(" cm/s ");
}
else {
lcd.setCursor(0, 0);
lcd.print(uScm1);
lcd.print(" cm ");
lcd.setCursor(0, 1);
lcd.print(speed1);
lcd.print(" cm/s ");
}
}

