Help with Arduino programming of MaxSonar EZ4

Hello, I’m brand new to arduino development and I’m currently trying to get valid MaxSonar-EZ4 sensor input. I’ve measured the voltage to make sure it is getting 5V, and the AN pin out is at 2.5V if I have the sensor covered up. The analog voltage also fluctuates as expected if I remove the tape and pan it around the room. However, no matter what I do, my arduino seems to report some random analog value around 203-250, regardless of where it is pointed. These random values also happen if don’t have anything connected to the arduino at all (if I disconnect the sensor and run the arduino without anything attached).

So it seems that the sensor is working properly from what I can tell, but I’m not getting good information from my arduino. I’m using an Arduino Duemilanove and a Lilypad, both with the same results. Here is the code that I am using:

// Input
int RANGE_INPUT_PIN = 0;

void setup() 
{
  pinMode(RANGE_INPUT_PIN, INPUT); 
  beginSerial(9600);  
}

void loop() 
{ 
  int rangeVal = analogRead(RANGE_INPUT_PIN);
  delay(500);
  Serial.println( rangeVal );  
}

No doubt there is something simple I am missing here. Does anyone have any ideas?

Thank you for your time!

Have you verified that you have a good connection from the sensor output to the microcontroller (i.e. by reading the voltage at the micro itself)?

And have you verified that you’re working from the same power supply (by reading the voltage between the Arduino ground and the sensor ground pin)?

Have you tried to move the sensor connection to another analog pin? You have a choice of several (pins 14-19 according to the Arduino docs).

This line:

pinMode(RANGE_INPUT_PIN, INPUT);

defined your input pin as a digital input. Remove it and you should get the analog reading your are looking for.

GeneW:
This line:

pinMode(RANGE_INPUT_PIN, INPUT);

defined your input pin as a digital input. Remove it and you should get the analog reading you are looking for.

According to the docs, you have to ensure that the pin is not a digital output; they say to set it as an input first.

From my reading of the docs, the analogRead function is OK with the code that he was using.

Sorry about the double post.

You are right, bikeNomad, a quick test shows that setting the analog pin as a digital input doesn’t effect its ability to read an analog value. At least on my 3.3 volt 168 Pro.

The random values do point to a floating input as you have suggested.

Thank you so much for the suggestions bikeNomad and GeneW. I’m embarrassed to admit that I was plugging into the digital input pins instead of the analog. Definitely a facepalm moment. Everything works great now!