#include "Global.h" const int DELTA_THRESHOLD = 5; // Any change below this threshold will not be performed, to smooth random noise in readings const float STEPPER_RATIO = 0.15; // Mapping ration between potentiometer and stepper movement const int STEP_INTERVAL = 1000; // Stepper Driver timing in us (probably no need to change this parameter) int curPos = 0; // Remember the stepper's current position const int numReadings = 500; int readings[numReadings]; // the readings from the analog input int readIndex = 0; // the index of the current reading int total = 0; // the running total int average = 0; // the average void setup() { // Setup Serial which is useful for debugging // Use the Serial Monitor to view printed messages Serial.begin(9600); Serial.println("start"); for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } stepperMotor.write(0, 1000, STEP_INTERVAL); } void loop() { int mappedPotVal = potentiometer.read(); mappedPotVal = map(mappedPotVal, 221, 950, 0, 1024); // subtract the last reading: total = total - readings[readIndex]; // read from the sensor: readings[readIndex] = mappedPotVal; // add the reading to the total: total = total + readings[readIndex]; // advance to the next position in the array: readIndex = readIndex + 1; // if we're at the end of the array... if (readIndex >= numReadings) { // ...wrap around to the beginning: readIndex = 0; } // calculate the average: average = total / numReadings; // send it to the computer as ASCII digits // Serial.println(average); int targetPos = mappedPotVal * STEPPER_RATIO; int deltaPos = targetPos - curPos; // if the difference is pos is very small, don't do anything if (abs(deltaPos) < DELTA_THRESHOLD) { delay(1); return; } // Determine correct direction to move if (deltaPos > 0) stepperMotor.write(1, abs(deltaPos), STEP_INTERVAL); else stepperMotor.write(0, abs(deltaPos), STEP_INTERVAL); curPos = targetPos; }