// https://forum.arduino.cc/t/execute-function-after-count/1057468
// https://wokwi.com/projects/349255255985226324

# define reject 2   // signals this item is a reject

void setup() {
  Serial.begin(115200);
  Serial.println("conveyor belt world\n");

  pinMode(reject, INPUT_PULLUP);
}

int currentPart;

# define FOUR 4       // steps from inspection to rejection
# define DWELL  1000  // time window for rejection

unsigned char tape[FOUR];   // circular buffer?
unsigned char writePosition;
unsigned char readPosition;

# define OK     0
# define REJECT 1

void loop() {

  static unsigned long lastTime;
  unsigned long now = millis();

// always check to see if we need to reject this part

  if (digitalRead(reject) == LOW) {
    if (tape[writePosition] != REJECT) {
      Serial.print("            REJECT PART ");
      Serial.println(currentPart);

      tape[writePosition] = REJECT;
    }
  }

// run the rest of loop every DWELL ms

  if (now - lastTime < DWELL) return;
  lastTime = now;

  currentPart++;
  Serial.print("now welcoming ");
  Serial.println(currentPart);

  writePosition++; if (writePosition >= FOUR) writePosition = 0;

  readPosition = writePosition; // oldest on the tape

  if (tape[readPosition] == REJECT) {
    Serial.print("                   rejecting ");
    Serial.println(currentPart - FOUR);
  }

  tape[readPosition] = OK; 
}