/*
https://forum.arduino.cc/t/schrankensteuerung-ho/1354059/20
2025-02-21 by noiasca
*/
#include <Wire.h>
constexpr uint8_t slave1Adresse = 9;
constexpr uint8_t in1 = 9; // in1 = Bezeichnung am L298N
constexpr uint8_t in2 = 8; // in2 = Bezeichnung am L298N
constexpr uint8_t limitSwitchUp = 6;
constexpr uint8_t limitSwitchDown = 7;
enum State {IDLE, UP, DOWN} state;
// callback for I2C
void receiveEvent(int bytes) {
int command = Wire.read(); // ich weis nicht was du wirklich über I2C überträgst. aus meiner Sicht wäre dieser Read nicht mehr notwendig
handleEvent(command);
}
// read Serial - for easier debugging without I2C
void serialRun() {
int command = Serial.read();
if (command != -1 ) handleEvent(command - '0');
}
// accept 1 up or 2 down
void handleEvent(int command) {
if (state == IDLE) {
switch (command) {
case 1:
motorUp();
break;
case 2:
motorDown();
break;
default:
Serial.print(F("E: unknown command=")); Serial.println(command);
}
}
else {
Serial.print(F("E: not in correct state=")); Serial.println(state);
}
}
// if motor is moving check the endswitch - call over and over in loop
void motorRun() {
switch (state) {
case UP:
if (digitalRead(limitSwitchUp) == LOW) motorStop();
break;
case DOWN:
if (digitalRead(limitSwitchDown) == LOW) motorStop();
break;
}
}
// start moving upwards
void motorUp() {
digitalWrite(in1, HIGH); // Motor 1 beginnt zu rotieren Rechts Auf
digitalWrite(in2, LOW);
state = UP;
Serial.print(F("state=")); Serial.println(state);
}
// start moving upwards
void motorDown() {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH); // Motor 1 beginnt zu rotieren Links Ab
state = DOWN;
Serial.print(F("state=")); Serial.println(state);
}
// stop movement
void motorStop() {
digitalWrite(in1, LOW); // Motor 1 Stop
digitalWrite(in2, LOW); // Motor 1 Stop
state = IDLE;
Serial.print(F("state=")); Serial.println(state);
}
void setup() {
Serial.begin(115200);
Serial.println(F("Motor for Railroad crossing. send 1 for up or 2 for down"));
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(limitSwitchUp, INPUT_PULLUP);
pinMode(limitSwitchDown, INPUT_PULLUP);
Wire.begin(slave1Adresse); // Start the I2C Bus as Slave
Wire.onReceive(receiveEvent); // Attach a function to trigger when something is received.
}
void loop() {
motorRun();
serialRun();
}
//