//Homing Limit Switch simulator
// for https://forum.arduino.cc/t/stepper-movement/1378295/9?u=davex
const int SensorPin = A0;
const int ResetPin = 2;
// Position and length of "limit switch" activation:
const int LimitSetPoint = 512, LimitWidth = 200;
uint32_t currentMillis;
int sensorPosition = 0;
int lastPosition = -1;
bool limitActive = false, lastLimitActive;
bool homed = false, resetPressed;
int homeOrigin = -1;
void usage() {
Serial.println(R"(This simulates a position sensor with a
"home" switch in the middle. Slide the slider to trigger the
switch and set a "zero".
Note that if you start up with the switch activated, it will
"home" immediately, not at an edge.
Try measuring the homed position of the 'V' and the 'T' after
homing from different starting positions
)");
}
void inputs() {
uint32_t interval = 100;
static uint32_t lastMillis = -interval;
if (currentMillis - lastMillis >= interval) {
lastMillis = currentMillis;
sensorPosition = analogRead(SensorPin);
resetPressed = digitalRead(ResetPin) == LOW;
// Simulate a limit switch somewhere on the LVDT:
limitActive = abs(sensorPosition - LimitSetPoint) * 2 <= LimitWidth;
}
}
void checkHomeByLevel() {
// Home based on switch level
if (!homed && limitActive) {
homed = true;
homeOrigin = sensorPosition;
}
if (resetPressed) {
homed = false;
homeOrigin = -1;
lastPosition = -1;
}
}
void checkHomeByEdge() {
// Home based on switch Edge
static bool armed = false; // arm when off of the switch
if (!homed){
if (armed && limitActive) {
homed = true;
homeOrigin = sensorPosition;
} else {
if(!limitActive){ // arm when clear of the switch
armed = true;
}
}
}
if (resetPressed) {
homed = false;
homeOrigin = -1;
lastPosition = -1;
armed = false;
}
}
void report() {
uint32_t interval = 100;
static uint32_t lastMillis = -interval;
if ((currentMillis - lastMillis >= interval) && (sensorPosition != lastPosition)) {
lastMillis = currentMillis;
lastPosition = sensorPosition;
Serial.print("val:");
Serial.print(sensorPosition);
Serial.print(" Active:");
Serial.print(limitActive ? "Yes" : "No");
Serial.print(" homeOrigin:");
Serial.print(homeOrigin);
if(homed){
Serial.print(" homed:");
Serial.print(sensorPosition - homeOrigin);
}
Serial.println();
}
}
void setup() {
Serial.begin(115200);
usage();
pinMode(ResetPin, INPUT_PULLUP);
inputs();
lastLimitActive = limitActive;
}
void loop() {
// put your main code here, to run repeatedly:
currentMillis = millis();
inputs();
//checkHomeByEdge(); // set home position when switch first switches to LOW
checkHomeByLevel(); // set home position when switch is first detected as LOW
report();
}
0- Simulated LVDT sensor - 1023
____________V__****___T____
Reset Homing