Example Code for Arduino-Linear Position Detection

Last revision 2026/02/07

Arduino Linear Position Detection tutorial guides users through setting up DFRduino UNO with Linear Flexible Potentiometer. Follow hardware and software preparation, utilize the wiring diagram, upload sample Arduino code, and monitor results through the Serial monitor.

Hardware Preparation

Software Preparation

Wiring Diagram

Other Preparation Work

  • Upload the following code and open Serial monitor to check the output

Sample Code

/*!
const int sensorPin = A0;         // Connect the sensor output to analog pin A0
const float Vcc = 5;              //Input pin voltage   5V   
const float Vin = 3.3;            //Input pin voltage   5V   
const float totalLength = 280.0;  // Total Sensor Length (mm)


void setup() {
  Serial.begin(9600);
  Serial.println("Current Position (mm)	Original Voltage (V)");
 }

void loop() {
  float rawVoltage = analogRead(sensorPin) * (Vcc/1023);    //5V Input
  //float rawVoltage = analogRead(sensorPin) * (Vin/((Vin/Vcc)*1023));    //3.3 Input
 
  float actualVoltage = rawVoltage;
  float position = 0.0;
  position = (rawVoltage / Vcc) * totalLength;

 // Position limiting (0-280mm)
  position = constrain(position, 0.0, totalLength);


  Serial.print("Current Position:");
  Serial.print(position);
  Serial.print(" mm\t\t");
  Serial.print("Current Position:");
  Serial.print(rawVoltage);
  Serial.println(" V");

  delay(50);  
}

Result

Was this article helpful?

TOP