Creating a 1KHz clock O/P

Hi All,

I have been trying to find the easiest way to create a 1KHz clock to clock a digital pot. It doesn't have to be super accurate and it also doesn't have to have a 50/50 duty cycle. I want to try using this on an ATTiny 25/45/85. I saw something about a tone library and it seems pretty simple.

What is the question?

The tone() function.

If you use a tiny85 you will need to install a core. I like the ATTinyCore core by Spence Konde.

Or use the Digispark board.

tone(myPin,1000);

Overkill, but you can gut the non-useful code:
http://www.technoblogy.com/show?20W6

I was planning on using his core.

And the question was ease of use. I have been reading so many threads that seem to make it so difficult using timers and prescalers, I am guessing thats what the Tone lib does.

Easy to use:

while(1) {
digitalWrite(pin, 1);
delayMicroseconds(498);
digitalWrite(pin,0);
delayMicroseconds(498);
}

To eliminate glitches, make sure interrupts are off.

Perhaps try reading the datasheet and make up your own mind.

If I use this option can the MCU be doing other stuff?

No.

Looks like Tone wins.

You can do the same sort of thing as @jremington's code with millis() for timing.

Blink without delay().
Beginner's guide to millis().
Several things at a time.

This demo give 1KHz out on pin 4.

const byte outPin = 4;

void setup()
{
    Serial.begin(115200);
    pinMode(outPin, OUTPUT);
}

void loop()
{
  static unsigned long timer = 0;
  unsigned long interval = 496;
  if(micros() - timer >= interval)
  {
   timer = micros();
   digitalWrite(outPin, !digitalRead(outPin));
  }
}

To get 1 kHz the interval in previous example should be 500.

It will have significant jitter on the output. The tone function (or other way using times) is much more reasonable.

No. digitalWrite and Read take about 2 us.

Why is it so important that the clock to a digital pot be exactly (or close to ) 1kHz?

Which pot are you using?

I missed you are not using it well. For better consistency you should use
timer+=interval;
instead of
timer=micros();
If you add anything nontrivial to your code the frequency will decrease.

There are a lot of things you are missing, including the fact that it is not my code you are "correcting".

I am using an AD5227BUJZ10. A nice and simple up/down pot. Also accuracy is not that important, +- 20Hz or so would be fine.

Why are you "clocking" the AD5227BUJZ10? It seems to just have a kind of SPI interface.

That pot can be clocked at up to 50MHz; again, why 1kHz +/- 20Hz? What's special about the clock rate? What in your code/project requires this specific clock rate?

Also, if you used tone() or a direct timer manipulation, how do you determine how many clock pulses are sent? You've only got 64 steps to work with after all...

The clock input can not be used by itself. It must be synchronized with the *CS and U/*D inputs. You can't do that with tone().