// DC_Motor_SerialControl.ino
// Steuerung per Serial Monitor: Fxxx = Vorwärts, Rxxx = Rückwärts, S = Stop
// Pin-Belegung: IN1 = 5 (PWM), IN2 = 6 (PWM), ENA ist per Jumper auf HIGH
const int motorPinA = 5; // PWM-fähig → IN1 am L298N
const int motorPinB = 6; // PWM-fähig → IN2 am L298N
void setup() {
Serial.begin(9600);
pinMode(motorPinA, OUTPUT);
pinMode(motorPinB, OUTPUT);
// Motor sicherheitshalber stoppen
analogWrite(motorPinA, 0);
analogWrite(motorPinB, 0);
Serial.println("=== DC-Motor Serial Control ===");
Serial.println("Befehle: Fxxx = Vorwaerts, Rxxx = Rueckwaerts, S = Stop");
Serial.println("Beispiel: F150 (Vorwaerts mit PWM=150)");
Serial.println(" R200 (Rueckwaerts mit PWM=200)");
Serial.println(" S (Motor Stoppen)");
Serial.println("--------------------------------");
}
void loop() {
if (Serial.available() > 0) {
// Einlesen bis Zeilenende
String input = Serial.readStringUntil('\n');
input.trim(); // Leerzeichen entfernen
if (input.length() == 0) return;
// Erstes Zeichen gibt Richtung an: F, R oder S
char cmd = toupper(input.charAt(0));
if (cmd == 'F' || cmd == 'R') {
// Rest der Zeichenfolge als Zahl interpretieren
String numPart = input.substring(1);
int value = numPart.toInt();
// toInt() liefert 0, wenn kein valider Wert. Wir setzen Minimum=0
if (value < 0) value = 0;
if (value > 255) value = 255;
if (cmd == 'F') {
// Vorwärts: IN2 = LOW, IN1 = PWM
digitalWrite(motorPinB, LOW);
analogWrite(motorPinA, value);
Serial.print("Motor: VORWAERTS, PWM = ");
Serial.println(value);
} else {
// Rückwärts: IN1 = LOW, IN2 = PWM
digitalWrite(motorPinA, LOW);
analogWrite(motorPinB, value);
Serial.print("Motor: RUECKWAERTS, PWM = ");
Serial.println(value);
}
}
else if (cmd == 'S') {
// Stop: beide PWM = 0
analogWrite(motorPinA, 0);
analogWrite(motorPinB, 0);
Serial.println("Motor: STOP");
}
else {
// Ungültiges Kommando
Serial.print("Unbekanntes Kommando: ");
Serial.println(input);
Serial.println("Nur Fxxx, Rxxx oder S benoetigt.");
}
}
}