I use TB6560 as a driver to drive my stepper motor,and I use timer1 in my arduino code,here is my code:
int steps=0;
char input;
#define step_pin 9
#define direction_pin 8
#define ledpin 13
#define expect_steps 1600
#define period 100//speed
#include "TimerOne.h"
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
//shorter the period,higher the buad rate (in order not to be cut by timer)
pinMode(step_pin,OUTPUT);
pinMode(direction_pin,OUTPUT);
pinMode(ledpin,OUTPUT);
digitalWrite(step_pin, LOW);
digitalWrite(direction_pin, LOW);//set direction CW
Timer1.initialize(period);
//Timer1.attachInterrupt(OneStep);
}
void loop() {
// put your main code here, to run repeatedly:
while(!Serial.available()){};
input=Serial.read();
if(input=='1'){
steps=0;
Timer1.detachInterrupt();
}
if(input=='2'){
digitalWrite(direction_pin, LOW);//CW
//Serial.println("CW");
}
if(input=='3'){
digitalWrite(direction_pin, HIGH);//CCW
//Serial.println("CCW");
}
if(input=='4'){
Timer1.attachInterrupt(OneStep);
}
}
void OneStep(){
steps=steps+1;//count the steps
digitalWrite(step_pin,HIGH);//once a move,200steps per 360 degree
digitalWrite(step_pin,LOW);
//Serial.println(steps);
if(steps==expect_steps){//move certain steps
steps=0;
Timer1.detachInterrupt();
}
}
It works well,but I have problems changing the speed.
If I want to change the speed,I have to change the period of timer1.I want the speed to change by itself while the code is running.So that I can make speed planning.However,if I change period and initialize timer in "OneStep" function,it would not work.
How could I change the speed in my code?Or should I use Accelstepper librarie?