waveform generator using attiny85

As discussed in the previous article ATtiny85 has a special 64MHz clock that can be configured along with Timer/Counter1 to fast digital to analogue conversion.  For doing so, initially the clock source has to be specified for Timer/Counter1. So the 6MHz clock is turned on.
To make Timer/Counter1 act like a digital-to-analogue converter, it has to be activated in PWM mode. This is done by using the values in the OCR1B register to vary the duty cycle. In this manner it can be made a waveform generator

 The interrupts are generated to the output samples by Timer/Counter0. The rate of these interrupts are set to the scale of 8MHz which is prescaled by 8. Prescaling is nothing but dividing the incoming clock pulse to feed the timer. Also, the value of OCR0A is set to 49+1 that results in the output of 20kHz. 

So these generated interrupts calls an ISR (Interrupt Service Routine) i.e. ISR(TIMER0_COMPA_vect) which eventually calculates the output of the sample. 

Combining all the above steps, the code for generating waveforms is as follows:

unsigned int counter;
unsigned int Temp = 857; 			// Middle C

void setup() {
  // Specification of clock source for Timer/Counter1
  PLLCSR = 1<<PCKE | 1<<PLLE;     

  // Activating Timer/Counter1 in PWM mode
  TIMSK = 0;                     			// Turning Timer interrupts to OFF
  TCCR1 = 1<<CS10;               			// 1:1 prescale
  GTCCR = 1<<PWM1B | 2<<COM1B0;  	// PWM B is cleared on matching

  pinMode(4, OUTPUT);            		// Setting PWM output pin

  // Set up Timer/Counter0 for 20kHz interrupt to output samples.
  TCCR0A = 3<<WGM00;             		// Fast PWM
  TCCR0B = 1<<WGM02 | 2<<CS00;  		// 1/8 prescale
  TIMSK = 1<<OCIE0A;             		// Enabling compare match, disabling overflow
  OCR0A = 49;                    			// Divide by 400

void loop() { }

  counter = counter + Temp;
  OCR1B = (counter >> 8) & 0x80;

Square Waveform Generator

The ISR which is mentioned in the above programs generates square waveform as follows:

Thai code is specifically responsible for generating square waveform:

counter = counter + Temp;
OCR1B = (counter >> 8) & 0x80

Triangle Waveform generator

This is much similar to sine wave form in shape but it uses the accumulator that takes the top 8 bits and inverts all of them when the top bit is set. So, the triangular waveform counts from 0 to 127 and then again back down to 0.

The ISR routine in the above code is replaced with the following code to result in triangular waveforms. 

  signed char i, j;
counter = counter + Temp;
i =counter >> 8;
 j = i >> 7;
OCR1B = i ^ j;

This result in the generation of Triangular waveforms as below:

Circuit for Waveform Generation using ATtiny85

Also read:
Timer program in 8051

Spread knowledge

Leave a Comment

Your email address will not be published. Required fields are marked *