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!).
Thanks!
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
Serial.begin(9600);
// 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);
delay(sonarDelayBetweenPings);
}
digitalWrite(pwr, LOW);
val = val / sonarReadings;
return val;
}