/*
 * "Copyright (c) 2008 Robert B. Reese, Bryan A. Jones, J. W. Bruce ("AUTHORS")"
 * All rights reserved.
 * (R. Reese, reese_AT_ece.msstate.edu, Mississippi State University)
 * (B. A. Jones, bjones_AT_ece.msstate.edu, Mississippi State University)
 * (J. W. Bruce, jwbruce_AT_ece.msstate.edu, Mississippi State University)
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose, without fee, and without written agreement is
 * hereby granted, provided that the above copyright notice, the following
 * two paragraphs and the authors appear in all copies of this software.
 *
 * IN NO EVENT SHALL THE "AUTHORS" BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE "AUTHORS"
 * HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * THE "AUTHORS" SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE "AUTHORS" HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
 *
 * Please maintain this header in its entirety when copying/modifying
 * these files.
 *
 *
 */
#define DEFAULT_BAUDRATE 57600
#include "pic24_all.h"
#include <stdio.h>

/** 
 *  Uses an external potentiometer to control the tone produced by an 
 *  output speaker.
 *  
 */
#define CONFIG_SPEAKER()  CONFIG_RB14_AS_DIG_OUTPUT()
#define SPEAKER  _LATB14    //_LATB14 is port register for RB14
#define VREF 3.3  //assume Vref = 3.3 volts

void playTone(uint16, uint32);

int main (void) {
	uint16 u16_adcVal;

	configClock();
	CONFIG_SPEAKER();
	SPEAKER = 0;
	CONFIG_AN0_AS_ANALOG();
  
  // Configure A/D to sample AN0 for 31 Tad periods in 10-bit mode
  // then perform a single conversion.
	configADC1_ManualCH0(ADC_CH0_POS_SAMPLEA_AN0, 31, 0);  
	while (1) {
		u16_adcVal = convertADC1();   //get ADC value
		u16_adcVal /= 2;
		playTone(u16_adcVal, 50);
	} //end while(1)
}

void playTone(uint16 tone, uint32 duration) {
// tone is the tone frequency in cycles per second
// duration is the length of time the tone is played
// in milliseconds
	uint32 pulseLength_us = 1000000 / (2 * tone);
	uint32 i, duration_us = duration*1000;

	if (tone) {
		for (i=0; i < duration_us; i += 2*pulseLength_us) {
			SPEAKER = 1;
			DELAY_US(pulseLength_us);
			SPEAKER = 0;
			DELAY_US(pulseLength_us);
		}
	}
	else {
		DELAY_MS(duration);
	}
}
