I have a stepper motor code that I am working on. I am not new to coding but I have hit a weird wall on getting my code to work.
A little backround on the application of the code:
I have a 10k pot that i have linked to a stepper motor. I am using a stepper motor to visually represent the position of the pot. I am using a stepper motor and not a servo motor for increased accuracy (this is for a emulated trim position indicator for a flight sim trim wheel).
I can get my stepper motor to work just fine working with the pot, but i need to have the stepper motor be zeroed so the positioning is correct.
I am trying to get a function to move the stepper a single step in one direction over and over until the limit switch is hit from the attached arm. Then it defines the position of the stepper to zero, stops the servo, then runs the function to follow the pot position.
When the limit switch is pressed, the servo motor stops, but when released it starts again. I put a serial monitor to output the value of "start" and it goes from 1 to 2 when i press the limit switch, but when released turns back to 1. I am very confused why this is happening and have not been able to figure out why.
I have tried changing "start" to a bool with no luck and have tried using static bool and static int with no luck either.
code:
#include <Stepper.h>
//Define the steps of the... stepper motor
#define STEPS 64
//Define Stepper motor pins
Stepper stepper(STEPS, 10, 14, 16, 15);
//Int the variables
int Pval = 0;
int potVal = 0;
int Lhigh;
int Llow;
int limitlow = 2;
int limithigh = 3;
int start = 1;
void setup() {
//set limit switches as pullup inputs
pinMode(limitlow, INPUT_PULLUP);
pinMode(limithigh, INPUT_PULLUP);
//Serial to monitor input of pot
Serial.begin(9600);
//Set the speed of the stepper motor
stepper.setSpeed(200);
}
void loop() {
//Run 1 of the 2 defined functions depending on state of start
if (start = 2)
servozeroed ();
if (start = 1)
zero ();
}
void servozeroed () {
//Read the limit switches and verify they are not pressed
Lhigh = digitalRead(limithigh);
Llow = digitalRead(limitlow);
//Check limit switches and see if stepper motor is at any extremes of movement
if (limithigh == LOW) {
Pval = 512;
}
if (limitlow == LOW) {
Pval = 0;
}
//Read the value of the pot
potVal = map(analogRead(A0), 0, 1023, 0, 512);
if ((Pval != potVal) && (limithigh != HIGH) && (limitlow == HIGH) && ((Pval - potVal) != 1) && ((Pval - potVal) != -1)) {
stepper.step(potVal - Pval);
Pval = potVal;
Serial.println(Pval); //for debugging
}
}
void zero () {
if (start = 1) {
Llow = digitalRead(limitlow);
if (Llow == HIGH) {
stepper.step(1);
}
else {
start = 2;
}
Serial.println(start); //for debugging
}
}