/*
Forum: https://forum.arduino.cc/t/dc-motor-mit-l293d-zufallig-ansteuern/1210964/6
Wokwi: https://wokwi.com/projects/387097065989298177
*/
const int rueckwaertsPin = 12;
const int vorwaertsPin = 8;
const int schalternormalPin = 6;
const int schalterzufallPin = 5;
const int pwmsignalmotorPin = 3;
struct buttonType {
byte pin;
byte state = LOW;
byte lastState = LOW;
unsigned long lastChange = 0;
void init(byte aPin) {
pin = aPin;
pinMode(pin, INPUT_PULLUP);
}
boolean isHigh() {
byte actState = digitalRead(pin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
}
if (actState != state && millis() - lastChange > 20) {
state = actState;
}
return state;
}
};
buttonType normal, zufall;
enum stateType {START, ZUFALL, WARTEN};
stateType state = START;
int drehzahl;
int richtung;
unsigned long zufallsDauer = 2000;
void setup() {
Serial.begin(115200);
pinMode (pwmsignalmotorPin, OUTPUT);
pinMode (vorwaertsPin, OUTPUT);
pinMode (rueckwaertsPin, OUTPUT);
normal.init(schalternormalPin);
zufall.init(schalterzufallPin);
randomSeed(analogRead(0));
}
void loop() {
stateMachine();
}
void stateMachine() {
static unsigned long startTime = 0;
switch (state) {
case START:
if (normal.isHigh()) {
setMotor(true, 60);
state = WARTEN;
Serial.println("WARTEN");
} else {
if (zufall.isHigh()) {
Serial.println("ZUFALL");
state = ZUFALL;
} else {
setMotor(true, 0);
}
};
break;
case ZUFALL:
if (millis() - startTime >= zufallsDauer) {
startTime = millis();
drehzahl = random(60, 255);
richtung = random(0, 2); // ergibt 0 oder 1 !!!!! Die 2 wird nicht erreicht!!
zufallsDauer = random(1,6)*1000UL;
setMotor(richtung, drehzahl);
Serial.print("Zufallsdauer: ");
Serial.println(zufallsDauer);
}
if (!zufall.isHigh()) {
setMotor(true,0);
state = START;
Serial.println("ZUFALL to START");
}
break;
case WARTEN:
if (!normal.isHigh()) {
Serial.println("WARTEN to START");
state = START;
}
break;
}
}
void setMotor(boolean Vorwaerts, int tempo) {
if (tempo == 0) {
digitalWrite(rueckwaertsPin, 0);
digitalWrite(vorwaertsPin, 0);
analogWrite (pwmsignalmotorPin, 0);
return;
}
if (Vorwaerts) {
digitalWrite(rueckwaertsPin, 0);
digitalWrite(vorwaertsPin, 1);
} else {
digitalWrite(rueckwaertsPin, 1);
digitalWrite(vorwaertsPin, 0);
}
analogWrite (pwmsignalmotorPin, tempo);
}