#define STEP_PIN 2 // Step
#define DIR_PIN 5 // Direction
// With a 1024 prescaler, max step time about 4 second
//#define PRESCALER 1024
// With a 256 prescaler, max step time about 1 seconds
#define PRESCALER 256
bool motorDir = false;
String rxBuf;
// Set Timer1 interrupt frequency
void setStepDelay(float stepTime) {
float t1Register = F_CPU / (PRESCALER * (2 / stepTime)) - 1 ;
noInterrupts();
TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; // Clear registers
OCR1A = (uint16_t) t1Register; // MUST be > 0 and <65536
TCCR1B |= (1 << WGM12); // CTC
TCCR1B |= (1 << CS12) | (0 << CS11) | (0 << CS10); // Prescaler 256
//TCCR1B |= (1 << CS12) | (0 << CS11) | (1 << CS10); // Prescaler 1024
TIMSK1 |= (1 << OCIE1A); // Output Compare Match A Interrupt Enable
interrupts();
Serial.print("OCR1A: ");
Serial.println((uint16_t) t1Register); // MUST be > 0 and <65536
}
// Timer 1 Interrupt Service Routine. If motor must run, simply toggle the state of STEP_PIN
ISR(TIMER1_COMPA_vect) {
digitalWrite(STEP_PIN, digitalRead(STEP_PIN) ^ 1);
}
void getNewValue() {
while (Serial.available()) {
float newValue = Serial.parseFloat();
if (newValue) {
setStepDelay(newValue);
}
}
}
void setup()
{
rxBuf.reserve(128);
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
Serial.begin(115200);
Serial.println("Insert a value for step time (eg. 0.01):");
motorDir = true;
digitalWrite(DIR_PIN, motorDir); // Set DIR pin value
setStepDelay(0.05);
}
void loop()
{
getNewValue();
}