Hello.
What I would need to do is to run a stepper motor while reading an arduino analog sensors. This fills in a bigger project, so I'm writing only the code related to this part.
Before I needed to read the sensor, I was driving the motor by switching the stepping pin from HIGH to LOW with a delay (easy way to drive a stepper). As soon as I had to read it with a different sampling frequency, I switched to use ArduinoThread library, but I immediately faced a problem.
This is precisely what it should be done:
- Arduino gets a signal from a computer
- Arduino start reading the analog sensor with a sampling rate of 1 kHz
- While reading, arduino must generate few stepper pulses of 300 ms, 5 seconds distant, and store the starting time
- Do some analysis
I spare you the part of the signal acquisition and analysis.
Before even try to make long stepper pulses, I've realised that firstly I need to know how to run a single step while keeping on reading the pin. I found it hard because the use of delay inside the thread cause the others to stop, so I would need two threads for the stepper and one for the sensor. The first two should have the same interval (5 seconds), but shifted of X microseconds to have the desired speed.
How can I keep the same interval but shift one thread in time?
#include <Thread.h>
#include <ThreadController.h>
Thread thread1 = Thread();
Thread thread2 = Thread();
Thread thread3 = Thread();
ThreadController control = ThreadController();
void thread1Callback()
{
digitalWrite(2,HIGH);
}
void thread2Callback()
{
digitalWrite(2,LOW);
}
void thread3Callback()
{
//read sensor and do things
return;
}
void setup()
{
pinMode(2,OUTPUT);
thread1.onRun(thread1Callback);
thread1.setInterval(3000);
thread2.onRun(thread2Callback); //??
thread2.setInterval(3000);
thread3.onRun(thread3Callback);
thread3.setInterval(1);
control.add(&thread1);
control.add(&thread2);
control.add(&thread3);
}
void loop()
{
control.run();
}