Skip to content

Instantly share code, notes, and snippets.

@yoniLavi
Created November 6, 2024 19:46
Show Gist options
  • Save yoniLavi/714577f07e3b609b15a88b49362250aa to your computer and use it in GitHub Desktop.
Save yoniLavi/714577f07e3b609b15a88b49362250aa to your computer and use it in GitHub Desktop.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 3; // PWM pin for LED
// Adjust these values to match your desired range
const float MIN_DISTANCE = 5.0; // Distance in cm when LED should be brightest
const float MAX_DISTANCE = 10.0; // Distance in cm when LED should be dimmest
const float MAX_DISTANCE_DISPLAY = 20.0; // Maximum distance for display purposes
float duration, distance;
void setup() {
// Ultrasonic sensor init
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
// LCD init
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Dist:");
}
void loop() {
// Get distance reading
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration * 0.0343) / 2;
// Constrain distance for display
float displayDistance = constrain(distance, 0, MAX_DISTANCE_DISPLAY);
// Update numerical display
lcd.setCursor(5, 0);
lcd.print(distance, 1);
lcd.print("cm ");
// Update bar graph
updateBarGraph(displayDistance);
// Update LED brightness
updateLED(distance);
// Print to Serial for debugging
Serial.print(distance);
Serial.print("cm, LED: ");
Serial.println(calculateLEDBrightness(distance));
delay(100);
}
void updateBarGraph(float value) {
int numBlocks = map(value, 0, MAX_DISTANCE_DISPLAY, 0, 16);
lcd.setCursor(0, 1);
for (int i = 0; i < 16; i++) {
if (i < numBlocks) {
lcd.write(255);
} else {
lcd.print(" ");
}
}
}
int calculateLEDBrightness(float distance) {
if (distance <= MIN_DISTANCE) return 255; // Full brightness
if (distance >= MAX_DISTANCE) return 0; // Off
// Map distance to LED brightness (inverse relationship)
return map(
constrain(distance, MIN_DISTANCE, MAX_DISTANCE) * 100, // Multiply by 100 for better precision
MIN_DISTANCE * 100,
MAX_DISTANCE * 100,
255, // Maximum brightness
0 // Minimum brightness
);
}
void updateLED(float distance) {
int brightness = calculateLEDBrightness(distance);
analogWrite(ledPin, brightness);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment