void main (void)
{
	/*
		Define Variables ---------------------------------------------------------------------
	*/
	// I2C/MSG Q variables
	char c;		// Is this used?
	signed char	length;
	unsigned char	msgtype;
	unsigned char last_reg_recvd;
	i2c_comm ic;
	//unsigned char msgbuffer[MSGLEN+1];
	unsigned char msgbuffer[12];
	unsigned char i;
	int I2C_buffer[];
	int index = 0;
	int ITR = 0;
	int I2C_RX_MSG_COUNT = 0;
	int I2C_RX_MSG_PRECOUNT = 0;
	int I2C_TX_MSG_COUNT = 1;

	// Timer variables
	timer1_thread_struct t1thread_data; 	// info for timer1_lthread
	timer0_thread_struct t0thread_data; 	// info for timer0_lthread
	int timer_on = 1;
	int timer2Count0 = 0, timer2Count1 = 0;

	// UART variables
	uart_comm uc;
	//uart_thread_struct	uthread_data; 		// info for uart_lthread


	// ADC variables
	int ADCVALUE = 0;
	int adc_counter = 0;
	int adc_chan_num = 0;
	int adcValue = 0;
	int count = 0;

	// MIDI variable
	char notePlayed;

	/*
		Initialization ------------------------------------------------------------------------
	*/
	

	// Clock initialization
	OSCCON = 0x7C; // 16 MHz	// Use for internal oscillator	
	OSCTUNEbits.PLLEN = 1; 		// 4x the clock speed in the previous line
	
	
	// UART initialization
	init_uart_recv(&uc);		// initialize my uart recv handling code
	// configure the hardware USART device
  	Open2USART( USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT   & 
		USART_CONT_RX & USART_BRGH_LOW, 31);
	Open1USART( USART_TX_INT_OFF & USART_RX_INT_ON & USART_ASYNCH_MODE & USART_EIGHT_BIT   & 
		USART_CONT_RX & USART_BRGH_LOW, 51);

	//RCSTA1bits.CREN = 1;
	//RCSTA1bits.SPEN = 1;
	//TXSTA1bits.SYNC = 0;
	//PIE1bits.RC1IE = 1;
	IPR1bits.RC1IP = 0;
	
	// I2C/MSG Q initialization
	init_i2c(&ic);				// initialize the i2c code
	init_queues();				// initialize message queues before enabling any interrupts
	i2c_configure_slave(0x9E);	// configure the hardware i2c device as a slave

	// Timer initialization
	init_timer1_lthread(&t1thread_data);	// init the timer1 lthread
	OpenTimer0( TIMER_INT_ON & T0_16BIT & T0_SOURCE_INT & T0_PS_1_8);
	OpenTimer2( TIMER_INT_ON & T2_PS_1_16 /*& T2_8BIT_RW & T2_SOURCE_INT & T2_OSC1EN_OFF & T2_SYNC_EXT_OFF*/); // Turn Off
// ADC initialization
	// set up PORTA for input
	PORTA = 0x0;	// clear the port
	LATA = 0x0;		// clear the output latch
	TRISA = 0xFF;	// set RA3-RA0 to inputs
	ANSELA = 0xFF;	
	initADC();

	// Interrupt initialization
	// Peripheral interrupts can have their priority set to high or low
	// enable high-priority interrupts and low-priority interrupts
	enable_interrupts();
	// Decide on the priority of the enabled peripheral interrupts, 0 is low 1 is high
	IPR1bits.TMR1IP = 0;		// Timer1 interrupt
	//IPR1bits.RCIP = 0;			// USART RX interrupt
	IPR1bits.SSP1IP = 1;			// I2C interrupt
	PIE1bits.SSP1IE = 1;			// must specifically enable the I2C interrupts
	IPR1bits.ADIP = 1;			// ADC interrupt WE ADDED THIS

	
	// set direction for PORTB to output
	TRISB = 0x0;
	TRISD = 0xFF;
	LATB = 0x0;
	ANSELC = 0x00;


	/*
		Hand off messages to subroutines -----------------------------------------------------------
	*/
	// This loop is responsible for "handing off" messages to the subroutines
	// that should get them.  Although the subroutines are not threads, but
	// they can be equated with the tasks in your task diagram if you 
	// structure them properly.
  	while (1) {
		// Call a routine that blocks until either on the incoming
		// messages queues has a message (this may put the processor into
		// an idle mode
		block_on_To_msgqueues();
		/*
			High Priority MSGQ ----------------------------------------------------------------------
		*/
		
		// At this point, one or both of the queues has a message.  It 
		// makes sense to check the high-priority messages first -- in fact,
		// you may only want to check the low-priority messages when there
		// is not a high priority message.  That is a design decision and
		// I haven't done it here.
		length = ToMainHigh_recvmsg(MSGLEN,&msgtype,(void *) msgbuffer);
		if (length < 0) {
			// no message, check the error code to see if it is concern
			if (length != MSGQUEUE_EMPTY) {
				//printf("Error: Bad high priority receive, code = %x\r\n", length);
			}
		} else {
			switch (msgtype) {
				case MSGT_ADC:	{				
					// Format I2C msg
					msgbuffer[6] = (timer2Count0 & 0x00FF);
					msgbuffer[5] = (timer2Count0 & 0xFF00) >> 8;
					msgbuffer[4] = (timer2Count1 & 0x00FF);
					msgbuffer[3] = (timer2Count1 & 0xFF00) >> 8;

					msgbuffer[8] = 0x00;
					msgbuffer[10] = adc_chan_num;
					msgbuffer[11] = 0xaa;			// ADC MSG opcode
					
					// Send I2C msg
					FromMainHigh_sendmsg(12, msgtype, msgbuffer);	// Send ADC msg to FromMainHigh MQ, which I2C
																	// int hdlr later Reads

					
					// Increment I2C message count from 1 to 100
					if(I2C_TX_MSG_COUNT < 100)	{
						I2C_TX_MSG_COUNT = I2C_TX_MSG_COUNT + 1;
					}
					else	{
						I2C_TX_MSG_COUNT = 1;
					}

					// Increment the channel number
					if(adc_chan_num <= 4)	adc_chan_num++;
					else	adc_chan_num = 0;
					// Set ADC channel based off of channel number
					if(adc_chan_num == 0)	SetChanADC(ADC_CH0);
					else if(adc_chan_num == 1)	SetChanADC(ADC_CH1);
					else if(adc_chan_num == 2)	SetChanADC(ADC_CH2);
					else if(adc_chan_num == 3)	SetChanADC(ADC_CH3);
					else if(adc_chan_num == 4)	SetChanADC(ADC_CH4);
					else	SetChanADC(ADC_CH5);
				};
				case MSGT_TIMER0: {
					timer0_lthread(&t0thread_data,msgtype,length,msgbuffer);

					break;
				};
				case MSGT_TIMER2:	{
					timer2Count0++;
					if(timer2Count0 >= 0xFFFF)	{	
						timer2Count1++;
						timer2Count0 = 0;
					}

					break;
				}

				case MSGT_I2C_DATA: { //this data still needs to be put in a buffer
;

						if(msgbuffer[0] == 0xaf)	{
						//FromMainLow_sendmsg(5, msgtype, msgbuffer);
						// The code below checks message 'counts' to see if any I2C messages were dropped
						//I2C_RX_MSG_COUNT = msgbuffer[4];
						
							FromMainLow_sendmsg(9, msgtype, msgbuffer);						
							TXSTA2bits.TXEN = 1;
	/*
							// Send note data to the MIDI device
							//while(Busy2USART());
							putc2USART(msgbuffer[1]);
							//while(Busy2USART());
							Delay1KTCYx(8);
							putc2USART(msgbuffer[2]);
							//while(Busy2USART());
							Delay1KTCYx(8);		
							putc2USART(msgbuffer[3]);
	*/
	
							if(I2C_RX_MSG_COUNT - I2C_RX_MSG_PRECOUNT == 1)	{
								if(I2C_RX_MSG_PRECOUNT < 99)	{
									I2C_RX_MSG_PRECOUNT++;
								}
								else	{
									I2C_RX_MSG_PRECOUNT = 0;
								}
							}
							else	{
								I2C_RX_MSG_PRECOUNT = I2C_RX_MSG_COUNT;
							}
						}
				};
				
	`			
				case MSGT_I2C_DBG: {
					//printf("I2C Interrupt received %x: ",msgtype);
					for (i=0;i<length;i++) {
						//printf(" %x",msgbuffer[i]);
					}
					//printf("\r\n");
					// keep track of the first byte received for later use
					last_reg_recvd = msgbuffer[0];
					break;
				};
				case MSGT_I2C_RQST: {
					//printf("I2C Slave Req\r\n");
					// The last byte received is the "register" that is trying to be read
					// The response is dependent on the register.
					switch (last_reg_recvd) {
						case 0xaa: {
							break;
						}
						/*
						case 0xa8: {
							length = 1;
							msgbuffer[0] = 0x3A;
							break;
						}					
						case 0xa9: {
							length = 1;
							msgbuffer[0] = 0xA3;
							break;
						}*/
					};
					//start_i2c_slave_reply(length,msgbuffer);
					break;
				};
				default: {
					//printf("Error: Unexpected msg in queue, type = %x\r\n", msgtype);
					break;
				};
			};
		}

		/*
			Low Priority MSGQ -----------------------------------------------------------------------
		*/
		
		length = ToMainLow_recvmsg(MSGLEN,&msgtype,(void *) msgbuffer);
		if (length < 0) {
			// no message, check the error code to see if it is concern
			if (length != MSGQUEUE_EMPTY) {
			
			}
		} else {
			switch (msgtype) {
				
				case MSGT_TIMER1: {
					timer1_lthread(&t1thread_data,msgtype,length,msgbuffer);
					break;
				};
				case MSGT_OVERRUN:
				case MSGT_UART_DATA: 
				{
					LATB = 0xFF;
					msgbuffer[11] = 0xBB;
					FromMainHigh_sendmsg(12, msgtype, msgbuffer);
					
					break;
				};
				default: {
					
					break;
				};
			};
		}
 	 }
int main(void)
#endif
{   
    BYTE i, j;
    BYTE TxSynCount = 0;
    BOOL bReceivedMessage = FALSE;
    _U16  m;

    
     #define BAUDRG 77
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/

    ANCON0 = 0XFF;     /*desactiva entradas analogicas*/
    ANCON1 = 0XFF;     /*desactiva entradas analogicas*/

    PPSUnLock();
    PPSOutput(PPS_RP10, PPS_TX2CK2);    // TX2 RP17/RC6
    PPSInput(PPS_RX2DT2, PPS_RP9);     // RX2 RP18/RC7

    PPSOutput(PPS_RP23, PPS_SDO2);    // SDO2 RP23/RD6
    PPSInput(PPS_SDI2, PPS_RP24);     // SDI2 RP24/RD7
    PPSOutput(PPS_RP22, PPS_SCK2);    // SCK2 RP22/RD5

    PPSLock();

     System_PeripheralPinSelect( ExternalInterrupt3, 19);  /*external interrupt 3 B3*/

     BoardInit();
     ConsoleInit();

     Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);

     Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/

     Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/
     Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/
     //Spi_SetMode(SPI_PORT1, 1);
     //Spi_SetMode(SPI_PORT1, 1);


    LED_1 = 1;
    LED_2 = 1;

    Read_MAC_Address();

    LED_1 = 0;
    LED_2 = 0;

                    ConsolePutROMString((ROM char *)"\r\n<MAC Addr:");
                 
                    PrintChar(myLongAddress[3]);
                    PrintChar(myLongAddress[2]);
                    PrintChar(myLongAddress[1]);
                    PrintChar(myLongAddress[0]);

                    ConsolePutROMString((ROM char *)"\r>");

        
    Printf("\r\nStarting Testing Interface for MiWi(TM) PRO Stack ...");
    #if defined(MRF24J40)
    Printf("\r\n     RF Transceiver: MRF24J40");
    #elif defined(MRF49XA)
    Printf("\r\n     RF Transceiver: MRF49XA");
    #elif defined(MRF89XA)
    Printf("\r\n     RF Transceiver: MRF89XA");
    #endif
    Printf("\r\n   Demo Instruction:");
    Printf("\r\n                     Press Enter to bring up the menu.");
    Printf("\r\n                     Type in hyper terminal to choose");
    Printf("\r\n                     menu item. ");
    Printf("\r\n\r\n");
   
    /*******************************************************************/
    // Following block display demo information on LCD of Explore 16 or 
    // PIC18 Explorer demo board.
    /*******************************************************************/
    #if defined(MRF49XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF49XA", 0, TRUE); 
    #elif defined(MRF24J40)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF24J40", 0, TRUE);
    #elif defined(MRF89XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF89XA", 0, TRUE); 
    #endif
    
    //if( (PUSH_BUTTON_1 == 0) || ( MiApp_ProtocolInit(TRUE) == FALSE ) )
    if (PUSH_BUTTON_1 == 1)
    {  

        MiApp_ProtocolInit(FALSE);


        LED_1 = 0;
        LED_2 = 0;

        #ifdef ENABLE_ACTIVE_SCAN
        
            myChannel = 0xFF;
            ConsolePutROMString((ROM char *)"\r\nStarting Active Scan...");
            
            LCDDisplay((char *)"Active Scanning", 0, FALSE);
    
            /*******************************************************************/
            // Function MiApp_SearchConnection will return the number of 
            // existing connections in all channels. It will help to decide 
            // which channel to operate on and which connection to add.
            // The return value is the number of connections. The connection 
            //     data are stored in global variable ActiveScanResults. 
            //     Maximum active scan result is defined as 
            //     ACTIVE_SCAN_RESULT_SIZE
            // The first parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 14, 
            //     or roughly 16 seconds.
            // The second parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            i = MiApp_SearchConnection(10, 0x02000000);
            
            if( i > 0 )
            {
                // now print out the scan result.
                Printf("\r\nActive Scan Results: \r\n");
                for(j = 0; j < i; j++)
                {
                    Printf("Channel: ");
                    PrintDec(ActiveScanResults[j].Channel );
                    Printf("   RSSI: ");
                    PrintChar(ActiveScanResults[j].RSSIValue);
                    Printf("\r\n");
                    myChannel = ActiveScanResults[j].Channel;
                    Printf("PeerInfo: ");
                    PrintChar( ActiveScanResults[j].PeerInfo[0]);
                }
            }
        #endif

    

        /*******************************************************************/
        // Function MiApp_ConnectionMode sets the connection mode for the 
        // protocol stack. Possible connection modes are:
        //  - ENABLE_ALL_CONN       accept all connection request
        //  - ENABLE_PREV_CONN      accept only known device to connect
        //  - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but 
        //                          allow response to active scan
        //  - DISABLE_ALL_CONN      disable all connection request, including
        //                          active scan request
        /*******************************************************************/
        MiApp_ConnectionMode(ENABLE_ALL_CONN);
    
    
        if( i > 0 )
        {
            /*******************************************************************/
            // Function MiApp_EstablishConnection try to establish a new 
            // connection with peer device. 
            // The first parameter is the index to the active scan result, which 
            //      is acquired by discovery process (active scan). If the value
            //      of the index is 0xFF, try to establish a connection with any 
            //      peer.
            // The second parameter is the mode to establish connection, either 
            //      direct or indirect. Direct mode means connection within the 
            //      radio range; Indirect mode means connection may or may not 
            //      in the radio range. 
            /*******************************************************************/
            if( MiApp_EstablishConnection(0, CONN_MODE_DIRECT) == 0xFF )
            {
                Printf("\r\nJoin Fail");
            }
        }    
        else
        {
            /*******************************************************************/
            // Function MiApp_StartConnection tries to start a new network 
            //
            // The first parameter is the mode of start connection. There are 
            // two valid connection modes:
            //   - START_CONN_DIRECT        start the connection on current 
            //                              channel
            //   - START_CONN_ENERGY_SCN    perform an energy scan first, 
            //                              before starting the connection on 
            //                              the channel with least noise
            //   - START_CONN_CS_SCN        perform a carrier sense scan 
            //                              first, before starting the 
            //                              connection on the channel with 
            //                              least carrier sense noise. Not 
            //                              supported on currrent radios
            //
            // The second parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 
            //     14, or roughly 16 seconds.
            //
            // The third parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            #ifdef ENABLE_ED_SCAN
                //LCDDisplay((char *)"Active Scanning Energy Scanning", 0, FALSE);
                ConsolePutROMString((ROM char *)"\r\nActive Scanning Energy Scanning");
                MiApp_StartConnection(START_CONN_ENERGY_SCN, 10, 0x02000000);
            #endif
        }
        
        // Turn on LED 1 to indicate ready to accept new connections
        LED_1 = 1;
    }
    else
    {
        //LCDDisplay((char *)" Network Freezer    ENABLED", 0, TRUE);
        Printf("\r\nNetwork Freezer Feature is enabled. There will be no hand-shake process.\r\n");
        LED_1 = 1;
        DumpConnection(0xFF);
    }
                   
    LCDDisplay((char *)"Start Connection on Channel %d", currentChannel, TRUE);
    LCDDisplay((char *)"Testing Menu on  Hyper Terminal", 0, FALSE);

    while(1)
    {
        /*******************************************************************/
        // Function MiApp_MessageAvailable will return a boolean to indicate 
        // if a message for application layer has been received by the 
        // transceiver. If a message has been received, all information will 
        // be stored in the rxMessage, structure of RECEIVED_MESSAGE.
        /*******************************************************************/
        if( MiApp_MessageAvailable() )
        {
            /*******************************************************************/
            // If a packet has been received, following code prints out some of
            // the information available in rxFrame.
            /*******************************************************************/
            if( rxMessage.flags.bits.secEn )
            {
                ConsolePutROMString((ROM char *)"Secured ");
            }

            if( rxMessage.flags.bits.broadcast )
            {
                ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
            }
            else
            {
                ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");
            }
            PrintChar(rxMessage.PacketRSSI);
            if( rxMessage.flags.bits.srcPrsnt )
            {
                ConsolePutROMString((ROM char *)" from ");
                if( rxMessage.flags.bits.altSrcAddr )
                {
                    PrintChar(rxMessage.SourceAddress[1]);
                    PrintChar(rxMessage.SourceAddress[0]);
                }
                else
                {    
                    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                    {
                        PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);
                    }
                }    
            }

            ConsolePutROMString((ROM char *)": ");
            
            
            for(i = 0; i < rxMessage.PayloadSize; i++)
            {
                ConsolePut(rxMessage.Payload[i]);
            }
            
            // Toggle LED2 to indicate receiving a packet.
            LED_2 ^= 1;
            
            /*******************************************************************/
            // Function MiApp_DiscardMessage is used to release the current 
            // received message. After calling this function, the stack can 
            // start to process the next received message.
            /*******************************************************************/          
            MiApp_DiscardMessage();
            
            bReceivedMessage = TRUE;
            
            /*******************************************************************/
            // Following block update the total received and transmitted messages
            // on the LCD of the demo board. 
            /*******************************************************************/
            LCDTRXCount(TxNum, ++RxNum);
        }
        else
        {
         ++m;

         if(m > 8000)
         {
             m=0;
             //LED_1 ^= 1;
             
                MiApp_FlushTx();
    	        MiApp_WriteData('H');
    	        MiApp_WriteData('o');
    	        MiApp_WriteData('l');
    	        MiApp_WriteData('a');
                MiApp_WriteData('a');
                MiApp_WriteData('a');
    	        MiApp_WriteData(0x0D);
    	        MiApp_WriteData(0x0A);
               MiApp_BroadcastPacket(FALSE);

         }



            if ( ConsoleIsGetReady() )
            {
                //ProcessMenu();
            } 
        }
    }
}
Beispiel #3
0
void main(void)
{
     #define BAUDRG 77

    BYTE SecNum = 0;

   BOOL Tx_Success = FALSE;
   BYTE Tx_Trials = 0, scanresult = 0;
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/

    ANCON0 = 0XFF;     /*desactiva entradas analogicas*/
    ANCON1 = 0XFF;     /*desactiva entradas analogicas*/



    PPSUnLock();

    PPSOutput(PPS_RP10, PPS_TX2CK2);    // TX2 RP17/RC6     icsp
    PPSInput(PPS_RX2DT2, PPS_RP9);     // RX2 RP18/RC7

    PPSOutput(PPS_RP23, PPS_SDO2);    // SDO2 RP23/RD6
    PPSInput(PPS_SDI2, PPS_RP24);     // SDI2 RP24/RD7
    PPSOutput(PPS_RP22, PPS_SCK2);    // SCK2 RP22/RD5

    PPSLock();

     System_PeripheralPinSelect( ExternalInterrupt3, 19);  /*external interrupt 3 B3*/

     BoardInit();
     ConsoleInit();

     Gpios_PinDirection(GPIOS_PORTC, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTC, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     
     //Gpios_PinDirection(GPIOS_PORTD, 4, GPIOS_OUTPUT);  /*pin D4 como salida */

     Open1USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud1USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);


     Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);


     OpenTimer1( TIMER_INT_OFF &T1_16BIT_RW &T1_SOURCE_FOSC_4 & T1_PS_1_8 &T1_OSC1EN_OFF &T1_SYNC_EXT_OFF, TIMER_GATE_OFF  & TIMER_GATE_INT_OFF);



     Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/

     Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/
     Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/

     //Adc_Init(ADC_10BITS);

     LED_1 = 1;
     LED_2 = 0;
     //RLY_1 = 0;
     RLY_2 = 0;

     ON_RADIO = 1;
     ON_MAC = 1;
     ON_TEMP = 1;
     
     StartWirelessConnection();
     
     
     
     //myDevicesRequiredStatus[0] = 0x55;
     
     
     EEPROMRead(&myDevicesRequiredStatus, 0, 1);
     
     if(myDevicesRequiredStatus[0] == 0x55)
     {
         RLY_1 = 1;
         EEPROMCHG = 1;
         ConsolePutROMString((ROM char *)"RELAY ON ");
     }
     
     if(myDevicesRequiredStatus[0] == 0xAA)
     {
         RLY_1 = 0;
         EEPROMCHG = 0;
         ConsolePutROMString((ROM char *)"RELAY OFF ");
     }
     
     
     
     
     

     for(j=0;j<10;j++)
     {
         DelayMs(50);

         LED_1 ^= 1;
         LED_2 ^= 1;
     }
     
     

     LED_1 = 0;
     LED_2 = 0;
     //RLY_1 = 0;
     RLY_2 = 0;
     
    
     
     TickScaler = 4;
     EndDevStateMachine =0;



/*
                                

                                while(!Tx_Success)
                                {
                                    if(myChannel < 8)
                                        scanresult = MiApp_SearchConnection(10, (0x00000001 << myChannel));
                                    else if(myChannel < 16)
                    				    scanresult = MiApp_SearchConnection(10, (0x00000100 << (myChannel-8)));
                                    else if(myChannel < 24)
                    				    scanresult = MiApp_SearchConnection(10, (0x00010000 << (myChannel-16)));
                                    else
                    				    scanresult = MiApp_SearchConnection(10, (0x01000000 << (myChannel-24)));
                                    if(scanresult == 0)
                                    {
                                        Tx_Trials++;
                                        if(Tx_Trials > 2) break;

                                    }
                                    else Tx_Success = TRUE;

                                }
                                if(Tx_Success)
                                {
                                    ConsolePutROMString((ROM char *)"RADIO OK ");
                                }
                                else
                                {
                                    ConsolePutROMString((ROM char *)"RADIO FAIL ");
                                }

*/


     //.VBGOE = 0;
     //ANCON1bits.VBGEN = 1;		// Enable Band gap reference voltage
     //DelayMs(10);
     //VBGResult = Adc_u16Read(15);
     //ANCON1bits.VBGEN = 0;	    // Disable Bandgap

      //Adc_Init(ADC_10BITS);
     
     
     ANCON0 = 0xFF;
     ANCON1 = 0x9F;
     ANCON1bits.VBGEN = 1;		// Enable Band gap reference voltage
     
     
     ADCON0bits.VCFG = 0;    // vreff VDD-VSS
     ADCON0bits.CHS = 0x0F;  // VBG channel select
     
     ADCON1 = 0xBE;
     ADCON0bits.ADON = 1;
     
     //for(j=0;j<16;j++)
     //{
        //myDevicesOutputStatus[j] = j;
     //}
    
     
     //EEPROMWRITE(myDevicesOutputStatus,0,16);
     
     
     //for(j=0;j<16;j++)
     //{
        //myDevicesOutputStatus[j] = 0;
     //}
     
     //DelayMs(500);
     
     EEPROMRead(&myDevicesOutputStatus, 0, 16);
     ConsolePutROMString((ROM char *)"EEPROM READ: ");
     //PrintChar(TemperatureCalibrationValue);
     
     
     for(j=0;j<1;j++)
     {
         PrintChar(myDevicesOutputStatus[j]);
     }
	

     SwTimer3 = 0;
     SwTimer4 = 0;
     
     TRISB&=0xEF;   //JL: Configuro el pin B4 como salida si modificar el estado de los demas pines
     
     while(1)
     {
     /*
         WirelessTxRx();
         WirelesStatus();
         Bypass();
         */
         
         
         //No se utilizaron
         //Menu();
         //Timer1Tick();
         //WirelessTxRxPANCOORD();
         //TaskScheduler();
         
         //JLEstas funciones deben habilitarse para trabajar como repetidora
         
         Timer1Tick();
         Repeater();
        
     }

}