const int stepPin = 5; 
const int dirPin = 6;  

// NEU: Der Sharp-Sensor kommt an einen ANALOGEN Pin (z.B. A0)
const int sensorPin = A0; 
const int ledGruen = 7;  
const int ledRot = 8;    

// NEU: Ab welchem analogen Wert soll der Motor stoppen?
// (Höherer Wert = Objekt ist näher dran / Niedrigerer Wert = Objekt ist weiter weg)
// Ein Wert von ca. 300 entspricht bei diesen Sensoren oft etwa 15-20 cm Abstand.
const int SCHWELLENWERT = 300; 

const int UMDREHUNGEN = 1;        
const int SPEED_PAUSE = 550;      
const long SCHRITTE_PRO_UMDREHUNG = 1600; 
const long GESAMT_SCHRITTE = SCHRITTE_PRO_UMDREHUNG * UMDREHUNGEN;

long aktuellePosition = 0; 

void setup() {
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  
  // Analoge Pins müssen nicht zwingend als INPUT definiert werden, schadet aber nicht
  pinMode(sensorPin, INPUT); 
  pinMode(ledGruen, OUTPUT);
  pinMode(ledRot, OUTPUT);

  Serial.begin(115200); 
}

void plotteDaten() {
  // Wir lesen den aktuellen analogen Rohwert des Sharp-Sensors ein (0 bis 1023)
  int sensorWert = analogRead(sensorPin);
  
  // Format für den Serial Plotter
  Serial.print("Motor_Position:");
  Serial.print(aktuellePosition);
  Serial.print(",");
  Serial.print("Sensor_Abstandswert:");
  Serial.print(sensorWert);
  Serial.print(",");
  Serial.print("Stopp_Linie:");
  Serial.println(SCHWELLENWERT); // Zeigt dir eine gerade Linie im Plotter, wann er stoppen würde
}

void checkSensorUndAmpel() {
  // "while": Solange der gemessene Wert GRÖSSER als unser Schwellenwert ist (Objekt ist zu nah)...
  while (analogRead(sensorPin) > SCHWELLENWERT) {
    digitalWrite(ledGruen, LOW);  
    digitalWrite(ledRot, HIGH);   
    
    plotteDaten(); // Zeigt die stehende Position und den Sensorwert im Plotter
    delay(50); 
  }

  // Weg wieder frei
  digitalWrite(ledGruen, HIGH); 
  digitalWrite(ledRot, LOW);    
}

void loop() {
  // ==========================================
  // 1. FAHRT: RECHTSHERUM
  // ==========================================
  digitalWrite(dirPin, HIGH); 
  
  for(long i = 0; i < GESAMT_SCHRITTE; i++) {
    checkSensorUndAmpel(); 
    
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(SPEED_PAUSE);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(SPEED_PAUSE);
    
    aktuellePosition++; 
    
    if (i % 20 == 0) {
      plotteDaten();
    }
  }
  
  for(int w = 0; w < 10; w++) { plotteDaten(); delay(50); }

  // ==========================================
  // 2. FAHRT: LINKSHERUM
  // ==========================================
  digitalWrite(dirPin, LOW); 
  
  for(long i = 0; i < GESAMT_SCHRITTE; i++) {
    checkSensorUndAmpel(); 
    
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(SPEED_PAUSE);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(SPEED_PAUSE);
    
    aktuellePosition--; 
    
    if (i % 20 == 0) {
      plotteDaten();
    }
  }

  for(int w = 0; w < 10; w++) { plotteDaten(); delay(50); }
}