Dear Arduidons
I'm playing around with a tutorial sketch to learn the basics. It is a simple distance measuring circuit, using a NANO R3, a serial driven LCD display and a US-015 ultrasonic device. The code is not mine - with all the tinkering...lost the owner's name but full recognition to him/her.
The basic code is working 100% but I wanted to enhance the code to light up a LED if the distance measured (in cm) is equal or less than 30cm. The code is not a lot so I copied everything.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
const int trigPin = 8; // ultransonic Sensor
const int echoPin = 9; //ultransonic Sensor
const int LED=5; // LED connected to pin 5, to indicate predetermined distance reached
// defines variables
long duration;
int distanceCM;
int distanceINCH;
void setup() {
lcd.init();
pinMode (LED, OUTPUT); // set pin driving LED as Output
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop()
{
// Clears the trigPin
digitalWrite(LED, LOW);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distanceCM= duration*0.034/2;
distanceINCH = duration*0.0133/2;
{
// Prints the distance on the Serial Monitor
Serial.print("Distance in cm: ");
Serial.println(distanceCM);
Serial.print ("Distance in Inches: ");
Serial.println(distanceINCH);
Serial.println();
//delay(500);
lcd.backlight();
lcd.setCursor(4,0); // 3 place on row 0
lcd.print("Distance");
lcd.setCursor(0,3);
lcd.print(distanceCM);
lcd.print(" cm");
lcd.setCursor(8,3);
//lcd.print("Distance: ");
lcd.print(distanceINCH);
lcd.print(" in");
// delay(500);
{
if (digitalRead(distanceCM) <= 30)
{
digitalWrite (LED, LOW);
}
else
{
digitalWrite (LED, HIGH);
}
}
}
}
When I cause the distance to be <= 30 cm - the LED remains off. Playing around, I set the LED to HIGH right at the start of the sketch and the LED does go high but remains high irrespective of any distance measured. I then tried playing around changing the if statement to be " >= 30" but no change occurs.
I'm sure it is a small and basic thing. Pointing me in the right direction will help me bashing my brains in ![]()
Thanking you in advance.
(PS.... if I'm too formal for the young generation - apologies, I am old)