#define ForLed 7
#define RevLed 6
#define LimitBtn 9
#define StartBtn 5
byte lastLimitBtnState = HIGH; // Default to HIGH because of INPUT_PULLUP
byte lastStartBtnState = HIGH; // Default to HIGH because of INPUT_PULLUP
byte ledState = LOW;
byte conveyorRunning = LOW;
unsigned long debounceDuration = 50; // millis
unsigned long lastTimeLimitBtnStateChanged = 0;
unsigned long lastTimeStartBtnStateChanged = 0;
int counter = 0;
void setup() {
pinMode(ForLed, OUTPUT);
pinMode(RevLed, OUTPUT);
pinMode(LimitBtn, INPUT_PULLUP); // Set LimitBtn to use the internal pull-up resistor
pinMode(StartBtn, INPUT_PULLUP); // Set StartBtn to use the internal pull-up resistor
Serial.begin(9600);
}
void loop() {
// Handle Start Button
if (millis() - lastTimeStartBtnStateChanged > debounceDuration) {
byte startBtnState = digitalRead(StartBtn);
if (startBtnState != lastStartBtnState) {
lastTimeStartBtnStateChanged = millis();
lastStartBtnState = startBtnState;
if (startBtnState == HIGH) { // Button released
conveyorRunning = HIGH;
digitalWrite(ForLed, HIGH);
digitalWrite(RevLed, LOW);
Serial.println("Conveyor Started");
}
}
}
// Handle Limit Button
if (conveyorRunning && millis() - lastTimeLimitBtnStateChanged > debounceDuration) {
byte limitBtnState = digitalRead(LimitBtn);
if (limitBtnState != lastLimitBtnState) {
lastTimeLimitBtnStateChanged = millis();
lastLimitBtnState = limitBtnState;
if (limitBtnState == HIGH) { // Button released
ledState = (ledState == HIGH) ? LOW : HIGH;
digitalWrite(ForLed, ledState);
Serial.println("Forward");
counter++;
Serial.print("Counter: ");
Serial.println(counter);
digitalWrite(RevLed, !ledState);
}
}
}
}