#include <p18f2525.h>
#include "main.h"
#include <delays.h>
#pragma config WDT = OFF, LVP = OFF, OSC = INTIO67, XINST = OFF
unsigned int Time;
unsigned int avg[3];
void main(void){
unsigned float temp = 0;
unsigned char speed,length;
OSCCON = 0x72; //8MHz clock 500ns cycles
while(!OSCCONbits.IOFS); //wait for osc stable
initPIC();
while(1){
GetPing();
speed = 0;
SetLED(0xFF);
if(Time < 50){
speed = 3;
length = 5;
SetLED(2);
goto PlayIt;
}
if(Time < 80){
speed = 6;
length = 5;
SetLED(1);
goto PlayIt;
}
if(Time < 125){
speed = 9;
length = 5;
SetLED(0);
goto PlayIt;
}
PlayIt:
if(speed>0)
PlayTone(speed,length);
}
}
void SetLED(char led){
LED0 = LED1 = LED2 = 0;
if(led == 0) LED0 = 1;
if(led == 1) LED1 = 1;
if(led == 2) LED2 = 1;
}
void PlayTone(unsigned char time,unsigned char dur){
unsigned char x;
for(x=0;x<dur;x++){
BuzzOut = 1;
Delay10KTCYx(time*2);
BuzzOut = 0;
Delay10KTCYx(time/2);
}
BuzzOut = 0;
}
void initPIC(void){
TRISA = 0x00;
TRISB = 0x00;
TRISC = 0x00;
//----------------------
// PING INIT
//----------------------
PingDir = 0; //PING pin is output
PingOut = 0; //Start with PING pin LOW
//----------------------
// Buzz INIT
//----------------------
BuzzDir = 0;
BuzzOut = 0;
T0CON = 0b00001000;
}
void GetPing(void){
unsigned char x;
unsigned int MyPing = 0;
char Done = 0;
for(x=0;x<3;x++){
PingDir = 0;
PingOut = 0;
Delay16uS();
PingOut = 1;
Delay10TCY();
PingOut = 0;
PingDir = 1;
PingIn = 0;
while(!PingIn);
while(PingIn){
MyPing++;
}
avg[x] = MyPing / 10;
Delay10KTCYx(15);
}
Time = (avg[0]+avg[1]+avg[2]) / 3;
}
//------------------------------------------------------
// Used MPLAB Stopwatch. Exact 16uS from call to return.
//------------------------------------------------------
void Delay16uS(void){
Delay10TCY();
Nop();Nop();
}
//------------------------------------------------------
// Used MPLAB Stopwatch. Exact 400uS from call to return.
//------------------------------------------------------
void Delay400uS(void){
Delay100TCYx(3);
Delay10TCYx(9);
Nop();Nop();Nop();Nop();Nop();Nop();
}