/*
Forum: https://forum.arduino.cc/t/dc-motorsteuerung-mit-hall-endschalter/1376495/10
Wokwi: https://wokwi.com/projects/429318070253515777
2025/04/26
ec2021
Taster
Blau = H1
Grün = H2
Rot = H3
Schwarz = S1
Weiss = S2
*/
#include <MobaTools.h>
const byte s1Pin = 4;
const byte s2Pin = 5;
const byte h1Pin = 6;
const byte h2Pin = 7;
const byte h3Pin = 8;
const byte stepPin = 3;
const byte dirPin = 2;
const int stepsPerRev = 6400;
enum States {IDLE, WAIT, GOH1, GOH2, GOH3};
States state = IDLE;
MoToStepper stepper1( stepsPerRev, STEPDIR );
struct switchType {
byte pin;
byte state = HIGH;
unsigned long lastChange = 0;
byte lastState = HIGH;
void init(byte aPin) {
pin = aPin;
pinMode(pin, INPUT_PULLUP);
}
boolean was_pressed() {
byte actState = digitalRead(pin);
if (actState != state && millis() - lastChange > 100) {
lastChange = millis();
state = actState;
return (state == LOW);
} else {
return false;
}
}
};
switchType S1, S2, H1, H2, H3;
void setup()
{
Serial.begin(115200);
stepper1.attach( stepPin, dirPin );
stepper1.setSpeed( 100 );
//stepper1.setRampLen( 50);
S1.init(s1Pin);
S2.init(s2Pin);
H1.init(h1Pin);
H2.init(h2Pin);
H3.init(h3Pin);
}
void loop() {
stateMachine();
}
void controlMachine() {
if (S1.was_pressed()) {
Serial.println("S1 Pressed");
stepper1.rotate(1);
state = GOH2;
}
if (S2.was_pressed()) {
Serial.println("S2 Pressed");
stepper1.rotate(1);
state = GOH3;
}
}
void stateMachine() {
static unsigned long startTime = 0;
switch (state) {
case IDLE:
controlMachine();
break;
case WAIT:
if (millis() - startTime >= 2000) {
state = GOH1;
stepper1.rotate(-1);
}
break;
case GOH1:
if (H1.was_pressed()) {
Serial.println("H1");
state = IDLE;
stepper1.stop();
}
break;
case GOH2:
if (H2.was_pressed()) {
Serial.println("H2");
startTime = millis();
state = WAIT;
stepper1.stop();
}
break;
case GOH3:
if (H3.was_pressed()) {
Serial.println("H3");
startTime = millis();
state = WAIT;
stepper1.stop();
}
break;
}
}