Am I reading my analog right?

I’m trying to test my sonic range sensor and flash the on board LED from the Blink routine when the sensor trips. So far I’m having no luck and I’m not sure where I’ve gone wrong.
-Sensor has analog output, and is plugged into analog port A1.
-Board is the Galileo II.


int led = 13;
int rangePin = A1;
int distance = 0;

// the setup routine runs once when you press reset:
void setup()
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
pinMode(A1, INPUT);

// the loop routine runs over and over again forever:
void loop()
distance = analogRead(rangePin)/1024 * 5; //Vcc/1024 per 5 mm
if (distance < 300) //300mm min distance to trigger LED shift
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW

analogRead(rangePin)/1024 * 5;Do the arithmetic

You didn't say what your problem was

FiddlerForest: distance = analogRead(rangePin)/1024 * 5;  //Vcc/1024 per 5 mm

This is an integer expression and the result of the division by 1024 is always zero. The simplest fix is to use floating point. Something like:

distance = ((float) analogRead(rangePin)) / 1024.0 * 5.0;  //Vcc/1024 per 5 mm

...and the pinMode for A1 isn't necessary

thanks! I'll see if I can get that working!

The sensor has a few modes of operation, one is a PWM where the pulse width is proportional to the distance to object. I've searched the forums a bit and the internet for a while, how do i get the board to measure the pulse width? I'm probably over-thinking the hell out of this, but for the life of me i'm not coming up with an easy way to solve the issue. The sensor updates ~ever 100mS, PWM varies from 300uS to 5000uS if that helps you. I can solve the math later, just keep messing up what might be an easier way to read these sensors.


AWOL: pulseIn?

That does exactly what i needed it to do. Thanks! not sure why my research didn't return that. I've a lot more to learn about arduino! Thanks again!