Arduino Trick: Treating Digital like Analog

In response to Katrina’s great tip about the multiplexer I thought I would pass this little trick on as well.

With only a few simple lines of code you too can use your digital inputs to read analog data. Below is the function. Just copy and paste the code before your void loop(), then call it with digiAnalog(pin). It’s pretty easy. Continue reading to see the code:

 

long digiAnalog(int pin){
  int count = 0;
  long analogValue= 0;
  int value = 0;

  value = digitalRead(pin);
  while(value == HIGH) { // Loop until pin reads a low
    value = digitalRead(pin);
  }

  while(value == LOW) { // Loop until pin reads a high
    value = digitalRead(pin);
  }

  while(value == HIGH) { // Loop until pin reads a low and count
    value = digitalRead(pin);
    count = count + 1;
  }

  analogValue = count;

  return analogValue;
}