/*************************************************************
	SOUND SYNTHESIZER 1.01    
	vincent leclerc           
	may 2003                  
   
	notes:
		+ 2 speakers should be connected to RB3 & RB4
	  	+ uses a PIC16F84A
		+ changed variables form long to int for more RAM space 
		  (ugly but saves space)
	to do:
		+ implement fast fourier algorithm for nicer waves
		  using a digital pot. to control amplitude  
*************************************************************/


/*************************************************************
	CONFIG            
*************************************************************/
#if defined(__PCM__)
#include <16f84a.h>
#fuses HS,NOWDT,NOPROTECT
#use delay(clock=10000000)
#endif


/*************************************************************
	INCLUDES
*************************************************************/
#include <v_tones.c>
#include <stdlib.h>


/*************************************************************
	FUNCTION DECLARATIONS
*************************************************************/
void randomSound(void);
void wah(int freqMin, int freqMax);
void sweep(long from, long to, int speed);


/*************************************************************
	MAIN   
*************************************************************/
void main(void)  {
	long oldscale = 0;
	
	while(TRUE) {
		long scale = 10;
		scale = 10 - (input(PIN_A0) + input(PIN_A1) + input(PIN_A2) + input(PIN_A3) + input(PIN_A4) + input(PIN_B0) + input(PIN_B2) + input(PIN_B5) + input(PIN_B6) + input(PIN_B7));
		scale = scale * 500;
		if (scale != oldscale) {
			sweep(oldscale,scale,25);
		}
		oldscale = scale;
	}
}


/*************************************************************
	RANDOMSOUND 
		randomly generates sounds      
*************************************************************/
void randomSound(void)	{
	generate_tone(rand()%2000,100);		
}


/*************************************************************
	WAH  
		ocillates between randomly generated sounds
		frequencies are in hectahertz to save memory      
*************************************************************/
void wah(int freqMin, int freqMax)	{
	int new, old, delta;
	delta = freqMax-freqMin;
	new = rand()%delta+freqMin;
 	while(TRUE)
   	{
		old = new;
		new = rand()%delta+freqMin;
		sweep(old*100,new*100,100);		
   	}
}


/*************************************************************
	SWEEP
		goes smoothly from one frequency to another 
*************************************************************/
void sweep(long from, long to, int speed)	{
	long i;
	if (from < to) {
		// increase tone
		for (i=from; i<to; i+=speed) {
			generate_tone(i,5);	
		}
	}
	else if (from > to) {
		// decrease tone
		for (i=from; i>to; i-=speed) {
			generate_tone(i,5);	
		}
	}
	else {
		// no sweep necessary
		generate_tone(to,5);
	}
}
