Need help with code for a counter using tcrt5000

I have this simple code for a coin counter. Everything works but I have to reupload the code every time I'm counting a different coin because of the delay. How do I go about where it doesn't count continuous high signals and waits for a low signal before counting another high signal.

const int sensorPin = A0; 

int signalCount = 0;

void setup() {
  Serial.begin(9600);
  pinMode(sensorPin, INPUT);
}

void loop() {
  int sensorState = analogRead(sensorPin);

  if (sensorState>600) {
    signalCount++;

    Serial.print("Count: ");
    Serial.println(signalCount);

    delay(70);
  }
}

Have a look at the "state change" sketch from the examples menu in the IDE.

Try this code:

const int sensorPin = A0; 

int signalCount = 0;
bool flag = false;
//-----------------------------------------------------------
void setup() {
  Serial.begin(9600);
  pinMode(sensorPin, INPUT);
}
//-----------------------------------------------------------
void loop() {
  int sensorState = analogRead(sensorPin);
  //Serial.println(sensorState);
  if (sensorState>600 and flag == false) {
    flag = true;
    signalCount++;
    Serial.print("Count: ");
    Serial.println(signalCount);
  }
  if (sensorState< 400) {    // Or another value below 600.
    flag = false;
  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.