I want to run a stepper motor with ldr at the same time, but im having a hard time running both at the same time :(. I know that i must use millis but i cant figure out how to do it.
Heres the code
const int s = 200;
Stepper myStepper(s, 8,9,10,11);
unsigned long currentmillis = 0;
unsigned long previousmillis = 0;
const int ledpin=13;
int buttonpin =2;
int interval = 50;
int interval2 = 200;
unsigned long currentmillis2 = 0;
unsigned long previousmillis2 = 0;
currentmillis = millis();
button = digitalRead(buttonpin);
if(currentmillis - previousmillis >= interval)
Av = analogRead(A);
previousmillis = currentmillis;
if(currentmillis - previousmillis2 >= interval2)
previousmillis2 = currentmillis;
You have blocking code that completely destroys your timing.
The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords.
if you set the speed to, say, 1 RPM and called step(100) on a 100-step motor, this function would take a full minute to run.
So while the step command is executing the program is hung there (code is "blocking")
How long does this take?
From the Stepper reference:
keep the speed high and only go a few steps with each call to step().
And using delay() in a program that can't tolerate blocking is BAD.
In my opinion, the best solution is to install the
AccelStepper library. It has non-blocking methods for controlling a stepper. Also it will work with multiple steppers, the Stepper library will not.
You have the idea (BWOD), just need to watch out for blocking code. I'll save the button for later.
@groundfungus thank you for the fast reply. I just downloaded accelstepper library, Im trying to figure out how to use it. By the way it takes approx of 22seconds to finish (mystepper.step(7140)
The AccelStepper library has a steep learning curve, but if you run the examples and play with the numbers it will become clear how it works. When using the non-blocking stepper functions, remember that you must call run() method often. That means every time through a tight loop() (loop() executes often, like max 50 milliseconds loop time).
You may got some ideas from these links
Several Things at a Time
Planning and Implementing a Program
Both are written in such a way that each function completes in a very short time and allows hundreds or thousands of iterations of loop() every second.