analog input voltage sweep counter.

hi
im trying to count the number of times an analog input goes below (or above) a set voltage, in hopes to count a crank position pulses. i came up with some test code, using a potentiometer to simulate a the change in voltage of the sensor, it works fine except i need it to only add 1 to the counter, rather the constantly count up as long as the voltage is above or below the set voltage, i cant seem to find a way only increment by 1. any help would be great thx

int LED = 13;
int counter = 0;

void setup() {
 pinMode(LED, OUTPUT); 
  Serial.begin(9600);
}


void loop() {

  int sensorValue = analogRead(A2);
  
  float voltage = sensorValue * (5.0 / 1023.0);
  
if (voltage > 0.42) digitalWrite(LED, LOW);
if (voltage < 0.42) digitalWrite(LED, HIGH);

if (voltage < 0.42) counter++;

  Serial.println(counter);
}

You need to remember what the prior voltage was (or if you incremented the counter) and then use that knowledge combined with the current voltage level to decide if you need to increment again or not

Also, voltage = sensorValue * 5.0 / 1024.0

so im amusing there isnt way to delay the next count until the voltage drops ? ive seen code where there is a memory counter to compare to but i dont understand it.

and so i dont need the "float" ?

thx

something like this should do what you want:

int LED = 13;
int counter = 0;

bool counterIncremented = false;

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

const float threshold = 0.42;

void loop() {

  int sensorValue = analogRead(A2);

  float voltage = sensorValue * (5.0 / 1024.0);

  if (voltage > threshold) {
    digitalWrite(LED, LOW);
    counterIncremented = false;
  } else {
    // we are at or below threshold
    digitalWrite(LED, HIGH);
    if (counterIncremented == false) {
      counter++;
      counterIncremented = true;
      Serial.println(counter);
    }
  }
}
[\code]

kdglv: so im amusing there isnt way to delay the next count until the voltage drops ? ive seen code where there is a memory counter to compare to but i dont understand it.

and so i dont need the "float" ?

thx

Look at the StateChangeDetecion example in the IDE to see how to detect when a values [u]becomes[/u] LOW or less than a value rather than when it [u]is[/u] LOW or below a value. Same for HIGH/higher than

Better still, don't do any floating-point at runtime, but get the compiler to calculate the threshold as ADC counts.