#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// --- Konfiguration ---
// Adresse 0x27 oder 0x3F!
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define TRIG_PIN 9
#define ECHO_PIN 10
#define LED_PIN 8
#define TAST_PIN 7
float entfernung; // Entfernung in cm
byte Status;
bool TasterZustand;
unsigned long Wechselzeit;
bool checkButtonInput(bool Taster)
{
if (Taster==LOW && millis()-Wechselzeit>1000)
{
TasterZustand = !TasterZustand;
lcd.clear();
Wechselzeit=millis();
}
return TasterZustand;
}
float measureDistance (unsigned long Echozeit)
{
return (Echozeit/2.0)*0.034346;
}
void updateLCD(bool Taster, float distanz, byte Statusbyte)
{
int anzahlHash,anzahlLeerzeichen;
if (Taster)
{
lcd.setCursor(0,0);
lcd.print("Dist: ");
lcd.print(entfernung);
lcd.print(" cm ");
lcd.setCursor(0,1);
lcd.print("STS: ");
for(int i=7; i>=0; i--)
{
lcd.print(bitRead(Status, i));
}
}
else
{
if(entfernung<=50)
{
anzahlHash=map(distanz,0,50,16,0);
}
else
{
anzahlHash=0;
}
anzahlLeerzeichen=16-anzahlHash;
lcd.setCursor(0,0);
lcd.print("Abstand ");
lcd.setCursor(0,1);
for(int i=0; i<anzahlHash;i++)
{
lcd.print("#");
}
for(int i=0; i<anzahlLeerzeichen;i++)
{
lcd.print(" ");
}
}
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(TAST_PIN, INPUT_PULLUP);
lcd.begin(16,2);
Serial.begin(9600);
Wechselzeit=millis();
}
void loop() {
Status=0;
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
entfernung=measureDistance(pulseIn(ECHO_PIN,HIGH));
if(entfernung == 0 || entfernung > 400)
{
Status=Status | (1 << 7);
digitalWrite(LED_PIN, HIGH);
}
else
{
digitalWrite(LED_PIN, LOW);
if(entfernung<50)
{
Status=Status|(1 << 0);
}
if (entfernung < 10)
{
Status=Status|(1 << 1);
}
}
updateLCD(checkButtonInput(digitalRead(TAST_PIN)),entfernung,Status);
Serial.print("Entfernung: ");
Serial.print(entfernung);
Serial.print(" cm. | ");
Serial.print("Status: ");
for(int i=7; i>=0; i--)
{
Serial.print(bitRead(Status, i));
}
Serial.println();
delay(500);
}