Control Arduino Frequency

Hello All,

I am driving a stepper motor with an Arduino Uno and a stepper motor driver. I was wondering how to control the frequency from the Arduino.

I understand that the code to pulse the pin on the Arduino is:

void loop()
{
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(Delay);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(Delay);
}

How do I determine the "Delay" value to achieve, let's say, a 440 Hz frequency?

Thanks in advance for any insight!

There's a stepper library. The Arduino can output PWM in hardware, so you don't need precise timing loops like that.

How do I determine the "Delay" value to achieve, let's say, a 440 Hz frequency?

If you really want to do it that way, it would be half of the period of 440 Hz wouldn't it? That's not exactly hard to work out.

1/440 = .002272

So the period is 2272 µS.

I'll let you work out what half of that is.

PLEASE don't use delay. Because if you get it right, the next thing you'll be wanting, is a method to do something else at the same time.

If you want a step rate of 440 hz that's about 2272 microseconds per step

So you could do it something like this.

unsigned long stepDelay=2272;
int stepPin=3;//Just something I picked at random


void setup()
{
pinMode(stepPin,OUTPUT);
}

unsigned long lastStep=0;
bool lastState=0;

void loop()
{
unsigned long t= micros();

if((t-lastStep) >= stepDelay)
  {lastState= !lastState;
   digitalWrite(stepPin,lastState);
   lastStep += stepDelay;   
  }

//then you can have other stuff happening here too.
//PERHAPS EVEN UPDATING THE VALUE OF stepDelay based on something else

}