/*
 * Progetto di scacciazanzare basato su PIC16C84
 * Versione 2.0 - 23.05.2013
 * prima versione: 07.2000
*/
#include <xc.h>

#ifndef _XTAL_FREQ
#define _XTAL_FREQ 4190000
#endif

#pragma config FOSC = XT, WDTE = OFF, CP = OFF, PWRTE = OFF

#define LED  PORTBbits.RB3  // RB3: LED...
#define SPK1 PORTBbits.RB4  // RB4: Speaker +
#define SPK2 PORTAbits.RA2  // RA2: Speaker -

#define LED_ON (LED=0);
#define LED_OFF (LED=1);

#define Factor 1           // Freq. max = 1 / (2*Factor) [us] = ca 41 KHz
unsigned char rit;

void sound(void){
    unsigned int i;
    unsigned char lambda;

    lambda=8;
    do{
        for(i=0;i<4000;i++){
            rit=lambda*Factor;
            SPK1=0;
            SPK2=1;
#asm
loop1:      decfsz _rit
            goto   loop1
#endasm
            rit=lambda*Factor;
            SPK1=1;
            SPK2=0;
       #asm
loop2:      decfsz _rit
            goto   loop2
#endasm
        }
        lambda--;
        //PORTBbits.RB0=0;
        //__delay_ms(1);
        //PORTBbits.RB0=1;
    }while (lambda);
    SPK1=1;
    SPK2=1;
    __delay_ms(500);
}

void main (void){
    TRISA=0x00;	// tutto output
    TRISB=0x00;
    PORTA=0xff;	// tutte le uscite ad 1
    PORTB=0xff;
    do{
        sound();
	LED_ON;
	__delay_ms(50);
	LED_OFF;
    }while (1);
}
