Program a Arduino to output a sine wave / square wave

Hi, having a problem understanding the code to write a simple program. Part 1 is having an Arduino output a sine wave to one of the PWM out pins. The Arduino has a native sin function, which can be used in conjunction with a counter to generate the waveform. Then in Part 2, I later need to modify the code so that the Arduino is outputting an approximated square wave. Not sure where I would add or subtract harmonics of the base sine wave. The ideal is to plug the output from the pin to the input lead of an oscilloscope and see the waveform on the screen and then by adding or subtracting harmonic one can see how distorted the wave gets.

my attempt at the code.

void setup () {
pinMode (13, output);
counter ( value )
counter = 0.001
void loop () {
value = sin(counter);
digital Write (13, value);
counter = counter + 0.001;


The sin() function accepts values in radians as a float.

You must modify your counter value to look like radians of a circle. You should do this in a spreadsheet before attempting to program.

The Arduino can not produce a sine wave on a pin.

You should Google PWM to see what it is all about.

A square wave can be made by toggling an output pin with equal HIGH and LOW periods.

You are jumping in to this without paying your dues, go thru the examples in the IDE.

I’d does but it is way too slow to be used to generate a waveform in real time. What you need to do is to use it to generate a look up table in an array, and then play that out to the PWM. This will not result in you seeing a sin wave on the PWM output unless you change the frequency of the PWM to about 30 to 40 KHz and you put a restoration filter on the PWM output pin.

The look up table should be such that it consists of numbers between zero and 255. With sin(0.0) corresponding to 128.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.