How to generate square wave using Arduino

Hi folks i am trying to generate a square wave of frequency 256KHz but iam not able to; maximum i am able generate upto 65KHZ

this is the code ia m using

int out = 9;

void setup() {
pinMode(out, OUTPUT);

void loop() {
int state = 0;

if(state == 0)
digitalWrite(out, LOW); state = 1; }
{ digitalWrite(out, HIGH); state = 0; }

If you're trying to do something fast, it's best to keep your code simple.

That is not the way to generate a fast square wave. The micro seconds delay has a resolution of 4 microseconds and digitalWrite takes too long.
Assuming you don't want to do anything else then change them to the direct port access equivlent instructions.

thanks grumpy_mike can u help me with the instructions i am not used to it


Thanks mike :slight_smile:

You could generate 253.97 or 258.06kHz by programming one of the timers
to count at full rate and wrap every 63 or 62 clock cycles (for a 16MHz system clock).

Arduino Due (<13$) can generate much higher frequencies.
DueVGA library generates more than 30MHz for 960x720 monochrome display @47Hz
(not counting invisible pixels outside 960x720 area: 96072047/1024/1024=30.98):


Thanks MarkT can u please help me in coding timers i’m not used to it

What exactly do you want to do? Generate a fixed frequency or a variable one? And why?

Hint - other people have done this, there is a search facility, you might find good examples if you look