device = 18F1320
clock = 8 // 8MHz clock
config OSC = INTIO2, WDT = OFF, LVP = OFF
include "USART.bas"
include "CONVERT.bas"
dim NOT_RBPU as INTCON2.7
dim TMR1IE as PIE1.0
dim TMR1IF as PIR1.0
dim TMR2IE as PIE1.1
dim TMR2IF as PIR1.1
dim TMR1 as TMR1L.AsWord
dim Speaker as PORTB.3// speaker output port pin 18
dim SpeakerTris as TRISB.3
//global variables
dim Seed as longword, Tone as byte
dim i as word, count as byte
dim speed as byte
dim IntFlag as bit
//half period delays = clock speed divided by 2*frequency
//note first value (1000) is not a frequency and shouldn't be changed.
const NumTones = 5
const Tones(NumTones+1) as word = (1000,2000000/12000,2000000/10000,2000000/8000,2000000/6000,2000000/4000)
//interrupt routine
interrupt MyInt()
if TMR1IF=1 then
T1CON.0=0 //stop timer
TMR1=-Tones(Tone) //reset period
T1CON.0=1 //restart timer
if Tone=0 then //if silence
Speaker=0 //speaker off
else //otherwise
toggle(Speaker) //make sound
endif
TMR1IF=0 //clear interrupt flag
endif
if TMR2IF = 1 then
TMR2IF=0
Count=Count+1
If Count=50 Then
Count=0
IntFlag=1
endif
EndIf
end interrupt
Sub Delay(Seconds as Word)
Dim x as Word
for x=0 to Seconds
While(IntFlag=0)
Wend
IntFlag=0
next
end sub
function Rand(Range as byte) as byte
dim i as byte, feed as bit, temp as word
for i = 0 to 7 //generate 8 bits
Feed = Seed.30 xor Seed.27 //make new bit
Seed=Seed*2+Feed //shift seed left and add new bit
next
Temp=(Seed and 255) * Range //change Rand from 0 to 255
Rand = Temp/256 //to 0 to (Range-1)
end function
//main code starts here
OSCCON = $72 //select 8MHz internal clock
NOT_RBPU=0 //WPUs on port B
ADCON1=$7f //all digita
TRISB.0=0 //make output
PORTB.0=1 //and high
T1CON = %10000001 //pre=1
Tone=0 //no sound please
TMR1IE=1 //enable timer 1 interrupt
T2CON = %01001110 //pre=16 post=10
PR2 = 249 //=8000000/4/16/10/250 = 50Hz
TMR2IE=1 //enable timer 2 interrupts
enable(MyInt) //set interrupt going
SpeakerTris=0 //Setup Port
Seed=$12345678 //seed random number
speed = 200 //changes via dip switches
USART.SetBaudrate(br9600)
while TRUE
for i = 1 to 5*60 //play for 5 minutes
while IntFlag=0
Tone=Rand(NumTones)+1 //each tone is random frequency
USART.Write(DecToStr(Tone),",")
delayms(speed) //and for 25-200 seconds here is where I want to change
wend
IntFlag=0
next //end for loop
USART.Write(13,10,"Silence,")
Tone=0 //silence
Delay(10*60) //delay 10 minutes
WEND
end