#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// تعريف الثوابت
#define TRIG_PIN 9
#define ECHO_PIN 10
#define BUTTON1_PIN 8
#define BUTTON2_PIN 11
#define LCD_ADDRESS 0x27
#define LCD_COLS 16
#define LCD_ROWS 2
LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLS, LCD_ROWS);
float distance;
float length;
float width;
float area;
bool button1_pressed;
bool button2_pressed;
float addValue;
unsigned long button2PressTime = 0;
unsigned long button2PressDuration = 0;
bool areaDisplayed = false; // حالة عرض المساحة
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUTTON1_PIN, INPUT_PULLUP);
pinMode(BUTTON2_PIN, INPUT_PULLUP);
lcd.init();
lcd.backlight();
distance = 0;
length = 0;
width = 0;
area = 0;
button1_pressed = false;
button2_pressed = false;
addValue = 0.05;
}
void loop() {
distance = measureDistance() + addValue;
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" m ");
button1_pressed = digitalRead(BUTTON1_PIN) == LOW;
if (button1_pressed) {
length = distance;
lcd.setCursor(0, 1);
lcd.print("Length: ");
lcd.print(length);
lcd.print(" m ");
while (digitalRead(BUTTON1_PIN) == LOW); // Wait until button is released
areaDisplayed = false; // إخفاء المساحة
}
// Check if BUTTON2 is pressed
if (digitalRead(BUTTON2_PIN) == LOW) {
// Start timing
if (button2PressTime == 0) {
button2PressTime = millis();
} else {
// Calculate how long the button has been pressed
button2PressDuration = millis() - button2PressTime;
if (button2PressDuration > 1000) {
// If pressed for more than 1000 ms, calculate area
area = length * width;
areaDisplayed = true; // عرض المساحة
}
}
} else {
// If the button was pressed for a short time, update width
if (button2PressDuration > 0 && button2PressDuration <= 1000) {
width = distance;
lcd.setCursor(0, 1);
lcd.print("Width: ");
lcd.print(width);
lcd.print(" m ");
}
// Reset the timing as the button is released
button2PressTime = 0;
button2PressDuration = 0;
}
// Display area if it has been calculated
if (areaDisplayed) {
lcd.setCursor(0, 1);
lcd.print("Area: ");
lcd.print(area);
lcd.print(" m2 ");
}
}
// Function to measure distance
float measureDistance() {
float duration;
// Trigger the ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the return pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance
return (duration * 0.034 / 2) / 100;
}