Hey everyone, so my boss told me to pick a task to do and complete it so the current goal is to - Have a stepper motor hit an limit switch and that limit switch to light up 6 LEDs and then to turn off when the switch is released.
This works, for about 3-4 clicks then the LEDS have some random behaviour, sometimes they will flash really quickly, not turn on at all or will light up and stay lighted up until the switch is pressed again. Could anyone show me what i've done wrong so I can make this code more stable? That would be amazing. Here is my code:
#include <Stepper.h>
// Stepper Settings
const float STEPS_PER_REV = 32;
const float GEAR_RED = 64;
const float STEPS_PER_OUT_REV = STEPS_PER_REV * GEAR_RED;
int StepsRequired;
Stepper steppermotor(STEPS_PER_REV, 8, 10, 9, 11);
//LED Settings
int LED[6] = { 3, 4, 5, 6, 7, 12 };
volatile bool ledState = false;
//LIMIT SWITCH
volatile int limitSwitchPin = 2;
void setup()
{
pinMode(LED[0], OUTPUT);
pinMode(LED[1], OUTPUT);
pinMode(LED[2], OUTPUT);
pinMode(LED[3], OUTPUT);
pinMode(LED[4], OUTPUT);
pinMode(LED[5], OUTPUT);
// pinMode(ledState, OUTPUT);
pinMode(limitSwitchPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), updateLEDS, FALLING);
Serial.begin(9600);
}
void loop()
{
clockWise();
//updateLEDS();
}
void clockWise()
//Turn the stepper motor to hit the limit switch
{
StepsRequired = -STEPS_PER_OUT_REV / 2;
steppermotor.setSpeed(1000);
steppermotor.step(StepsRequired);
//Serial.println("clockWise");
}
void updateLEDS()
{
if (digitalRead(limitSwitchPin) == LOW) {
ledState = !ledState;
digitalWrite(LED[0], ledState);
digitalWrite(LED[1], ledState);
digitalWrite(LED[2], ledState);
digitalWrite(LED[3], ledState);
digitalWrite(LED[4], ledState);
digitalWrite(LED[5], ledState);
}
}
/* else {
if (digitalRead(limitSwitchPin) == LOW) {
ledState = !ledState;
digitalWrite(LED[0], ledState);
digitalWrite(LED[1], ledState);
digitalWrite(LED[2], ledState);
digitalWrite(LED[3], ledState);
digitalWrite(LED[4], ledState);
digitalWrite(LED[5], ledState);
}
} */
}
You may wonder, "Why is he using interupts for such a simple task?" Well, for some reason the stepper motor blocks the code of anything else that is happening in the background so I had no choice other than to use an interrupt.