Hi everybody,
I have a question regarding an arduino code controlling the rotary speed of 26 stepper motors attached to an arduino Mega 2560. I generate different rotary frequencies for each stepper using the timer1() library.
Since the stepper motors rotate in audio frequencies, the conventional digitalWrite() function is not fast enough for that purpose. I have tried several options (like digitalWritefast(), digitalWrite2()), but until now all my attempts have failed.
Here is the code, which is a excerpt from a monster longish code, so please don't get confused.
The crucial part are the 3 digitalWrite() functions in the void togglePin() function.
How could I speed them up?
Any help is highly appreciated!
#include <TimerOne.h>
#define RESOLUTION 40 // Resolution of our timer
const byte firstPin = 2;
const byte lastPin = 53;
//Setup pins (Even-odd pairs for step control and direction)
void setup(){
for (byte x = firstPin; x <= lastPin; x = x + 1) {
pinMode(x, OUTPUT);
delay(2); }
Timer1.initialize(RESOLUTION); // Set up a timer at the defined resolution
Timer1.attachInterrupt(tick); // Attach the tick function
Serial.begin(57600);
}
// Function called by the timer inturrupt at the specified resolution.
void tick() {
/* If there is a period set for a certain pin, count the number of
ticks that pass, and toggle the pin if the current period is reached. */
byte i;
for(i = firstPin ; i <= fddAmount; i=i+2) {
if (period[i]>0){
currentTick[i]++;
if (currentTick[i] >= period[i]){
togglePin(i,i+1);
currentTick[i]=0;
}
}
}
}
void togglePin(byte pin, byte direction_pin) {
//Switch directions if end has been reached
if (currentPosition[pin] >= MAX_POSITION[pin]) {
currentState[direction_pin] = HIGH;
digitalWrite(direction_pin,HIGH);
}
else if (currentPosition[pin] <= 0) {
currentState[direction_pin] = LOW;
digitalWrite(direction_pin,LOW);
}
//Update currentPosition
if (currentState[direction_pin] == HIGH){
currentPosition[pin]--;
}
else {
currentPosition[pin]++;
}
//Pulse the control pin
digitalWrite(pin,currentState[pin]);
currentState[pin] = ~currentState[pin];
}
arduino_forum.ino (1.56 KB)