Hey. First of all - sorry for my poor english. I've got a problem with implementing acceleration from library accelstepper to code from book about arduino. Code:
int speed = 100; // desired speed in steps per second
int steps = 0; // the number of steps to make
void setup()
{
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if ( Serial.available()) {
char ch = Serial.read();
if(ch >= '0' && ch <= '9'){ // is ch a number?
steps = steps * 10 + ch - '0'; // yes, accumulate the value
}
else if(ch == '+'){
step(steps);
steps = 0;
}
else if(ch == '-'){
step(-steps);
steps = 0;
}
else if(ch == 's'){
speed = steps;
Serial.print("Setting speed to ");
Serial.println(steps);
steps = 0;
}
}
}
void step(int steps)
{
int stepDelay = 1000 / speed; //delay in ms for speed given as steps per sec
int stepsLeft;
// determine direction based on whether steps_to_mode is + or -
if (steps > 0)
{
digitalWrite(dirPin, HIGH);
stepsLeft = steps;
}
if (steps < 0)
{
digitalWrite(dirPin, LOW);
stepsLeft = -steps;
}
// decrement the number of steps, moving one step each time
while(stepsLeft > 0)
{
digitalWrite(stepPin,HIGH);
delayMicroseconds(1);
digitalWrite(stepPin,LOW);
delay(stepDelay);
stepsLeft--; // decrement the steps left
}
}
Everything works fine (also with my changes: I replaced delay with non-blocking micros(); ):
void step(int steps) {
long stepDelay = 300000L / (8L * speed);
int stepsLeft = steps;
if (steps > 0)
{
PORTB |= 1 << 0;
stepsLeft = steps;
}
if (steps < 0)
{
PORTB &= ~(1 << 0);
stepsLeft = -steps;
}
unsigned long previousMicros = 0;
while (stepsLeft > 0 && digitalRead(homeButton) == 1) {
if ((unsigned long)(micros() - previousMicros) >= stepDelay) {
previousMicros = micros();
PORTB |= 1 << 1;
PORTB &= ~(1 << 1);
stepsLeft--;
}
}
}
but I want acceleration and deceleration for my stepper. I know basics of this, but in this example, I have no idea how to do it...