Hi,
I have a project that is controlling the position of a stepper motor by a pot (with switch) or a photocell. If the pot switch is high then the stepper is controlled by the position of the pot. If the pot switch is low the stepper is controlled by a sensor reading. I have the individual parts running correctly but for some reason can't seem to properly do a if... statement to check the switch status and then go to either the pot or sensor subroutine. I am serial printing the sensor, pot, and switch values and they all are correct but I cannot get the sensor subroutine to activate when the switch is low. The program starts with a homing procedure which works properly.
Here is the code:
#include <AccelStepper.h>
// libraries
AccelStepper stepper(1, 2, 3); // 1=easydriver interface, 2=step, 3=dir
// variables
int maxopen = 0;
int maxclose = 3750;
int jit = 15;
int ljit = 15;
int current = 0; // current pot reading
int previous = 0; // previous pot reading
int newpos = 0; // current mapped pot reading
int lcurrent = 0; // current light sensor reading
int lprevious = 0; // previous light sensor reading
int lnewpos = 0; //current mapped sensor reading
int lswitch ; //pot switch status
int dummy ;
// program
void setup() {
Serial.begin(9600); //Initiate Serial com
pinMode(12, INPUT); // set digital input 12 for pot switch
stepper.setMaxSpeed(2500);
stepper.setAcceleration(7500);
// homing and exercise cycle
stepper.runToNewPosition(-1 * (maxclose + 300) ); // run against max opening stop to start homing
stepper.setCurrentPosition(0); // set position as maxopen to home
stepper.runToNewPosition(maxclose); // move to max close
stepper.runToNewPosition(maxopen); // move to max open
}
void dial() {
if ((current > previous+jit) || (current < previous-jit)) { // jitter
newpos = map(current, 1023, 0, 50, maxclose); // map pot to mechanical travel
stepper.runToNewPosition(newpos); // Move stepper to new position
previous = current; // update previous value for next loop
}
}
void sensor() {
if ((lcurrent > lprevious+ljit) || (lcurrent < lprevious-ljit)) { // jitter
lnewpos = map(lcurrent, 0, 1023, 50, maxclose); // map sensor to mechanical travel
stepper.runToNewPosition(lnewpos); // Move stepper to new position
lprevious = lcurrent; // update previous value for next loop
}
}
void loop() {
lswitch = digitalRead(12); // read switch value
current = analogRead(A4); // Pot current value
lcurrent = analogRead(A0) - 150 ; // light sensor current value
Serial.print("switch");
Serial.print(lswitch);
Serial.print(" ");
Serial.print("current");
Serial.print(current);
Serial.print(" ");
Serial.print("lcurrent");
Serial.println(lcurrent);
if (lswitch = 1)
{
dial();
}
else
{
sensor();
}
dummy = 0;
}
Any help is appreciated.
Chris