Our team is having a kind of strange issue. Using the documentation provided by MaxBotix, we programmed our distance sensor to measure distance in inches. The trouble is that whenever it ran, it displayed a consistent reading of 512 inches, jumping only very slightly every few seconds. What could be causing this? I’ve attached both the website with the documentation and a code sample.

package org.usfirst.frc.team2557.robot.subsystems;

import org.usfirst.frc.team2557.robot.RobotMap;

import edu.wpi.first.wpilibj.command.Subsystem;

import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**

*

*/

public class Sonar extends Subsystem {

```
public void getDistance(){
//SmartDashboard.putNumber("VoltageToTarget", RobotMap.sonarUnit.getVoltage());
double Voltage = RobotMap.sonarUnit.getVoltage();
double VoltsPerInch = RobotMap.sonarUnit.getVoltage() / 512;
double Distance = Voltage / VoltsPerInch;
SmartDashboard.putNumber("Voltage", Voltage);
SmartDashboard.putNumber("VoltsPerInch", VoltsPerInch);
SmartDashboard.putNumber("Distance", Distance);
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
```

}

The formula you have will always yield a result of 512:

```
double Voltage = RobotMap.sonarUnit.getVoltage();
double VoltsPerInch = RobotMap.sonarUnit.getVoltage() / 512;
double Distance = Voltage / VoltsPerInch;
```

The above is essentially the same as writing:

```
double Distance = RobotMap.sonarUnit.getVoltage() / (RobotMap.sonarUnit.getVoltage() / 512);
```

Which can be rewritten as:

```
double Distance = 512;
```

From the documentation link you provided, it looks like the volts/inch value should be Vcc / 512 where Vcc is the power supplying the sensor (not the voltage returned by the sensors). Assuming the roboRIO is providing 5.0 volts to the sensor, try changing your code to the following:

```
double Voltage = RobotMap.sonarUnit.getVoltage();
double VoltsPerInch = 5.0 / 512.0; // NOTE: .0 is used to avoid integer division
double Distance = Voltage / VoltsPerInch;
```

Since the documentation implies a linear relationship between distance and voltage, you could add a correction (gain) factor to help correct for errors.

Start with a gain of 1.0 (no correction):

```
double Voltage = RobotMap.sonarUnit.getVoltage();
double VoltsPerInch = 5.0 / 512.0; // NOTE: .0 is used to avoid integer division
double Distance = Voltage / VoltsPerInch;
double gain = 1.0;
Distance = Distance * gain;
```

If you then put distances out to the dashboard and find that the sensors is consistently off by a certain percentage you can change the gain setting to compensate.

Good Luck.