In this project an audio signal is generated to provide a tone of a required frequency. The tones are generated by the hardware timer of the microcontroller. The microcontroller used in this project is the ATTiny2313. Also the duration of the tone can be specified. When a sequence of tones with a specified duration is played by the microcontroller, it can create any music you want.

  The purpose of this project is to build a circuit that can play music stored in the memory of the microcontroller. The music is generated by playing a sequence of tone and duration pairs. The microcontroller reads the pair from the memory and generates a tone with a specified duration. The hardware of the project is a circuit that is based on the ATTiny2313 microcontroller. For this project we use the ATTiny2313 board, which can be purchased at www.bizztronix.eu.The project uses a small speaker, which is driven by an NPN transistor.


 

Schematic and build

The circuit is simple, a transisitor is via a resitor connected to PORTB.2 of the ATTiny2313 which is the output of the PWM hardware timer. The transistor amplifies the signal. The circuit can be build on a breadboard and connected to the ATTiny2313 board. 


Design Code

 A tone consist of notes and their duration. A note is a particular frequency which comes out of the loudspeaker for a certian duration. In this code a tone is saved in a structure with the elements frequency and duration in milli seconds of the datatype unsigned integer.

// program name: music player
// last update: 15.09.2017
// author: www.avrprojects.net
// target device: atmega328
// harware: ATMEGA328 board, LED
// software: WinAVR-20100110 compiler

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#define LED_TOGGLE PINB |= (1<<PINB0)
#define C 784

struct _Note
{
unsigned int durationMS;
unsigned int frequency;
};

struct _Note song1[] = {
//Happy Birthday
{ 360, 784},{ 120, 784},{ 480, 440},{ 480, 784},{ 480, 1048},{ 960, 494}, 
{ 360,    784},{ 120, 784},{ 480, 440},{ 480, 784},{ 480, 1176},{ 960, 1048},{ 360, 784},
{ 120, 784},{ 480, 1568},{ 480, 1320},{ 480, 1048},{ 480, 494},{ 480, 440},{ 240,1396},
{ 480, 784},{ 120, 1396},{ 480, 1320},{ 480, 1048},{ 480, 1176},{ 960, 1048 },{0,0}
}; 

ISR(TIMER1_COMPA_vect)
{
     LED_TOGGLE;
}

void timer_freq(unsigned int freq)
{
    TCCR1B |= (0<<CS11) | (1<<CS10) | (1<<WGM12) ; //  clkio/256 / CTC mode
    TIMSK1 |= (1<<OCIE1A); // Timer/Counter1, Output Compare A Match Interrupt Enable
    OCR1A = (F_CPU/(freq*2*1) -1);
}

int main(void)
{
DDRB |=  (1<<DDB0);//set PB0 as output
char i = 0;
sei();


    while(1)
    {
    unsigned int note = song1[i].frequency;
    unsigned int time = song1[i].durationMS;
    timer_freq(note);
    _delay_ms(time);
    i++;
    }
}