I’m trying to understand this code:
#include <pic.h>
#include "delay.h"
#define brisi_flag timer_flag=0
unsigned char timer;
unsigned char impuls;
unsigned char ton_koji_ne_svira;
static bit disable @ (unsigned)&PORTA*8+4;
static bit izlaz @ (unsigned)&PORTA*8+1;
static bit izlaz_inv @ (unsigned)&PORTA*8+0;
static unsigned char stanja @ 0x2e;
static bit stanje_izlaza @ (unsigned)&stanja*8+1;
static bit timer_flag @ (unsigned)&INTCON*8+2;
void
DelayMs_2(unsigned char cnt)
{
unsigned char i;
do { asm("CLRWDT");
if(ton_1)
return;
i = 4;
do {
DelayUs(250);
} while(--i);
} while(--cnt);
}
void
DelayMs(unsigned char cnt)
{
unsigned char i;
do { asm("CLRWDT");
i = 4;
do {
DelayUs(250);
} while(--i);
} while(--cnt);
}
void ton_1_2(unsigned char onaj_drugi_ton)
{
izlaz=0;
izlaz_inv=1;
stanje_izlaza=0;
TMR0=timer;
ton_1_2_start:
brisi_flag;
disable=0;
ton_1_2_sviranje:
while(timer_flag==0)
{
if((TMR0-timer)>=impuls)
{izlaz=0;
izlaz_inv=0;
}
}
brisi_flag;
TMR0=timer;
if(stanje_izlaza==0)
izlaz_inv=1;
else
izlaz=1;
stanje_izlaza=stanje_izlaza+1;
if((PORTA&0x0c)==onaj_drugi_ton)
return;
asm("CLRWDT");
goto ton_1_2_sviranje;
}
void main()
{
CMCON=0x07;//portA su normalni ulazi (za 16F628A)
TRISA=0x0c;
TRISB=0xff;
disable=1;
OPTION=0x81; //WDT na 18 msec, preset TMR0 sa 4
izlaz=0;
izlaz_inv=0;
timer=107;
impuls=0x1d;
ton_1_2(ton_koji_ne_svira);
}
This program generates 800 Hz sound on speaker. I don’t understand how to calculate frequency (it must be something with variables impuls and timer ). This code is for PIC16F628A, it has external oscillator set at 4Mhz.
Here is how I understand the code.
The timer starts at 107. As the timer interrupt triggers on overflow the period is 256-107 = 149 ticks. During each period, the outputs are turned off after IMPULS=29 ticks. Hence you have a 29/149=19% duty cycle. In addition, the pulses alternate between two pins.
OPTION=0x81 sets a 1:4 prescaler for the timer. Hence if the clock runs at 4MHz (period 0.25µs), the timer ticks at 1MHz (period 1µs). Thus a period of 149 ticks should equal 149µs and correspond to a frequency of 6711Hz. Adding the time it takes to start the timer each time the actual frequency is slightly lower.
Are you sure the frequency is 800Hz ? Did you measure it ? Maybe the processor is really running at 500Hz, or there is a global 1:8 prescaler somewhere.