I need help converting my analogRead/Voltage to a distance in Arduino. I have an equation for it but that only applies when you're given a max and a min voltage. I need something that will update as the program runs. I was wondering if anyone could help with that.
Copy the text of your program, click the < CODE > button, then paste the text in the message box. Use images only for non-text purposes.
You are missing:
void setup()
See:
https://docs.arduino.cc/built-in-examples/basics/BareMinimum/
... and inside setup() you need to start serial communications...
Serial.begin(9600);
Here is your complete code... it works.
void setup() {
Serial.begin(9600);
}
void loop()
{
int val;
int var = 0;
int sensorValue = analogRead(A1);
while (var < 100) {
sensorValue = analogRead(A1);
float voltage = sensorValue * (5.0 / 1023.0);
// int Vmm (max Voltage - min Voltage) / .005;
// float distance = (max Voltage - min Voltage) / (Vmm);
Serial.print("Voltage: ");
Serial.println(voltage, 4);
//Serial.print("Distance: ");
//Serial.println(distance, 3);
delay(500);
var++;
}
while (1) { // hang out
}
}
First you need to take a look at the data sheet for your specific sensor. Just as an example I will use a common analog out hall sensor like the AH49E which is an analog out.
This sensor has a sensitivity (output) and things look like this:

Using a good quality DMM measure the sensor's Vout as you move your sensor away from your magnetic source. Measure as you go and note the linearity. Now you can Map voltage out against distance or really bits against distance since we aren't really concerned with voltage and your uC is counting bits against an analog input.
P.S. Pay no attention to the 465 X 309 in my image, I screwed up leaving it in. ![]()
Ron
I have the setup there I just didn’t include it, I figured I only needed to show the loop
Thank you!
Always show everything. It will help with finding the cause.
If super accuracy is not needed and the output is relative linear, take a look at the "map()" statement, it will allow you to set the input range and map it to the output range. You need to to specify both max and min on in and out. Example: Map(A/D reading, min steps, max steps, min out, max out), this is the basic structure not working code.
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
