// For: https://forum.arduino.cc/t/problem-with-nema-17-and-potentiometer/1031505
//
// Formatted the text a little.
// Changed pins to "const int", changed small other things.
// Added AccelStepper library.
// Added a 50Hz millis-timer to sample and average the sensor data.
// Added a low-pass filter.
// Show potentiometer value before and after filtering.
//
#include <AccelStepper.h>
const int stepPin = 6;
const int dirPin = 3;
const int potPin = A6;
AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin);
const int sensorMin = 250; // minimum sensor value
const int sensorMax = 800; // maximum sensor value
float sensorValue; // a global variable for the filtered value
unsigned long previousMillis;
const unsigned long interval = 20; // for 50Hz sample rate
void setup()
{
Serial.begin(115200);
stepper.setMaxSpeed(500);
stepper.setAcceleration(40);
// Set the sensorValue to a initial value.
// To make the filter start with a real value.
sensorValue = getSensor(potPin);
}
void loop()
{
unsigned long currentMillis = millis();
// Sample the input with 50Hz.
// That seems enough and a fixed timing is needed for the filter.
if( currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
float newSensorValue = getSensor(potPin);
Serial.print(newSensorValue);
Serial.print(",");
// Low-pass filter, for example with 5%.
sensorValue = 0.95 * sensorValue + 0.05 * newSensorValue;
Serial.print(sensorValue);
Serial.println();
// To do: Create a dead area.
stepper.moveTo( (long) sensorValue);
}
stepper.run(); // this function makes the stepper motors move
}
// This function gets the sensor data.
// It returns 0...1000 as a floating point.
// Only a part of the potentiometer is used.
float getSensor(int pin)
{
// Take 10 samples and calculate the average.
// The result should be 0...1000.
// Using floating point helps for the low-pas filter.
long total = 0;
for( int i=0; i<10; i++)
{
int pot = analogRead(pin);
pot = constrain(pot, sensorMin, sensorMax);
pot = map(pot, sensorMin, sensorMax, 0, 1000);
total += pot; // calculate the total of the samples
}
return(float(total) / 10.0); // the average as a floating point
}