ad space

How to generate Sine Wave with Arduino

oscilloscope sine wave

Here we will show how we can produce sine wave from Arduino by generating square wave and using passive low pass filter(LPF). With Arduino it is possible to generate square wave upto 8MHz. There are various modes such as Fast PWM, Phase correct PWM, CTC mode. Here we will use the CTC mode(Clear Timer on Compare match). To make the calculation easier we will use online ATmega calculator and low pass filter online calculator.

 The following shows Arduino nano generating square wave and the fourth order passive low pass filter on breadboard.

Arduino Nano Low Pass filter

The corresponding schematic diagram of the Arduino Nano and Filter is shown below.

The Arduino Nano is used to generate 1.95KHz square wave signal at digital pin 6 using CTC mode(see Programming ATmega328p in CTC mode for details). The value to be loaded in the OCR0A register to generate 1.95KHz signal is 63 with prescalar of 64. The ATmega timer/counter calculator can be used to calculate the required value to be loaded into the OCR0A register. Following shows screenshot of the calculator used here.

The Arduino program code to generate 1.95KHz square wave signal at pin 6 in CTC mode with prescalar of 64 is provided below.

void setup () {
  //Pin 6 (OC0A) is output
  pinMode(6, OUTPUT);
  // reset timer 0 control registers
  TCCR0B = 0;   
  TCCR0A = 0;
  
  // Load 63 to generate 1.95 kHz sq.wave
  OCR0A = 63; 
  // Toggle OC0A on compare match, WGM 2 (CTC)
  TCCR0A = (1 << COM0A0) | (1 << WGM01); 
  // Start the timer, with 64 prescalar
  TCCR0B = (1 << CS00) | (1 << CS01); 
}

void loop() {

}

To obtain sine wave signal of the same frequency from the square wave generated above we can apply simple passive RC filter. For this we can calculate the resistor and capacitor value using the online passive filter calculator. Sine our signal frequency is 1.95KHz and if we select capacitor of 0.1uF then using the calculator we obtain resistor value of 820Ohm.

RC filter calculator

This is how we can easily generate square wave signal with the help of the two calculators.

Now the following shows the signal captured by the digital oscilloscope.

sine wave from arduino on DSO

The following video shows sine wave, sawtooth wave, triangle wave from the first order, second order, third order RC filter.


 So in this way we can easily generate sine wave from square wave using Arduino Nano in CTC mode.

Post a Comment

Previous Post Next Post