Square-wave generator 31 Hz to 8 MHz


From the analog technique you will know devices to produce tones of different frequencies. Most of them have rotary knobs to select the frequency you want. As the rage of possible frequencies is extremly wide you mostly have a range selector.

We want an Arduino to do this job. And we want a digital display to see the value of the produced frequency.

Some restrictions we will have to accept:

How it was done

The project has to fit on a SYB-46 breadboard. There is only space for a cheap 2-digit LED display type BVN7572SR4 next to the micrcontroller. So whatever frequency is selected you always will see only the two most significant digits.

Details of the implementation

The Arduino offers 3 timers (Timer0 (8 bit), Timer1 (16 bit), and Timer2 (8 bit)). Mostly, Timer2 will be unused.

Which range of frequencies will be possible?

Register TCCR2B
prescaler value
high value of counter
Register OCR2A
frequency in Hertz
7 1024 249 16.000.000 / 1024 / (249+1) / 2 = 31,25
1 1 0 16.000.000 / 1 / (0 + 1) / 1 = 8.000.000

So you get more than 5 decades by turning your knob.

As you can combine 7 prescaler values and 256 high values (OCR2A register) you get 7 * 256 = 1792 frequencies. But some of them are identical or differ from as little as 0.4 per cent from one another.

As the frequency selector will be a potentiometer connected to an analog input you only can get the input values from 0 to 1023.

If you want that the selectable frequencies will differ at least by 1 per cent from each other, you get 676 frequencies that means you have to store 676 pairs of prescalers and ocr2a-values. We save these values in a *.h file and read these values directly from the flash memory.

A potentiometer (any value between 10 kOhm and 1 MOhm will do) connected to analog input A0 gives values from 0 to 1023 which will be mapped to the range from 1 to 676.

As there will be some noise on the analog input we take a sliding average. The side effect is when you start the controller it takes some time until the selected frequency is produced.

Final remarks

When putting the hardware together it showed that the LED display and the controller did not fit on the breadboard- There was an overlap of 0.5 mm. A milling tool had to be used to make them fit.

the source

the parameters for prescaler and OCR2A

contact: nji(at)gmx.de