I'm just starting out with Arduino so I copy-pasted the code from the ultrasonic sensors lesson and modified it to make a sensor+lcd combo that sends different messages based on the distance of an object. Unfortunately, it always returns 0 cm in the serial monitor no matter what I do. Here's the code (I know the text doesn't really make much sense at the moment but I'll iron that out):
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int distanceThreshold;
int cm;
int inches;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
// set up the LCD's number of columns and rows:
lcd.begin(19, 2);
// Print a message to the LCD.
lcd.print("Welcome!");
delay(500);
lcd.clear();
lcd.setCursor(4,0);
lcd.print("Let's see!");
delay(500);
lcd.clear();
}
void loop()
{
distanceThreshold = 350;
cm = 0.01723 * readUltrasonicDistance(7, 7);
inches = (cm / 2.54);
Serial.print(cm);
Serial.print("cm, ");
Serial.print(inches);
Serial.println("in");
if (cm > distanceThreshold) {
lcd.print("You cannot be detected. Please stand closer");
lcd.setCursor(2,1);
lcd.print("? units away");
delay(1500);
lcd.clear();
lcd.setCursor(4,0);
}
if (cm <= distanceThreshold && cm > distanceThreshold - 100) {
lcd.print("Step MUCH closer!");
lcd.print(cm);
}
if (cm <= distanceThreshold - 100 && cm > distanceThreshold - 250) {
lcd.print("A bit too far!");
lcd.setCursor(2,1);
lcd.print(cm);
}
if (cm <= distanceThreshold - 250 && cm > distanceThreshold - 350) {
lcd.print("Perfect");
lcd.setCursor(2,1);
lcd.print(cm);
}
if (cm <= distanceThreshold - 350) {
lcd.print("Way too close!");
lcd.setCursor(2,1);
lcd.print(cm);
lcd.setCursor(2,1);
lcd.print("? units away");
delay(1500);
lcd.clear();
lcd.setCursor(4,0);
}
delay(100); // Wait for 100 millisecond(s)
}
And here's an image:
Any help with making it work as intended would be very appreciated!