/*
Forum: https://forum.arduino.cc/t/code-funktioniert-nicht-richtig-warum/1327820/9
Wokwi: https://wokwi.com/projects/416199928123552769
*/
#include <Servo.h>
// Servo-Objekte erstellen
Servo servo1;
Servo servo2;
// Potentiometer-Pin
const int potPin = A0;
int potValue; // Aktueller Potentiometerwert
// Bluetooth-Signal
char bluetoothSignal;
bool bluetoothActive = false; // Flag für Bluetooth-Steuerung
// Definition der Zustände
enum State {
STARTPOSITION,
ZIELPOSITION,
UNTERSCHRITTEN_700,
WARTEN_AUF_RESET
};
State currentState = STARTPOSITION; // Initialzustand
bool resetAllowed = false; // Flag, ob erneuter Übergang erlaubt ist
void setup() {
servo1.attach(9); // Servo 1 an Pin 9
servo2.attach(10); // Servo 2 an Pin 10
Serial.begin(9600); // Serielle Kommunikation starten (auch für Bluetooth)
// Startposition
servo1.write(0);
servo2.write(180);
Serial.println("System initialisiert. Servos auf Startposition.");
}
void loop() {
// Potentiometerwert einlesen
potValue = analogRead(potPin);
// Bluetooth-Befehl prüfen
if (Serial.available()) {
bluetoothSignal = Serial.read();
if (bluetoothSignal == 'T') {
Serial.println("Bluetooth-Befehl 'T' empfangen. Servos bewegen sich.");
bluetoothActive = true; // Bluetooth-Steuerung aktivieren
}
}
// Zustandslogik nur ausführen, wenn Bluetooth nicht aktiv ist
if (bluetoothActive){
activateBluetoothAction();
} else {
switch (currentState) {
case STARTPOSITION:
if (potValue < 990) {
moveToTargetPosition();
currentState = ZIELPOSITION;
Serial.println("Wechsel zu: ZIELPOSITION");
}
break;
case ZIELPOSITION:
if (potValue < 700) {
currentState = UNTERSCHRITTEN_700;
Serial.println("Wechsel zu: UNTERSCHRITTEN_700");
}
break;
case UNTERSCHRITTEN_700:
if (potValue > 700) {
moveToStartPosition();
currentState = WARTEN_AUF_RESET;
Serial.println("Wechsel zu: WARTEN_AUF_RESET");
resetAllowed = false;
}
break;
case WARTEN_AUF_RESET:
if (potValue > 990) {
resetAllowed = true;
currentState = STARTPOSITION;
Serial.println("Reset erlaubt. Wechsel zu: STARTPOSITION");
}
break;
}
}
delay(50); // Kurze Verzögerung für Stabilität
}
// Funktion: Bewegung in die Zielposition
void moveToTargetPosition() {
servo1.write(180);
servo2.write(0);
Serial.println("Servos bewegen sich zur Zielposition.");
}
// Funktion: Bewegung zurück in die Startposition
void moveToStartPosition() {
servo1.write(0);
servo2.write(180);
Serial.println("Servos bewegen sich zurück zur Startposition.");
}
// Funktion: Bluetooth-Aktion ausführen
void activateBluetoothAction() {
moveToTargetPosition(); // Servos zur Zielposition bewegen
// Verzögerung von 2 Sekunden (2000 ms)
delay(2000);
moveToStartPosition(); // Servos zurück zur Startposition bewegen
delay(100);
// Nach der Aktion Bluetooth-Steuerung deaktivieren
bluetoothActive = false; // Reset auf false, um Potentiometer-Aktionen zu ermöglichen
Serial.println("Bluetooth-Aktion abgeschlossen. Zurück zur Potentiometer-Steuerung.");
}