So I try to get multiple steppermotors to drive to different positions (at different speeds), using the RAMPS1.4 Shield, the drivers that came with it and a MEGA2560.
But I’m currently stuck having not even one Motor driving as intended.
#define MAX 4480
unsigned long current_time = 0;
//Loopvariables
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int n = 0;
int z = 0;
class Motor
{
int En_pin;
int Step_pin;
int Dir_pin;
int Min_pin;
bool cur_state;
bool prev_state;
unsigned int Speed_motor;
unsigned long Time_motor;
public:
Motor(int En, int Step, int Dir, int Min, unsigned int Speed)
{
En_pin = En;
Step_pin = Step;
Dir_pin = Dir;
Min_pin = Min;
pinMode(En_pin, OUTPUT);
pinMode(Step_pin, OUTPUT);
pinMode(Dir_pin, OUTPUT);
pinMode(Min_pin, INPUT_PULLUP);
Speed_motor = Speed;
Time_motor = 0;
cur_state = 0;
prev_state = 0;
}
bool drive(bool direction)
{
digitalWrite(Dir_pin, richtung);
//digitalWrite(En_pin, 0);
if((cur_state == 0) && (current_time - Time_motor) >= (Speed_motor))
{
prev_state = cur_state;
cur_state = 1;
digitalWrite(En_pin, 0);
digitalWrite(Step_pin, cur_state);
Time_motor = current_time;
return(0);
}
else if((cur_state == 1) && (current_time - Time_motor) >= (Speed_motor))
{
prev_state = cur_state;
cur_state = 0;
digitalWrite(Step_pin, cur_state);
digitalWrite(En_pin, 1);
Time_motor = current_time;
return(1);
}
}
void middle()
{
while(m < MAX/2)
{
current_time = micros();
k = drive(0);
if (k == 1)
{
m++;
k = 0;
//delayMicroseconds(200);
//Serial.println(m);
}
}
}
};
Motor Motor1(38, A0, A1, 14, 200);
void setup()
{
Serial.begin(9600);
m = 0;
}
void loop()
{
current_time = micros();
Motor1.middle();
}
If I comment out the delayMicroseconds(200) and the Serial.print(m), the motor jumps making only one step, if I leave it in, it drives as it should do.
My next problem is that if I increase the speed (decrease the number) when constructing Motor1, it also doesn’t drive to the intended position, but shorter (no problem by decreasing speed).
I came to the conclusion that my m gets incremented to fast, but I can’t wrap my head around why that is the case.
The Motor usually handles speeds as low as 100 Microsecs well and doesn’t jump any steps (at least as I can tell).
Also yes, this is all the code, as I scrapped my old try.
Any help would be greatly appreciated.