Hello, I am trying to practice programming and I have attempted to combine two different pieces of code.
The first bit of code uses the ultrasonic sensor to measure distance and if the is nothing in front of the sensor a (green) led will show and if an object comes closer than a certain distance a (red) led will show.
I wanted to implement a basic LCD-LED code that would print “Activated” when the red led went on when an object comes close to the sensor. Then clear the screen or print nothing when the (green) led is on.
I managed to get the code to work but when I move my hand away from the sensor(turning back on the Green led) the “Activated fades away rather slowly”
which I do want the “activated” to go away when nothing is in front of the sensor and the green led is on but I don’t think it is supposed to be that slow.
Can anyone see where i can improve this?
Thanks
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
unsigned int distance;
byte redLed = 8;
byte greenLed = 10;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4);
int ledPin=9;
void setup()
{
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
lcd.init();
lcd.backlight();
}
void loop()
{
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
distance = sonar.ping_cm();
Serial.print("Ping: ");
Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
if (distance > 40) {
// d > 40
lcd.clear();
digitalWrite(greenLed, HIGH);
digitalWrite(redLed, LOW);
} else
if (distance != 0) {
// d inferior or equal to 40 but non 0
lcd.setCursor(0,0);
lcd.print("Activate");
digitalWrite(redLed, HIGH);
digitalWrite(greenLed, LOW);
} else {
// d is 0
lcd.setCursor(0,0);
lcd.print("Activate");
digitalWrite(redLed, HIGH);
digitalWrite(greenLed, LOW);
}
}