Why is analogRead() returning zero all the time?

Hi all,

I’m probably doing something stupid here but I’ve been at this for an hour now and my brain hurts. If you can, please shed a little sanity! The problem is, analogRead() is always returning zero on both pins I’m using, even if I deliberately remove the sensor attached to the pin and supply a voltage.

The code is designed to work with the Maxbotix EZ1 sonars (in case you’re wondering!).


int sonarWarmupDelay = 250;             // ms delay after powerup before first reading available
int sonarDelayBetweenPings = 25;       // ms to wait between readings
int sonarReadings = 5;              // number of readings to obtain (and to average) to help pad results

// Configure power output
#define totalSonars 2                  // Total number of sonar sensors being polled
int pwr[] = { 6, 7 };                  // Power Pins
int son[] = { 1, 0 };                  // Corresponding data pins to pwr[] array (eg. "Sonar operated on pwr pin 7 is read on analog pin 0)

// Store current sensor readings
int vals[totalSonars];

void setup() {
  // Configure serial
  // Turn off all sonars to start
  for (int i; i < totalSonars; i++) {
   pinMode(pwr[i], OUTPUT);
   pinMode(son[i], INPUT);
   digitalWrite(pwr[i], LOW);  

void loop() {      
      for (int i; i < totalSonars; i++) {                
        vals[i] = getSonarReading(pwr[i], son[i]);            

int getSonarReading(int pwr, int sensor) {
      // powerup the sonar
      int val = 0;
      digitalWrite(pwr, HIGH); 
        delay(sonarWarmupDelay);            // Wait the specified time before obtaining a reading
      for (int i; i<=sonarReadings; i++) {
            val += analogRead(sensor);
        digitalWrite(pwr, LOW);
      val = val / sonarReadings;
      return val;

Asking the obvious - you are using an analogue input pin? The analogue pins are separate to the digital ones, and don't need you to

pinMode(son*, INPUT);*

You have a strange construct:

for (int i; .....

Maybe it's legal, but it's weird. You should explicitly initialize i to 0:

for (int i=0; ...

How do you know it's returning 0?

Hi, well spotted ;)

Serial.println for the analogRead()s was how I found out the values were zero. I cleaned those out for posting. I will correct the omission in my for construct; maybe that'll help.


Hi RuggedCircuits

You were spot on, thank you very much. Corrected the issue and now all seems well.

Thanks very much!