<<< Zpět

#define	B3	0x8
#define	B4	0x10
typedef unsigned char u8;

/*=============================================================================

               PWM sine tone generator (speaker connected to PB3)

=============================================================================*/
/* http://extremeelectronics.co.in/avr-tutorials/sound-generation-by-avr-micro-tutorial-i/ */
/* http://www.csulb.edu/~hill/ee470/Sine_Wave_Generator.pdf */

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

/* sine table */
prog_uint8_t sine[256]={
127, 130, 133, 136, 139, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173,
176, 178, 181, 184, 187, 189, 192, 195, 197, 200, 203, 205, 207, 210, 212, 214,
217, 219, 221, 223, 225, 227, 229, 231, 232, 234, 236, 237, 239, 240, 242, 243,
244, 245, 246, 248, 248, 249, 250, 251, 251, 252, 253, 253, 253, 254, 254, 254,
254, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 247, 246,
245, 243, 242, 241, 239, 238, 236, 235, 233, 231, 229, 227, 225, 224, 221, 219,
217, 215, 213, 210, 208, 206, 203, 201, 198, 195, 193, 190, 187, 185, 182, 179,
176, 173, 170, 167, 164, 161, 158, 155, 152, 149, 146, 143, 140, 137, 134, 131,
128, 125, 121, 118, 115, 112, 109, 106, 103, 100,  97,  94,  91,  88,  85,  82,
 79,  76,  73,  71,  68,  65,  62,  60,  57,  55,  52,  50,  47,  45,  42,  40,
 38,  36,  34,  31,  29,  27,  26,  24,  22,  20,  19,  17,  15,  14,  13,  11,
 10,   9,   8,   7,   6,   5,   4,   3,   3,   2,   2,   1,   1,   0,   0,   0,
  0,   0,   0,   0,   1,   1,   1,   2,   2,   3,   4,   4,   5,   6,   7,   8,
  9,  10,  12,  13,  14,  16,  17,  19,  21,  22,  24,  26,  28,  30,  32,  34,
 36,  39,  41,  43,  45,  48,  50,  53,  55,  58,  61,  63,  66,  69,  72,  74,
 77,  80,  83,  86,  89,  92,  95,  98, 101, 104, 107, 110, 113, 116, 119, 122,
};

int main(void)
{
	u8 i, delay, n;

	/* set PB3 to output mode */
	DDRB |= B3;
	DDRB |= B4;

	PORTB &= ~B4;

	/* initialize TIMER2 to fast PWM mode */
	TCCR2 |= BIT(WGM20)+BIT(WGM21)+BIT(COM21)+BIT(CS20);


	while (1)
	{
		for(delay=1;delay<=50;delay++)
		{
			for(n=0;n<(51-delay);n++)
			{
				for(i=0;i<=254;i++)
				{
					OCR2=pgm_read_byte_near(sine+i);
					_delay_loop_2(delay);
				}
			}
		}

		for(delay=50;delay>=2;delay--)
		{
			for(n=0;n<(51-delay);n++)
			{
				for(i=0;i<=254;i++)
				{
					OCR2=pgm_read_byte_near(sine+i);
					_delay_loop_2(delay);
				}
			}
		}
	}
}

<<< Zpět