How would you produce a square wave on a digital system? At first sight, this seems completely trivial. You might think that you could just alternate a series of +1 values with a series of −1 values and be done with it. Well, it doesn’t work like that. An ideal square wave needs infinite bandwith, so creating one is impossible in practice. We have to settle for a finite-bandwidth approximation. In practice, the sampling rate of the system determines the highest frequency that can be allowed (the Nyquist frequency), which sets a hard limit on how good the approximation of the square wave can be. Analytically, the definition of a square wave is given by
Only odd-integer harmonics are present (\(n=1,3,5,\ldots\)). The image below shows a square wave with an increasing number of harmonics. Of course, a “square” wave with only the fundamental harmonic is simply a sine wave. Note that the signal overshoots the theoretical square wave after each transition from low to high and vice versa. This is called the Gibbs phenomenon. The overshoot does not diminish when more harmonics are added. The follow-up article Finite-Bandwidth Square Wave in Samples shows how a bandwidth-limited square wave looks in digital form.
Below is the same sequence of square waves as an audio fragment (using a 1 kHz tone), with an harmonic added every half second, again starting with a single sine. The more the wave starts to resemble a real square wave, the sharper the sound becomes. The ground tone is audible all the time and you can clearly hear tones of increasing frequency being added, although the difference becomes too small to be audible in the last few steps. I am aware that .mp3 and .ogg files (which one you get depends on your browser) are not ideal for these kinds of demonstrations, but the original .wav file sounds very much the same in this case, and is quite a bit larger.
Square Wave with harmonics 1, 3, 5, …, 19