示例#1
0
void MyWIFI_Init(void) {

    // Configure Pins for MRF24J40MB
    mPORTESetBits(RST_WIFI);
    mPORTESetPinsDigitalOut(RST_WIFI);

    mPORTBSetBits(WIFI_HIB);
    mPORTBSetPinsDigitalOut(WIFI_HIB);

    mPORTBClearBits(WIFI_WP);                // Has to be pulled low
    mPORTBSetPinsDigitalOut(WIFI_WP);
/*
    // Configure the INT4 controller for WIFI
    // Set RD11/INT4 as input
    mPORTDSetPinsDigitalIn(BIT_11);
    // Clear corresponding bits in INTCON for falling edge trigger
    INTCONCLR = _INTCON_INT4EP_MASK;
    // Set up interrupt prioirty and sub-priority
    INTSetVectorPriority(INT_EXTERNAL_4_VECTOR, My_INT_EXTERNAL_4_PRIORITY);
    INTSetVectorSubPriority(INT_EXTERNAL_4_VECTOR, My_INT_EXTERNAL_4_SUB_PRIORITY);
    // Clear the interrupt flags
    INTClearFlag(INT_INT4);
    // Enable INT4
    INTEnable(INT_INT4, INT_ENABLED);
 */
}
示例#2
0
void initialiseIO()
{
	//Led Fault
	mPORTBSetPinsDigitalOut(BIT_8);
	PORTSetBits(IOPORT_B, BIT_8);
	//Led Alert
	mPORTBSetPinsDigitalOut(BIT_9);
	PORTSetBits(IOPORT_B, BIT_9);

	//Relais 1
	mPORTDSetPinsDigitalOut(BIT_1);
	PORTSetBits(IOPORT_D, BIT_1);
	
	//Relais 2
	mPORTDSetPinsDigitalOut(BIT_2);
	PORTSetBits(IOPORT_D, BIT_2);
	
	//Address
	mPORTESetPinsDigitalIn(BIT_0);
	mPORTESetPinsDigitalIn(BIT_1);
	mPORTESetPinsDigitalIn(BIT_2);
	mPORTESetPinsDigitalIn(BIT_3);
	mPORTESetPinsDigitalIn(BIT_4);
	mPORTESetPinsDigitalIn(BIT_5);
	mPORTESetPinsDigitalIn(BIT_6);
	mPORTESetPinsDigitalIn(BIT_7);	
}
示例#3
0
void MyMIWI_Init(void) {

    // Configure Pins for MRF24J40MB
    mPORTESetBits(RST_MIWI);
    mPORTESetPinsDigitalOut(RST_MIWI);

    mPORTBSetBits(MIWI_WAKE);
    mPORTBSetPinsDigitalOut(MIWI_WAKE);

    // Configure the INT3 controller for MIWI
    // Set RD10/INT3 as input
    mPORTDSetPinsDigitalIn(BIT_10);
    // Clear corresponding bits in INTCON for falling edge trigger
    INTCONCLR = _INTCON_INT3EP_MASK;
    // Set up interrupt prioirty and sub-priority
    INTSetVectorPriority(INT_EXTERNAL_3_VECTOR, My_INT_EXTERNAL_3_PRIORITY);
    INTSetVectorSubPriority(INT_EXTERNAL_3_VECTOR, My_INT_EXTERNAL_3_SUB_PRIORITY);
    // Clear the interrupt flags
    INTClearFlag(INT_INT3);
    // Enable INT3
    INTEnable(INT_INT3, INT_ENABLED);

    // WARNING : Change in file MRF24J40.c in Microchip Application Library
    // the line : void __ISR(_EXTERNAL_1_VECTOR, ipl4) _INT1Interrupt(void)
    // by       : void __ISR(_EXTERNAL_3_VECTOR, ipl4) _INT3Interrupt(void)
}
示例#4
0
void MyFlash_Init(void)
{
    unsigned int    intStatus;
    unsigned int    theStatus;
    char            theStr[64];

    // Configure Flash Pins (Port B) and set to 1 (default value)
    mPORTBSetBits(FLASH_WP | FLASH_HOLD);
    mPORTBSetPinsDigitalOut(FLASH_WP | FLASH_HOLD);

    // Set the Block Protection bits (BP3-0) to 0 (Disable all protections)
    FLASH_ENABLE_ACCESS;
        MySPI_PutC(FLASH_EN_WR_STATUS);
    FLASH_DISABLE_ACCESS;
    FLASH_ENABLE_ACCESS;
        MySPI_PutC(FLASH_WRITE_STATUS);
        MySPI_PutC(0x00);
    FLASH_DISABLE_ACCESS;
/*
    // Read the Status Register
    FLASH_ENABLE_ACCESS;
        MySPI_PutC(FLASH_READ_STATUS);
        theStatus = MySPI_GetC();
    FLASH_DISABLE_ACCESS;

    sprintf(theStr, "Flash Status 0: 0x%x\n>", theStatus);
    MyConsole_SendMsg(theStr);
*/
}
示例#5
0
/**
 * Initialize the I2C
 */
void InitI2C()
{
    //I2C Pin Config
    mPORTBSetPinsDigitalOut(I2C_SCL_Pin | I2C_SDA_Pin);

    I2CEnable(I2C1, FALSE);

    //Soft reset I2C Bus by pulsing the clock line 10 times
    mPORTBSetBits(I2C_SCL_Pin | I2C_SDA_Pin);
    unsigned int i;
    unsigned int wait;
    for (i = 0; i < 20; i++) {
        for (wait = 0; wait < 20; wait++);
        mPORTBToggleBits(I2C_SCL_Pin);
    }
    mPORTBSetBits(I2C_SCL_Pin | I2C_SDA_Pin);

    // Configure Various I2C Options
    //!!!!! - Slew rate control off(High speed mode enabled), If enabled, RA0 and RA1 fail to work, see silicon errata (Microchip Hardware Bugs)
    I2CConfigure(I2C1, I2C_ENABLE_SLAVE_CLOCK_STRETCHING | I2C_ENABLE_HIGH_SPEED);
    // Set the I2C baud rate
    int I2C_actualClock = I2CSetFrequency(I2C1, SYS_FREQ, I2C_Clock);
    UART_SendString("I2C Clock: ");
    UART_SendInt(I2C_actualClock);
    UART_SendString(" Hz\n\r");
    // Enable the I2C bus
    I2CEnable(I2C1, TRUE);

    while (!I2CTransmitterIsReady(I2C1));

    // configure the interrupt priority for the I2C peripheral
    //INTSetVectorPriority(INT_I2C_1_VECTOR,INT_PRIORITY_LEVEL_3);
    //INTClearFlag(INT_I2C1);
    //INTEnable(INT_I2C1,INT_ENABLED);
}
示例#6
0
void InitBluetooth(void)
{

    #if DESIRED_BAUDRATE == 9600
        mPORTBSetPinsDigitalOut(BIT_9);
        mPORTBSetBits(BIT_9);// BT high level, the reset polarity is active low

        mPORTASetPinsDigitalOut(BIT_3);
        mPORTASetBits(BIT_3);// Set Baud rate (high = force 9,600, low = 115 K or firmware setting)

        mPORTASetPinsDigitalOut(BIT_2);
        mPORTASetBits(BIT_2);// Set BT master (high = auto-master mode)

    #elif DESIRED_BAUDRATE == 115200
        mPORTBSetPinsDigitalOut(BIT_9);
        mPORTBSetBits(BIT_9);// BT high level, the reset polarity is active low

        mPORTASetPinsDigitalOut(BIT_3);
        mPORTAClearBits(BIT_3);// Set Baud rate (high = force 9,600, low = 115 K or firmware setting)

        mPORTASetPinsDigitalOut(BIT_2);
        mPORTASetBits(BIT_2);// Set BT master (high = auto-master mode)
    
    #elif DESIRED_BAUDRATE ==921600
        //nothing

    #endif

    UARTConfigure(UART_MODULE_ID2, UART_ENABLE_PINS_TX_RX_ONLY|UART_ENABLE_PINS_CTS_RTS);
    UARTConfigure(UART_MODULE_ID2, UART_ENABLE_HIGH_SPEED);
    UARTSetFifoMode(UART_MODULE_ID2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART_MODULE_ID2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART_MODULE_ID2, GetPeripheralClock(), DESIRED_BAUDRATE);
    UARTEnable(UART_MODULE_ID2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));

    // Configure UART RX Interrupt
    INTEnable(INT_SOURCE_UART_RX(UART_MODULE_ID2), INT_ENABLED);
    INTSetVectorPriority(INT_VECTOR_UART(UART_MODULE_ID2), INT_PRIORITY_LEVEL_2);
    INTSetVectorSubPriority(INT_VECTOR_UART(UART_MODULE_ID2), INT_SUB_PRIORITY_LEVEL_1);

    // Enable multi-vector interrupts
    

    //WriteStringXbee("*** UART Bluetooth demarre ***\r\n");
    
   
}
示例#7
0
// initialize hardware
void Initialize()
{
    // All of these items will affect the performance of your code and cause it to run significantly slower than you would expect.
    SYSTEMConfigPerformance(SYS_CLOCK);

    WriteCoreTimer(0); // Core timer ticks once every two clocks (verified)

    // set default digital port A for IO
    DDPCONbits.JTAGEN = 0; // turn off JTAG
    DDPCONbits.TROEN = 0; // ensure no tracing on
    //mPORTASetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7);

    // todo - set this based on width of image. make rest inputs?
    mPORTBSetPinsDigitalOut(BIT_0|BIT_1|BIT_2|BIT_3|BIT_4|BIT_5|BIT_6|BIT_7|BIT_8|BIT_9|BIT_10|BIT_11|BIT_12|BIT_13|BIT_14|BIT_15);

    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    int pbClk = SYSTEMConfig( SYS_CLOCK, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    InitializeUART(pbClk);

    mPORTASetPinsDigitalOut(BIT_1);


    // set internals
    // SetUARTClockDivider(flashOptions.baudDivisor);

    // prepare 32 bit timer 45 to trigger interrupts
    //OpenTimer45(T45_ON | T45_SOURCE_INT | T45_PS_1_1, interruptTime);

    // set up the timer interrupt and priority
    //ConfigIntTimer45(T4_INT_ON | T4_INT_PRIOR_7);

    // enable multivectored interrupts
    //INTEnableSystemMultiVectoredInt();

    // start watchdog timer
    //tickle in interrupt, turn off during reset of device, causes a reset
    //The next statement enables the Watchdog Timer:
    // WDTCONbits.ON = 1;

    //sprintf(text,"Wait states %d\r\n.",BMXCONbits.BMXWSDRM);
    //PrintSerial(text);
    //BMXCONbits.BMXWSDRM = 0; // set RAM access to zero wait states

    //sprintf(text,"TODO _ REMOVE:override %d\r\n",pinOverride);
    //PrintSerial(text);
    //sprintf(text,"TODO _ REMOVE:actual %d\r\n",PORTAbits.RA1);
    //PrintSerial(text);
}
示例#8
0
int main(void)
{

  // === config the uart, DMA, SPI ===========
  PT_setup();

  // == SPI ==
  //enable SPI at 10 MHz clock to meet digital potentiometer specifications
  SpiChnOpen(spiChn, SPI_OPEN_ON | SPI_OPEN_MODE16 | SPI_OPEN_MSTEN | SPI_OPEN_CKE_REV , spiClkDiv);
  
  // === setup system wide interrupts  ====================
  INTEnableSystemMultiVectoredInt();
    
  // === set up i/o port pin ===============================
  //Port B bits, 3,7,8, and 9 are used to select digital output
  //Port B bit 4 is used as chip select for treble digital potentiometer
  //Port B bit 13 is used as a select signal for output effect selection multiplexer
  //Additional functionality would use the TFT to display which output was being
  //selected
  mPORTBSetPinsDigitalOut(BIT_4 | BIT_3|BIT_7 | BIT_8 | BIT_9 |BIT_13);    //Set port as output
 
  //Port A Bits 0,2,and 3 are used to configure digital potentiometers (chip selects). Port A bit 4 is used
  //for multiplexing whether to have input from Digital effector chip, distortion,
  //or pure tonestack sound
  mPORTASetPinsDigitalOut(BIT_0 | BIT_2 | BIT_3 | BIT_4);
  // === now the threads ===================================
  
  // init the threads
  PT_INIT(&pt_cmd);
  PT_INIT(&pt_time);
  
  //==Digipot spi stuff
   // SCK2 is pin 26 
    // SDO1 (MOSI) is in PPS output group 1, could be connected to RB5 which is pin 14
    PPSOutput(2, RPB5, SDO1);
    // control CS for DAC
    //mPORTBSetPinsDigitalOut(BIT_4); //CS
    mPORTBSetBits(BIT_4 | BIT_6);
    //===
    
    mPORTASetBits(BIT_0 | BIT_2 | BIT_3 | BIT_4); //CS pins active high
    mPORTAClearBits(BIT_4);
    mPORTBClearBits(BIT_13);
    mPORTBSetBits(BIT_13);
    
    
  // schedule the threads
  while(1) {
      //cmd used as command center for all effects
    PT_SCHEDULE(protothread_cmd(&pt_cmd));
  }
} // main
int main(void)
{
  // === config the uart, DMA, vref, timer5 ISR =============
  PT_setup();

   // === setup system wide interrupts  ====================
  INTEnableSystemMultiVectoredInt();
    
  // === set up i/o port pin ===============
  mPORTASetBits(BIT_0 | BIT_1 );	//Clear bits to ensure light is off.
  mPORTASetPinsDigitalOut(BIT_0 | BIT_1 );    //Set port as output
  mPORTBSetBits(BIT_0 );	//Clear bits to ensure light is off.
  mPORTBSetPinsDigitalOut(BIT_0 );    //Set port as output

  // === now the threads ====================
  // init  the thread control semaphores
  PT_SEM_INIT(&control_t1, 0); // start blocked
  PT_SEM_INIT(&control_t2, 1); // start unblocked
  PT_SEM_INIT(&send_sem, 1); // start with ready to send

  // init the threads
  PT_INIT(&pt1);
  PT_INIT(&pt2);
  PT_INIT(&pt3);
  PT_INIT(&pt4);
  PT_INIT(&pt5);

  // init the optional rate scheduler
  PT_RATE_INIT();

  // schedule the threads
  while(1) {
    PT_RATE_LOOP(); // not necessary if you use PT_SCHEDULE
    PT_RATE_SCHEDULE(protothread1(&pt1), t1_rate);
    if (run_t4) PT_RATE_SCHEDULE(protothread4(&pt4), t4_rate); //run always
    PT_RATE_SCHEDULE(protothread2(&pt2), t1_rate);
    if (cmd[0] != 'k') PT_RATE_SCHEDULE(protothread3(&pt3),t3_rate);
    PT_SCHEDULE(protothread5(&pt5));

     /*
    // alternate scheme
    PT_SCHEDULE(protothread1(&pt1));
    if (run_t4) PT_SCHEDULE(protothread4(&pt4));
   PT_SCHEDULE(protothread2(&pt2));
    if (run_t4) PT_SCHEDULE(protothread4(&pt4));
    if (cmd[0] != 'k') PT_SCHEDULE(protothread3(&pt3));
     */
  }
} // main
示例#10
0
/**
 * @brief: Initialisation SPI 
 * @param: 	void
 * @return: void
*/
void SPI_Init(void)
{
    // Turn off leds before configuring the IO pin as output
   	SET_CSB;            // same as LATDCLR = 0x0007
	mPORTBSetPinsDigitalOut(CSB_BIT);    // same as TRISDCLR = 0x0007


	unsigned int config1 = FRAME_ENABLE_OFF|ENABLE_SDO_PIN|SPI_MODE8_ON|SPI_SMP_OFF|SPI_CKE_OFF|SLAVE_ENABLE_OFF|CLK_POL_ACTIVE_LOW|MASTER_ENABLE_ON|SEC_PRESCAL_4_1|PRI_PRESCAL_16_1;
	unsigned int config2 = SPI_ENABLE|SPI_IDLE_CON;
	
	
	OpenSPI1(config1, config2);
//	DBPRINTF("\r\nSPI INIT FINISHED\n");

}
示例#11
0
void InitializeSystem()
{
	SYSTEMConfigWaitStatesAndPB(CLOCK_FREQ);
	mOSCSetPBDIV(OSC_PB_DIV_4);  // Set to get 20MHz PB clock
  //mOSCSetPBDIV(OSC_PB_DIV_2);
	CheKseg0CacheOn();
	mJTAGPortEnable(0);

	// Initialize the pins to all digital output and driven to ground.
	// Exception is RE7 and RE6 which are switch inputs
	PORTSetPinsDigitalIn(IOPORT_E, BIT_6);
	PORTSetPinsDigitalIn(IOPORT_E, BIT_7);

	mPORTASetPinsDigitalOut(0xFFFF);
	mPORTBSetPinsDigitalOut(0xFFFF);
	mPORTCSetPinsDigitalOut(0xFFFF);
	mPORTDSetPinsDigitalOut(0xFFFF);
	mPORTESetPinsDigitalOut(0xFF3F);
	mPORTFSetPinsDigitalOut(0xFFFF);
	mPORTGSetPinsDigitalOut(0xFFFF);

	mPORTAClearBits(0xFFFF);
	mPORTBClearBits(0xFFFF);
	mPORTCClearBits(0xFFFF);
	mPORTDClearBits(0xFFFF);
	mPORTEClearBits(0xFF3F);
	mPORTESetBits(0x000F);		// LED latches need to be set high for off
	mPORTFClearBits(0xFFFF);
	mPORTGClearBits(0xFFFF);

	INTEnableSystemMultiVectoredInt();

  #ifdef SANITY_CHECK
  mLED_Green_On();
  #endif
	
	//LCD_Initialize();
	//WIFI_Initialize();
	//SPRINKLER_Initialize();
	//RTCC_Initialize(); 
  //SERIALUSB_Initialize();
	SDCARD_Initialize();

  TCPIP_Initialize();
}
示例#12
0
//===================== Main ======================= //
void main(void) {
    SYSTEMConfig( SYS_FREQ,  SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    ANSELA = 0; ANSELB = 0; CM1CON = 0; CM2CON = 0;

    PT_setup();
    INTEnableSystemMultiVectoredInt();

    
    // initialize the threads
    PT_INIT(&pt_blink);
    PT_INIT(&pt_capture);
    
    // initialize the display
    tft_init_hw();
    tft_begin();
    tft_fillScreen(ILI9340_BLACK);

    tft_setRotation(0); //240x320 vertical display

    // initialize the comparator
    CMP1Open(CMP_ENABLE | CMP_OUTPUT_ENABLE | CMP1_NEG_INPUT_IVREF);
    
    // initialize the timer2
    OpenTimer2(T2_ON | T2_SOURCE_INT | T2_PS_1_64, 0xffffffff);

    // initialize the input capture, uses timer2
    OpenCapture1( IC_EVERY_RISE_EDGE | IC_FEDGE_RISE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON);
    ConfigIntCapture1(IC_INT_ON | IC_INT_PRIOR_3 | IC_INT_SUB_PRIOR_3 );
    INTClearFlag(INT_IC1);

    // initialize the input/output I/O
    mPORTBSetPinsDigitalOut(BIT_3);
    mPORTBClearBits(BIT_3);
    PPSOutput(4, RPB9, C1OUT);		//set up output of comparator for debugging
    PPSInput(3, IC1, RPB13);		//Either Pin 6 or Pin 24 idk
   
    //round-robin scheduler for threads
    while(1) {
	PT_SCHEDULE(protothread_blink(&pt_blink));
	PT_SCHEDULE(protothread_capture(&pt_capture));
    }
    
} //main
void setupHardware()
{
    SYSTEMConfig(SYS_CLOCK, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    mPORTDSetPinsDigitalOut(BIT_1); //yellow LED
    mPORTGSetPinsDigitalOut(BIT_6); //green LED

    //A1 PIR Input (CN4 module, RB2)
    //A2 STB current consumption (AN3)
    //D0 IR Output
    mPORTDSetPinsDigitalOut(BIT_3); //D1 STB IRF control
    mPORTDSetPinsDigitalIn(BIT_4); //D2 BUT OTG
    mPORTDSetPinsDigitalOut(BIT_5); //D3 SHD RED LED Command OFF acqusition notificaiton
    mPORTDSetPinsDigitalOut(BIT_6); //D4 SHD GREEN LED Command ON acqusition notificaiton
    //D5 IR input (RD7)
    //D6 SHD BUT1
    //D7 SHD BUT2
    mPORTBSetPinsDigitalOut(BIT_14); //D9 monitor relay control

    DDPCONbits.JTAGEN = 0;

    initLEDs();
    initUART();

    initADC();
    setupCNModuleAnd_IR_PIR_Input();
    //setupCNModuleAndPIRInput();
    configureRTC();
    setupIRTransmit();

    switchMonitorOff();
    switchSTBOff();

    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();

    T2CONbits.ON = 1;
}
示例#14
0
文件: fakemain.c 项目: fkummer/4760
// This thread is responsible for all the code not involving the TFT Display, it handled discharging and charging the capacitor and calculating the 
// capacitance of the capacitor.
static PT_THREAD(protothread_cap(struct pt *pt)){
    PT_BEGIN(pt);
        
    while(1){
        // Discharge Capacitor
        // Set pin as output
        mPORTBSetPinsDigitalOut(BIT_3);    
        // Drive RB3 low so capacitor can discharge into the pin
        mPORTBClearBits(BIT_3);

        // Yield until discharge is complete 
        PT_YIELD_TIME_msec(2); // 2ms is given for the capacitor to discharge and for the display to update if needed
        Comp1Setup();
		
		// Charge Capacitor
		// Set RB3 as an input to detect capacitor's current charge
        mPORTBSetPinsDigitalIn(BIT_3); 
		// Set up the timer for charging the capcitor
        capTimerSetup();
		// Set up the input capture to capture when the capacitor voltage reaches the reference voltage
        IC1setup();
		
        // Yield while waiting for event from comparator
        PT_YIELD_UNTIL(pt, charged);
        CloseTimer2();
        
		// Reset thread wait variable
        charged = 0;

        // Calculate capacitance in nF
        capacitance =  (((charge_time*-1)/1000000)/(log(1-(VREF / VDD)) * RESISTOR))*1000000000;

        CMP1Close();
        PT_YIELD_TIME_msec(20);
    }
    PT_END(pt);
}
示例#15
0
//===================== Capture ==================== //
// Discharges capacitor, displays  and begins measurement of C1INA
static PT_THREAD (protothread_capture(struct pt *pt))
{
    PT_BEGIN(pt);
    while(1) {
    // sets pin 7 to an output
    mPORTBSetPinsDigitalOut(BIT_3);
    mPORTBClearBits(BIT_3);
    tft_setCursor(10, 50);
    tft_setTextColor(ILI9340_YELLOW);  tft_setTextSize(3);
    tft_writeString("Capacitance: ");
    
    //sets up for the capacitor reading
    char buffer[20];
    tft_setCursor(10, 90);
    tft_fillRect(10,90, 300, 100, ILI9340_BLACK);
    sprintf(buffer,"%.1f nF",cap);
    tft_setTextColor(ILI9340_WHITE);
    
    //displays the capacitor value if it is above the threshold of 1 nF
    if(cap < 1.0*(1-ERROR))
        tft_writeString("No capacitor");
    else
        tft_writeString(buffer);
    

    cap = 0.0;
    PT_YIELD_TIME_msec(1);
    
    //Clear timer and sets pin 7 as input
    WriteTimer2(0);    
    mPORTBSetPinsDigitalIn(BIT_3);
    
    PT_YIELD_TIME_msec(100);
    }
    PT_END(pt);
} // capture
//********************************
//********************************
//********** INITIALISE **********
//********************************
//********************************
void initialise (void)
{
	BYTE data;
	
	//##### GENERAL NOTE ABOUT PIC32'S #####
	//Try and use the peripheral libraries instead of special function registers for everything (literally everything!) to avoid
	//bugs that can be caused by the pipeline and interrupts.
	

	//---------------------------------
	//----- CONFIGURE PERFORMANCE -----
	//---------------------------------
	
	//----- SETUP EVERYTHING FOR OPTIMUM PERFORMANCE -----
	SYSTEMConfigPerformance(80000000ul);		//Note this sets peripheral bus to '1' max speed (regardless of configuration bit setting)
												//Use PBCLK divider of 1:1 to calculate UART baud, timer tick etc


	//----- SET PERIPHERAL BUS DIVISOR -----
	//To minimize dynamic power the PB divisor should be chosen to run the peripherals at the lowest frequency that provides acceptable system performance
	mOSCSetPBDIV(OSC_PB_DIV_2);			//OSC_PB_DIV_1, OSC_PB_DIV_2, OSC_PB_DIV_4, OSC_PB_DIV_8, 

	//----- SETUP INTERRUPTS -----
	INTEnableSystemMultiVectoredInt();

	//-------------------------
	//----- SETUP IO PINS -----
	//-------------------------
	//(Device will powerup with all IO pins as inputs)

	//----- TURN OFF THE JTAG PORT -----
	//(JTAG is on by default)
	//mJTAGPortEnable(0);		//Must be on for Microchip Multimedia Development board

	#define	PORTA_IO	0xc2ff				//Setup the IO pin type (0 = output, 1 = input)
	mPORTAWrite(0xc033);					//Set initial ouput pin states
	mPORTASetPinsDigitalIn(PORTA_IO);		//(Sets high bits as input)
	mPORTASetPinsDigitalOut(~PORTA_IO);		//(Sets high bits as output)
	
	#define	PORTB_IO	0xfbff				//Setup the IO pin type (0 = output, 1 = input)
	mPORTBWrite(0x6d13);					//Set initial ouput pin states
	mPORTBSetPinsDigitalIn(PORTB_IO);		//(Sets high bits as input)
	mPORTBSetPinsDigitalOut(~PORTB_IO);		//(Sets high bits as output)

	mPORTBSetPinsDigitalIn(BIT_0 | BIT_1 | BIT_3 | BIT_4 | BIT_15);			//Joystick inputs

	#define	PORTC_IO	0xf01e				//Setup the IO pin type (0 = output, 1 = input)
	mPORTCWrite(0x3018);					//Set initial ouput pin states
	mPORTCSetPinsDigitalIn(PORTC_IO);		//(Sets high bits as input)
	mPORTCSetPinsDigitalOut(~PORTC_IO);		//(Sets high bits as output)

	#define	PORTD_IO	0x7bfe				//Setup the IO pin type (0 = output, 1 = input)
	mPORTDWrite(0xbdaf);					//Set initial ouput pin states
	mPORTDSetPinsDigitalIn(PORTD_IO);		//(Sets high bits as input)
	mPORTDSetPinsDigitalOut(~PORTD_IO);		//(Sets high bits as output)

	mPORTDSetPinsDigitalOut(BIT_2 | BIT_1);		//LED's 2 and 3
	mPORTDSetPinsDigitalIn(BIT_9);

	#define	PORTE_IO	0x03ff				//Setup the IO pin type (0 = output, 1 = input)
	mPORTEWrite(0x02a2);					//Set initial ouput pin states
	mPORTESetPinsDigitalIn(PORTE_IO);		//(Sets high bits as input)
	mPORTESetPinsDigitalOut(~PORTE_IO);		//(Sets high bits as output)

	#define	PORTF_IO	0x111f				//Setup the IO pin type (0 = output, 1 = input)
	mPORTFWrite(0x0039);					//Set initial ouput pin states
	mPORTFSetPinsDigitalIn(PORTF_IO);		//(Sets high bits as input)
	mPORTFSetPinsDigitalOut(~PORTF_IO);		//(Sets high bits as output)

	#define	PORTG_IO	0xd3cf				//Setup the IO pin type (0 = output, 1 = input)
	mPORTGWrite(0xf203);					//Set initial ouput pin states
	mPORTGSetPinsDigitalIn(PORTG_IO);		//(Sets high bits as input)
	mPORTGSetPinsDigitalOut(~PORTG_IO);		//(Sets high bits as output)



	//Read pins using:
	// mPORTAReadBits(BIT_0);
	//Write pins using:
	// mPORTAClearBits(BIT_0);
	// mPORTASetBits(BIT_0);
	// mPORTAToggleBits(BIT_0);



	//----- INPUT CHANGE NOTIFICATION CONFIGURATION -----
	//EnableCN0();
	ConfigCNPullups(CN2_PULLUP_ENABLE | CN3_PULLUP_ENABLE | CN5_PULLUP_ENABLE | CN6_PULLUP_ENABLE | CN12_PULLUP_ENABLE);		//Joystick pins



	//----- SETUP THE A TO D PINS -----
	ENABLE_ALL_DIG;


	//---------------------
	//----- SETUP USB -----
	//---------------------
	//The USB specifications require that USB peripheral devices must never source current onto the Vbus pin.  Additionally, USB peripherals should not source
	//current on D+ or D- when the host/hub is not actively powering the Vbus line.  When designing a self powered (as opposed to bus powered) USB peripheral
	//device, the firmware should make sure not to turn on the USB module and D+ or D- pull up resistor unless Vbus is actively powered.  Therefore, the
	//firmware needs some means to detect when Vbus is being powered by the host. A 5V tolerant I/O pin can be connected to Vbus (through a resistor), and
	//can be used to detect when Vbus is high (host actively powering), or low (host is shut down or otherwise not supplying power).  The USB firmware
	//can then periodically poll this I/O pin to know when it is okay to turn on the USB module/D+/D- pull up resistor.  When designing a purely bus powered
	//peripheral device, it is not possible to source current on D+ or D- when the host is not actively providing power on Vbus. Therefore, implementing this
	//bus sense feature is optional.  This firmware can be made to use this bus sense feature by making sure "USE_USB_BUS_SENSE_IO" has been defined in the
	//HardwareProfile.h file.    
    //	#if defined(USE_USB_BUS_SENSE_IO)
    //	tris_usb_bus_sense = INPUT_PIN; // See HardwareProfile.h
    //	#endif
    
	//If the host PC sends a GetStatus (device) request, the firmware must respond	and let the host know if the USB peripheral device is currently bus powered
	//or self powered.  See chapter 9 in the official USB specifications for details regarding this request.  If the peripheral device is capable of being both
	//self and bus powered, it should not return a hard coded value for this request.  Instead, firmware should check if it is currently self or bus powered, and
	//respond accordingly.  If the hardware has been configured like demonstrated on the PICDEM FS USB Demo Board, an I/O pin can be polled to determine the
	//currently selected power source.  On the PICDEM FS USB Demo Board, "RA2" is used for	this purpose.  If using this feature, make sure "USE_SELF_POWER_SENSE_IO"
	//has been defined in HardwareProfile.h, and that an appropriate I/O pin has been mapped to it in HardwareProfile.h.
    //	#if defined(USE_SELF_POWER_SENSE_IO)
    //	tris_self_power = INPUT_PIN;	// See HardwareProfile.h
    //	#endif
    
    
    //Enable the USB port now - we will check to see if Vbus is  powered at the end of init and disable it if not.
    //USBDeviceInit();	//usb_device.c.  Initializes USB module SFRs and firmware variables to known states.

	

	//------------------------
	//----- SETUP TIMERS -----
	//------------------------
	//(INCLUDE THE USAGE OF ALL TIMERS HERE EVEN IF NOT SETUP HERE SO THIS IS THE ONE POINT OF
	//REFERENCE TO KNOW WHICH TIMERS ARE IN USE AND FOR WHAT).

	//----- SETUP TIMER 1 -----
	//Used for: Available
	//OpenTimer1((T1_ON | T1_IDLE_CON | T1_GATE_OFF | T1_PS_1_4 | T1_SOURCE_INT), 20000);

	//----- SETUP TIMER 2 -----
	//Used for: 
	//OpenTimer2((T2_ON | T2_IDLE_CON | T2_GATE_OFF | T2_PS_1_1 | T2_SOURCE_INT), 0xffff);		//0xffff = 305Hz

	//----- SETUP TIMER 3 -----
	//Used for: 
	//OpenTimer3((T3_ON | T3_IDLE_CON | T3_GATE_OFF | T3_PS_1_1 | T3_SOURCE_INT), PIEZO_TIMER_PERIOD);

	//----- SETUP TIMER 4 -----
	//Used for: 
	//OpenTimer4((T4_ON | T4_IDLE_CON | T4_GATE_OFF | T4_PS_1_1 | T4_SOURCE_INT), 20000);

	//----- SETUP TIMER 5 -----
	//Used for: Heartbeat
	OpenTimer5((T5_ON | T5_IDLE_CON | T5_GATE_OFF | T5_PS_1_1 | T5_SOURCE_INT), 40000);		//1mS with 80MHz osc and PB_DIV_2
	ConfigIntTimer5(T5_INT_ON | T5_INT_PRIOR_7);											//1=lowest priority to 7=highest priority.  ISR function must specify same value



	//---------------------------------
	//----- SETUP EVAL BOARD CPLD -----
	//---------------------------------
	//Graphics bus width = 16
	mPORTGSetPinsDigitalOut(BIT_14);
	mPORTGSetBits(BIT_14);

	//SPI source select = SPI3 (not used)
	mPORTGSetPinsDigitalOut(BIT_12);
	mPORTGClearBits(BIT_12);
	
	//SPI peripheral destination select = Expansion Slot (not used)
	mPORTASetPinsDigitalOut(BIT_7 | BIT_6);
	mPORTASetBits(BIT_7);
	mPORTAClearBits(BIT_6);


	//--------------------------------------
    //----- PARALLEL MASTER PORT SETUP -----
	//--------------------------------------
    PMMODE = 0;
    PMAEN = 0;
    PMCON = 0;
    PMMODE = 0x0610;
    PMCONbits.PTRDEN = 1;                   //Enable RD line
    PMCONbits.PTWREN = 1;                   //Enable WR line
    PMCONbits.PMPEN = 1;                    //Enable PMP


	//------------------------------
	//----- INITIALISE DISPLAY -----
	//------------------------------
	display_initialise();


	display_test();

	//LOAD OUR GLOBAL HTML STYLES FILE READY FOR DISPLAY HTML PAGES
	BYTE dummy_styles_count;
	DWORD file_size;
	if (display_html_setup_read_file(global_css, 0, &file_size))
	{
		dummy_styles_count = 0;
		display_html_read_styles(&file_size, &dummy_styles_count, 1);			//1 = this is global styles file
	}

}
示例#17
0
/*******************************************************************************
 * Function:    BoardInit(void)
 * PreCondition:None
 * Input:       None
 * Output:      None
 * Overview:    SPI pins and SFR, Maintenance Tasks Timer, External Interrupts,
 *              and other board issues initialization.
 * Note:        This routine needs to be called before initialising MiWi stack
 *              or invoking other function that operates on MiWi stack.
 ******************************************************************************/
void BoardInit(void){
    #if defined(__PIC32MX__)

    // RADIO INTERFACES & SPI INIT -------------------------------------------//
        #if defined HARDWARE_SPI
            /* Peripheral Bus Frequency = System Clock / PB Divider */
            unsigned int pbFreq;
            pbFreq = (DWORD) CLOCK_FREQ/(1 << mOSCGetPBDIV());

            unsigned int SPI_Clk_Freq;
            unsigned char SPI_Brg;
        #endif

        #if defined MRF24J40
            PHY_CS_TRIS = 0;
            PHY_CS = 1;
            PHY_RESETn_TRIS = 0;
            PHY_RESETn = 1;

            MRF24J40_INT_TRIS = 1;

            SDI_TRIS = 1;
            SDO_TRIS = 0;
            SCK_TRIS = 0;
            SPI_SDO = 0;
            SPI_SCK = 0;

            PHY_WAKE_TRIS = 0;
            PHY_WAKE = 1;

            SPICONCLR = 0xFFFFFFFF;             // Clear SPIxCON register

            #ifdef HARDWARE_SPI
                /* Enable SPI, Set to Master Mode & Set CKE bit : Serial output
                 * data changes on transition from active clock state to Idle
                 * clock state */
                SPICON = 0x00008120;

                /* PB Frequency can be maximum 40 MHz */
                if(pbFreq > (2 * MAX_SPI_CLK_FREQ_FOR_P2P)){
                    SPI_Brg = 1;
                    /* Continue the loop till you find SPI Baud Rate Reg Value */
                    while(1){
                        /* SPI Clock Calculation as per PIC32 Manual */
                        SPI_Clk_Freq = pbFreq / (2 * (SPI_Brg + 1));

                        if(SPI_Clk_Freq <= MAX_SPI_CLK_FREQ_FOR_P2P){
                            break;
                        }
                        SPI_Brg++;
                    }
                    #if defined MRF24J40_IN_SPI1
                    mSpiChnSetBrg (1, SPI_Brg);
                    #elif defined MRF24J40_IN_SPI2
                    mSpiChnSetBrg (2, SPI_Brg);
                    #elif defined MRF24J40_IN_SPI3
                        mSpiChnSetBrg (1A, SPI_Brg);
                    #elif defined MRF24J40_IN_SPI4
                        mSpiChnSetBrg (3A, SPI_Brg);
                    #endif
               }
               else{
                    #if defined MRF24J40_IN_SPI1
                    mSpiChnSetBrg (1, 0);
                    #elif defined MRF24J40_IN_SPI2
                    mSpiChnSetBrg (2, 0);
                    #elif defined MRF24J40_IN_SPI3
                        mSpiChnSetBrg (1A, 0);
                    #elif defined MRF24J40_IN_SPI4
                        mSpiChnSetBrg (3A, SPI_Brg);
                    #endif
               }
            #endif
        #endif
        #if defined(MRF49XA_1)
            //Configuration for Guilja's Expansion Board, Connection SLot 1 --//
            mPORTESetPinsDigitalOut(BIT_1); //nCS
            mPORTBSetPinsDigitalIn(BIT_2);  //FINT      //Juan: Added.
            //----------------------------------------------------------------//

            MRF49XA_1_PHY_CS_TRIS = 0;
            MRF49XA_1_PHY_CS = 1;
            MRF49XA_1_PHY_RESETn_TRIS = 0;
            MRF49XA_1_PHY_RESETn = 1;

            MRF49XA_1_INT_TRIS = 1;

            MRF49XA_1_SDI_TRIS = 1;
            MRF49XA_1_SDO_TRIS = 0;
            MRF49XA_1_SCK_TRIS = 0;
            MRF49XA_1_SPI_SDO = 0;
            MRF49XA_1_SPI_SCK = 0;

            MRF49XA_1_nFSEL_TRIS = 0;
            MRF49XA_1_FINT_TRIS = 1;
            MRF49XA_1_nFSEL = 1;          // nFSEL inactive

            MRF49XA_1_SPICONCLR = 0xFFFFFFFF;       //Clear SPIxCON register

            #ifdef HARDWARE_SPI
                /* Enable SPI1, Set to Master Mode & Set CKE bit : Serial output
                * data changes on transition from active clock state to Idle
                * clock state */
                MRF49XA_1_SPICON = 0x00008120;

                /* PB Frequency can be maximum 40 MHz */
                if(pbFreq > (2 * MAX_SPI_CLK_FREQ_FOR_P2P)){
                    SPI_Brg = 1;
                    /* Continue the loop till you find SPI Baud Rate Reg Value */
                    while(1){
                        /* SPI Clock Calculation as per PIC32 Manual */
                        SPI_Clk_Freq = pbFreq / (2 * (SPI_Brg + 1));
                        if(SPI_Clk_Freq <= MAX_SPI_CLK_FREQ_FOR_P2P){
                            break;
                        }
                        SPI_Brg++;
                    }
                    #if defined MRF49XA_1_IN_SPI1
                    mSpiChnSetBrg (1, SPI_Brg);
                    #elif defined MRF49XA_1_IN_SPI2
                    mSpiChnSetBrg (2, SPI_Brg);
                    #elif defined MRF49XA_1_IN_SPI3
                        mSpiChnSetBrg (1A, SPI_Brg);
                    #endif
               }
               else{
                    #if defined MRF49XA_1_IN_SPI1
                    mSpiChnSetBrg (1, 0);
                    #elif defined MRF49XA_1_IN_SPI2
                    mSpiChnSetBrg (2, 0);
                    #elif defined MRF49XA_1_IN_SPI3
                        mSpiChnSetBrg (1A, 0);
                    #endif
               }
            #endif
        #endif
        #if defined(MRF49XA_2)
            MRF49XA_2_PHY_CS_TRIS = 0;
            MRF49XA_2_PHY_CS = 1;
            MRF49XA_2_PHY_RESETn_TRIS = 0;
            MRF49XA_2_PHY_RESETn = 1;

            MRF49XA_2_INT_TRIS = 1;

            MRF49XA_2_SDI_TRIS = 1;
            MRF49XA_2_SDO_TRIS = 0;
            MRF49XA_2_SCK_TRIS = 0;
            MRF49XA_2_SPI_SDO = 0;
            MRF49XA_2_SPI_SCK = 0;

            MRF49XA_2_nFSEL_TRIS = 0;
            MRF49XA_2_FINT_TRIS = 1;
            MRF49XA_2_nFSEL = 1;          // nFSEL inactive

            MRF49XA_2_SPICONCLR = 0xFFFFFFFF;       // Clear SPIxCON register

            #ifdef HARDWARE_SPI
                /* Enable SPI1, Set to Master Mode & Set CKE bit : Serial output
                * data changes on transition from active clock state to Idle
                * clock state */
                MRF49XA_2_SPICON = 0x00008120;

                /* PB Frequency can be maximum 40 MHz */
                if(pbFreq > (2 * MAX_SPI_CLK_FREQ_FOR_P2P)){
                    SPI_Brg = 1;
                    /* Continue the loop till you find SPI Baud Rate Reg Value */
                    while(1){
                        /* SPI Clock Calculation as per PIC32 Manual */
                        SPI_Clk_Freq = pbFreq / (2 * (SPI_Brg + 1));
                        if(SPI_Clk_Freq <= MAX_SPI_CLK_FREQ_FOR_P2P){
                            break;
                        }
                        SPI_Brg++;
                    }
                    #if defined MRF49XA_2_IN_SPI1
                    mSpiChnSetBrg (1, SPI_Brg);
                    #elif defined MRF49XA_2_IN_SPI2
                    mSpiChnSetBrg (2, SPI_Brg);
                    #elif defined MRF49XA_2_IN_SPI3
                        mSpiChnSetBrg (1A, SPI_Brg);
                    #endif
               }
               else{
                    #if defined MRF49XA_2_IN_SPI1
                    mSpiChnSetBrg (1, 0);
                    #elif defined MRF49XA_2_IN_SPI2
                    mSpiChnSetBrg (2, 0);
                    #elif defined MRF49XA_2_IN_SPI3
                        mSpiChnSetBrg (1A, 0);
                    #endif
               }
            #endif
        #endif
        #if defined MRF89XA
            Data_nCS_TRIS = 0;
            Config_nCS_TRIS = 0;
            Data_nCS = 1;
            Config_nCS = 1;
            PHY_IRQ1_TRIS = 1;

            //... REVIEW...
        #endif

    // SPI & EXTERNAL INTERRUPTS PINS AND CONFIGURATION ----------------------//
    #if defined (__32MX795F512L__) || defined __32MX675F256L__
        /* Set the SPI Port Directions (SDO, SDI, SCK) for every SPI module.*/
            #if defined MRF49XA_1_IN_SPI1 || defined MRF49XA_2_IN_SPI1 || \
                defined MRF89XA_IN_SPI1   || defined MRF24J40_IN_SPI1  || \
                defined MRF24WB0M_IN_SPI1
                mPORTDSetPinsDigitalOut(BIT_0);     //SDO1
                mPORTDSetPinsDigitalOut(BIT_10);    //SCK1
                mPORTCSetPinsDigitalIn(BIT_4);      //SDI1
            #endif
            #if defined MRF49XA_1_IN_SPI2 || defined MRF49XA_2_IN_SPI2 || \
                defined MRF89XA_IN_SPI2   || defined MRF24J40_IN_SPI2  || \
                defined MRF24WB0M_IN_SPI2
                mPORTGSetPinsDigitalOut(BIT_8);     //SDO2
                mPORTGSetPinsDigitalOut(BIT_6);     //SCK2
                mPORTGSetPinsDigitalIn(BIT_7);      //SDI2
            #endif
            #if defined MRF49XA_1_IN_SPI3 || defined MRF49XA_2_IN_SPI3 || \
                defined MRF89XA_IN_SPI3   || defined MRF24J40_IN_SPI3  || \
                defined MRF24WB0M_IN_SPI3
                mPORTFSetPinsDigitalOut(BIT_8);     //SDO3
                mPORTDSetPinsDigitalOut(BIT_15);    //SCK3
                mPORTFSetPinsDigitalIn(BIT_2);      //SDI3
            #endif
            #if defined MRF49XA_1_IN_SPI4 || defined MRF49XA_2_IN_SPI4 || \
                defined MRF89XA_IN_SPI4   || defined MRF24J40_IN_SPI4  || \
                defined MRF24WB0M_IN_SPI4
                mPORTFSetPinsDigitalOut(BIT_5);     //SDO4
                mPORTFSetPinsDigitalOut(BIT_13);    //SCK4
                mPORTFSetPinsDigitalIn(BIT_4);      //SDI4
            #endif
        #elif defined (__32MX795F512H__)
            #if defined MRF49XA_1_IN_SPI2 || defined MRF49XA_2_IN_SPI2 || \
                defined MRF89XA_IN_SPI2   || defined MRF24J40_IN_SPI2  || \
                defined MRF24WB0M_IN_SPI2
                mPORTGSetPinsDigitalOut(BIT_8);     //SDO2
                mPORTGSetPinsDigitalOut(BIT_6);     //SCK2
                mPORTGSetPinsDigitalIn(BIT_7);      //SDI2
            #endif
            #if defined MRF49XA_1_IN_SPI3 || defined MRF49XA_2_IN_SPI3 || \
                defined MRF89XA_IN_SPI3   || defined MRF24J40_IN_SPI3  || \
                defined MRF24WB0M_IN_SPI3
                mPORTDSetPinsDigitalOut(BIT_3);     //SDO3
                mPORTDSetPinsDigitalOut(BIT_1);     //SCK3
                mPORTDSetPinsDigitalIn(BIT_2);      //SDI3
            #endif
            #if defined MRF24J40_IN_SPI4 || defined MRF24WB0M_IN_SPI4
                mPORTFSetPinsDigitalOut(BIT_5);     //SDO4
                mPORTBSetPinsDigitalOut(BIT_14);    //SCK4
                mPORTFSetPinsDigitalIn(BIT_4);      //SDI4
            #endif
        #endif

        #if defined (__32MX795F512L__) || defined __32MX675F256L__
        /* Set the external interrups Pin Directions and Priority*/
            #if defined MRF49XA_1_USES_INT1 || defined MRF49XA_2_USES_INT1 || \
                defined MRF89XA_USES_INT1   || defined MRF24J40_USES_INT1  || \
                defined MRF24WB0M_USES_INT1
                mPORTESetPinsDigitalIn(BIT_8);
                mINT1SetIntPriority(4);
                mINT1SetIntSubPriority(2);
                mINT1SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT1 */
                mINT1IntEnable(1);
            #endif
            #if defined MRF49XA_1_USES_INT2 || defined MRF49XA_2_USES_INT2 || \
                defined MRF89XA_USES_INT2   || defined MRF24J40_USES_INT2  || \
                defined MRF24WB0M_USES_INT2
                mPORTESetPinsDigitalIn(BIT_9);
                mINT2SetIntPriority(4);
                mINT2SetIntSubPriority(2);
                mINT2SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT2 */
                mINT2IntEnable(1);
            #endif
            #if defined MRF49XA_1_USES_INT3 || defined MRF49XA_2_USES_INT3 || \
                defined MRF89XA_USES_INT3   || defined MRF24J40_USES_INT3  || \
                defined MRF24WB0M_USES_INT3
                mPORTASetPinsDigitalIn(BIT_14);
                mINT3SetIntPriority(4);
                mINT3SetIntSubPriority(2);
                mINT3SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT3 */
                mINT3IntEnable(1);
            #endif
            #if defined MRF49XA_1_USES_INT4 || defined MRF49XA_2_USES_INT4 || \
                defined MRF89XA_USES_INT4   || defined MRF24J40_USES_INT4  || \
                defined MRF24WB0M_USES_INT4
                mPORTASetPinsDigitalIn(BIT_15);
                mINT4SetIntPriority(4);
                mINT4SetIntSubPriority(2);
                mINT4SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT4 */
                mINT4IntEnable(1);
            #endif
        #elif defined (__32MX795F512H__)
            #if defined MRF49XA_1_USES_INT1 || defined MRF49XA_2_USES_INT1 || \
                defined MRF89XA_USES_INT1   || defined MRF24J40_USES_INT1  || \
                defined MRF24WB0M_USES_INT1
                mPORTDSetPinsDigitalIn(BIT_8);
                mINT1SetIntPriority(4);
                mINT1SetIntSubPriority(2);
                mINT1SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT1 */
                mINT1IntEnable(1);
            #endif
            #if defined MRF49XA_1_USES_INT2 || defined MRF49XA_2_USES_INT2 || \
                defined MRF89XA_USES_INT2   || defined MRF24J40_USES_INT2  || \
                defined MRF24WB0M_USES_INT2
                mPORTDSetPinsDigitalIn(BIT_9);  //Warning. Shared with SPI3 nSS3
                mINT2SetIntPriority(4);
                mINT2SetIntSubPriority(2);
                mINT2SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT2 */
                mINT2IntEnable(1);
            #endif
            #if defined MRF49XA_1_USES_INT3 || defined MRF49XA_2_USES_INT3 || \
                defined MRF89XA_USES_INT3   || defined MRF24J40_USES_INT3  || \
                defined MRF24WB0M_USES_INT3
                mPORTDSetPinsDigitalIn(BIT_10);
                mINT3SetIntPriority(4);
                mINT3SetIntSubPriority(2);
                mINT3SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT3 */
                mINT3IntEnable(1);
            #endif
            #if defined MRF49XA_1_USES_INT4 || defined MRF49XA_2_USES_INT4 || \
                defined MRF89XA_USES_INT4   || defined MRF24J40_USES_INT4  || \
                defined MRF24WB0M_USES_INT4
                mPORTDSetPinsDigitalIn(BIT_11);
                mINT4SetIntPriority(4);
                mINT4SetIntSubPriority(2);
                mINT4SetEdgeMode(0);                //0: Falling Edge.
                /* Enable INT4 */
                mINT4IntEnable(1);
            #endif
        #endif

    // TIMER 1 FOR TIME_SYNC -------------------------------------------------//
        #if defined(ENABLE_TIME_SYNC)   
        //TIMER 1 MAY BE USED FOR SLEEP MODE AND/OR FOR STACKS MAINTENANCE. IT
        //NEEDS ADAPTATION BEFORE ENABLING TIME_SYNC WITH TIMER 1 TOO!
            T1CON = 0;
            T1CON = 0x0012;
            T1CONSET = 0x8000;
            PR1 = 0xFFFF;
            IFS0bits.T1IF = 0;

            mT1IntEnable(1);
            mT1SetIntPriority(4);

            while(T1CONbits.TWIP);
            TMR1 = 0;
        #endif
    // TIMER 1 FOR NODE STACKS AUTO-MAINTENANCE ------------------------------//
        #if defined NODE_DOES_MAINTENANCE_TASKS
            T1CON = 0x0070;             //Disable timer, PBCLK source, PS=256
            TMR1  = 0x0000;             //Reset count
            PR1   = MAINTENANCE_PERIOD; //Set period.

            IPC1SET = 0x00000005;   //Set Priority level 1, Subpriority level 1
            IFS0CLR = 0x00000010;   //Clear T1IF
            IEC0SET = 0x00000010;   //Set T1IE
            //Timer will be triggered after initialization.
        #endif

    // IOPORT CN - For waking up the node manually. --------------------------//
        mPORTDSetPinsDigitalIn(BIT_5); // CN14
        CNCON = 0x8000;         //Module enabled.
        CNEN = 0x00004000;      //Enable CN14
        CNPUE = 0x00004000;     //Enable CN14 weak pull-up.
        //ReadBUTTONS();          //Clear PORT mismatch condition.
        IFS1CLR = 0x00000001;   //Clear the CN interrupt flag status bit
        IPC6SET = 0x00180000;   //Set CN priority 6, subpriority 0.
        //It will be enabled only during sleep mode time interval
    //------------------------------------------------------------------------//


        //JUAN: NVM NOT ADAPTED FOR LSI-CWSN MIWI STACK																									// Lo modifico en el wifi config
        #if defined(ENABLE_NVM)     
            //EE_nCS_TRIS = 0;
            //EE_nCS = 1;
        #endif

    // INTERRUPTION FLAGS AND EXT_INT PIN FINAL SETTINGS ---------------------//
        #if defined MRF49XA_1
            MRF49XA_1_IF = 0;
            if(MRF49XA_1_INT_PIN == 0){
                MRF49XA_1_IF = 1;
            }
        #endif
        #if defined MRF49XA_2
            MRF49XA_2_IF = 0;
            if(MRF49XA_2_INT_PIN == 0){
                MRF49XA_2_IF = 1;
            }
        #endif
        #if defined MRF89XA
            PHY_IRQ1 = 0;
        #endif
        #if defined MRF24J40
            MRF24J40_IF = 0;
            if(MRF24J40_INT_PIN == 0){
                MRF24J40_IF = 1;
            }
        #endif

    #else   //Not PIC32.
        #error "Unknown target board."
    #endif
}
示例#18
0
/****************************************************************************
  Function:
    static void InitializeBoard(void)

  Description:
    This routine initializes the hardware.  It is a generic initialization
    routine for many of the Microchip development boards, using definitions
    in HardwareProfile.h to determine specific initialization.

  Precondition:
    None

  Parameters:
    None - None

  Returns:
    None

  Remarks:
    None
 ***************************************************************************/
static void InitializeBoard(void) {
    // WiFi Module hardware Initialization handled by Library

    // Enable multi-vectored interrupts
    INTEnableSystemMultiVectoredInt();

    // Enable optimal performance
    SYSTEMConfigPerformance(GetSystemClock());
    mOSCSetPBDIV(OSC_PB_DIV_1); // Use 1:1 CPU Core:Peripheral clocks

    // Disable JTAG port so we get our I/O pins back, but first
    // wait 50ms so if you want to reprogram the part with
    // JTAG, you'll still have a tiny window before JTAG goes away.
    // The PIC32 Starter Kit debuggers use JTAG and therefore must not
    // disable JTAG.
    DelayMs(50);
    DDPCONbits.JTAGEN = 0;

    // LEDs
    LEDS_OFF();
    mPORTESetPinsDigitalOut(BIT_5 | BIT_6 | BIT_7);

    // Switches
    mPORTDSetPinsDigitalIn(BIT_4 | BIT_5 | BIT_6);
    ConfigCNPullups(CN13_PULLUP_ENABLE | CN14_PULLUP_ENABLE | CN15_PULLUP_ENABLE);

    // LCD
    mPORTESetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2 | BIT_3);
    //Configure LCD SPI pins
    mPORTFSetPinsDigitalOut(BIT_8);
    mPORTDSetPinsDigitalOut(BIT_15);

    //SPI Flash
    mPORTDSetPinsDigitalOut(BIT_14);


    //UART
    mPORTFSetPinsDigitalOut(BIT_5);
    mPORTFSetPinsDigitalIn(BIT_4);

    //MiWi
#if defined(MRF24J40) || defined(MRF49XA)
    PHY_CS = 1;
    mPORTDSetPinsDigitalOut(BIT_9);

    PHY_RESETn = 1;
    mPORTDSetPinsDigitalOut(BIT_11);
#endif

#if defined(MRF49XA)
    nFSEL_TRIS = 0;
    FINT_TRIS = 1;

    nFSEL = 1;
#elif defined(MRF24J40)
    PHY_WAKE = 1;
    mPORTBSetPinsDigitalOut(BIT_9);
#else
    Data_nCS_TRIS = 0;
    Config_nCS_TRIS = 0;
    Data_nCS = 1;
    Config_nCS = 1;
    IRQ1_INT_TRIS = 1;
    IRQ0_INT_TRIS = 1;

#endif

    /* Set the Port Directions of SDO, SDI, Clock & Slave Select Signal */
    /* Set SCK port pin to output */
    mPORTDSetPinsDigitalOut(BIT_10);
    /* Set SDO port pin to output */
    mPORTDSetPinsDigitalOut(BIT_0);
    /* Set SDI port pin to input */
    mPORTCSetPinsDigitalIn(BIT_4);
    /* Set INT1, INT2 port pins to input */
    mPORTESetPinsDigitalIn(BIT_8 | BIT_9);

    /* Clear SPI1CON register */
    SPI1CONCLR = 0xFFFFFFFF;

#ifdef HARDWARE_SPI
    unsigned int pbFreq;

    /* Enable SPI1, Set to Master Mode & Set CKE bit : Serial output data changes on transition
      from active clock state to Idle clock state */
    SPI1CON = 0x00008120;
    /* Peripheral Bus Frequency = System Clock / PB Divider */
    pbFreq = (DWORD) CLOCK_FREQ / (1 << mOSCGetPBDIV());

    /* PB Frequency can be maximum 40 MHz */
    if (pbFreq > (2 * MAX_SPI_CLK_FREQ_FOR_P2P)) {
        {
            unsigned int SPI_Clk_Freq;

            unsigned char SPI_Brg1 = 1;

            //For the SPI1
            /* Continue the loop till you find SPI Baud Rate Register Value */
            while (1) {
                /* SPI Clock Calculation as per PIC32 Manual */
                SPI_Clk_Freq = pbFreq / (2 * (SPI_Brg1 + 1));

                if (SPI_Clk_Freq <= MAX_SPI_CLK_FREQ_FOR_P2P) {
                    break;
                }

                SPI_Brg1++;
            }



            mSpiChnSetBrg(1, SPI_Brg1);

        }
    } else {
        /* Set SPI1 Baud Rate */
        mSpiChnSetBrg(1, 0);

    }

#endif

    /* Set the Interrupt Priority */
    mINT2SetIntPriority(4);

#if defined(MRF89XA)
    mINT1SetIntPriority(4);
#endif

    /* Set Interrupt Subpriority Bits for INT2 */
    mINT2SetIntSubPriority(2);

#if defined(MRF89XA)
    mINT2SetIntSubPriority(1);
#endif

    /* Set INT2 to falling edge */
    mINT2SetEdgeMode(0);

#if defined(MRF89XA)
    mINT1SetEdgeMode(1);
    mINT2SetEdgeMode(1);
#endif

    /* Enable INT2 */
    mINT2IntEnable(1);

#if defined(MRF89XA)
    mINT2IntEnable(1);
#endif

    /* Enable Multi Vectored Interrupts */
    //    INTEnableSystemMultiVectoredInt();

#if defined(MRF89XA)
    PHY_IRQ1 = 0;
    PHY_IRQ0 = 0;
    PHY_RESETn_TRIS = 1;
#else
    RFIF = 0;
    if (RF_INT_PIN == 0) {
        RFIF = 1;
    }
#endif

    // Initialize the EEPROM
    XEEInit();

    // UART Initialization
#if defined(STACK_USE_UART)
    UARTTX_TRIS = 0;
    UARTRX_TRIS = 1;
    UMODE = 0x8000; // Set UARTEN.  Note: this must be done before setting UTXEN
    USTA = 0x00001400; // RXEN set, TXEN set
#define CLOSEST_UBRG_VALUE ((GetPeripheralClock()+8ul*BAUD_RATE)/16/BAUD_RATE-1)
#define BAUD_ACTUAL (GetPeripheralClock()/16/(CLOSEST_UBRG_VALUE+1))

#define BAUD_ERROR ((BAUD_ACTUAL > BAUD_RATE) ? BAUD_ACTUAL-BAUD_RATE : BAUD_RATE-BAUD_ACTUAL)
#define BAUD_ERROR_PRECENT	((BAUD_ERROR*100+BAUD_RATE/2)/BAUD_RATE)
#if (BAUD_ERROR_PRECENT > 3)
#warning UART frequency error is worse than 3%
#elif (BAUD_ERROR_PRECENT > 2)
#warning UART frequency error is worse than 2%
#endif

    UBRG = CLOSEST_UBRG_VALUE;
#endif


}
示例#19
0
void Terminal(void)
{
    const char str1[] = {'k',0x00,'e',0x00,'y',0x00,'.',0x00,'b',0x00,'m',0x00,'p',0x00,'\0',0x00};
    const char str2[] = {'\\',0x00,'s',0x00,'y',0x00,'s',0x00,'\0',0x00};
    char KeyBuffer[31]={'Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M',',',' ',' ',' ','.'};
    char SpecialKeyBuffer[31]={'1','2','3','4','5','6','7','8','9','0','!','@','#','$','%','&','*','?','/','Z','"',' ','(',')','-','+',';',' ',' ',' ',':'};
     
    const unsigned short int LetterPosX[4]={93,62,32,1};
    const unsigned short int SpecialCharPosY[6]={1,284,1,39,245,284};
     
    const unsigned short int LetterPosY[31]={1,33,65,97,129,161,193,225,257,289,
                                             17,49,81,113,145,177,209,241,273,
                                                49,81,113,145,177,209,241,
                                                   81,113,145,177,209};
    _Bool NumSp=0,UppLow=0,ReadCmd=0,ErrorSyntax=0,HighApp=0,LowApp=0,SyntaxError=0,ExitApp=0,InitRfApp=0,SendApp=0,StatusRfApp=0,ReadApp=0,SetTime=0,SetDate=0;
    char c[2]={'A',0x00};
    char TextBuffer[10],i=0,b=0,Parametri=0,StringBuffer[50],Nchar=0,Param3[10],Param2[10],Param1[10],Param4[10],Param5[10];
    unsigned short int clu=0, dat=0,DelCount=0,a=0x0000;

    TRFData rfData;

    char  Minuti[3]={0x30,0x30,0x00};///minuti
    char  Ore[3]={0x30,0x31,0x00};///Ore

    
    SSD1289_writeResgiter( 0x0049, 0x000A );///fine della finestra a 10 px
    LCD_CLS(AZZURRO);
    sprintf(TextBuffer,"Loading..");
    LCD_Text57(2,1,TextBuffer,1,BLACK,NONE);
    Xcursor=238;
    Ycursor=2;
    wFSchdir ((unsigned short int *)&str2[0]);
    DrawBmp(0,319,(unsigned short int * )&str1[0],0);

    SSD1289_writeResgiter( 0x0049, 0x013F );
    while(TRUE)
    {
        if(PORTDbits.RD14==0)
        {
            read();
            clu=getX();
            dat=getY();
            clu=(unsigned short int)((((float)6.01/(float)233.01)*(float)clu)+(float)clu);
            dat=(unsigned short int)((((float)10.01/(float)313.01)*(float)dat)+(float)dat);
            b=0;
            for(i=0; i<31; i++)
            {
                ///lettere
                if((LetterPosX[b]<=clu)&&(clu<=(LetterPosX[b]+29))&&((LetterPosY[i]<=dat)&&(dat<=(LetterPosY[i]+29))))//la Q
                {
                    ///se attivo caratteri speciali
                    if(NumSp) c[0]=SpecialKeyBuffer[i];
                    else c[0]=KeyBuffer[i];
                    if((UppLow==1)&&(NumSp==0))
                    {
                        switch(c[0])
                        {
                            case ',':
                                break;
                            case' ':
                                break;
                            case'.':
                                break;
                            default:
                                c[0]+=0x20;
                                break;
                        }
                    }
                     
                    LCD_FastRect(Xcursor-6,Ycursor,Xcursor,Ycursor+5,WHITE);
                    strcpy(TextBuffer,c);
                    StringBuffer[Nchar]=c[0];
                    LCD_Text57Land(Xcursor,Ycursor,TextBuffer,1,BLACK,NONE);
                    Nchar++;
                    //Ycursor+=6;
                    if(Ycursor>=319)
                    {
                        Ycursor=2;
                        Xcursor-=8;
                        Nchar=0;
                    }
                    DelayMs(50);
                }
                if(i==9) b++;
                if(i==18) b++;
                if(i==25) b++;
            }

            ///comandi speciali
            b=2;
            for(i=0; i<6; i++)
            {
                if((LetterPosX[b]<=clu)&&(clu<=(LetterPosX[b]+29))&&((SpecialCharPosY[i]<=dat)&&(dat<=(SpecialCharPosY[i]+34))))//la Q
                {
                    switch(i)
                    {
                        case 0:
                            ///da implementare Upper/lower letter
                            if(UppLow==0)
                            {
                                UppLow=1;
                                LCD_Cercle(53,29,3,1,GRAY);
                            }
                            else
                            {
                                UppLow=0;
                                LCD_Cercle(53,29,3,1,BLUE);
                            }
                            break;
                        case 1:
                            LCD_FastRect(Xcursor-6,Ycursor,Xcursor,Ycursor+5,AZZURRO);
                            Ycursor-=6;
                            Nchar--;
                            if(Ycursor>350) 
                            {
                                Ycursor=314;
                                Xcursor+=8;
                                Nchar=0;
                               if(Xcursor>241) Xcursor=238;
                            }
                            break;
                         case 2:
                            ///da implementare
                            break;
                         case 3:
                            ///da implementare
                            break;
                         case 4:
                            ///da implementare attiva/disattiva numeri+caratteri speciali
                             if(NumSp==0)
                             {
                                 NumSp=1;
                                 LCD_Cercle(22,274,3,1,BLUE);
                             }
                             else
                             {
                                 NumSp=0;
                                 LCD_Cercle(22,274,3,1,GRAY);
                             }
                             break;
                        case 5:
                            ///torna a capo riga (invio)
                            LCD_FastRect(Xcursor-6,Ycursor,Xcursor,Ycursor+5,AZZURRO);
                            NumSp=0;
                            LCD_Cercle(22,274,3,1,GRAY);
                            UppLow=0;
                            LCD_Cercle(53,29,3,1,BLUE);
                            
                            Ycursor=2;
                            Xcursor-=8;
                            if(Xcursor<=136)
                            {
                                LCD_FastRect(121,0,239,319,AZZURRO);
                                Xcursor=238;
                            }
                            ReadCmd=1;
                            StringBuffer[Nchar]=0x00;
                            Nchar=0;
                            break;
                    }
                    DelayMs(50);
                }
                if(i==1) b=3;
            }
        }


        ///Lampeggio cursore
        DelayMs(1);
        DelCount++;
        if(DelCount==200)
        {
            DelCount=0;
            if(a==0x00000) a=0xffff;
            else a=0x0000;
            LCD_FastRect(Xcursor-6,Ycursor,Xcursor,Ycursor+5,a);
         }

        ///Se premuto invio..
        if(ReadCmd==1)
        {
            ReadCmd=0;
            ErrorSyntax=0;
            Parametri=0;
            b=0;

            ///Ciclo per verificare la stringa passata
            ///carica in Param1, Param2, Param3, ogni parola separata da uno spazio
            for(i=0; i<20; i++)
            {
                if(StringBuffer[i]==0x20) {Parametri=1; Param1[i]=0x00; break;}
                if(StringBuffer[i]==0x00) {Parametri=1; Param1[i]=0x00; break;}
                Param1[i]=StringBuffer[i];
            }

            if(StringBuffer[i]!=0x00)
            {
                b=0;
                for(i<20; i++;)
                {
                    if(StringBuffer[i]==0x20) {Parametri=2; Param2[b]=0x00; break;}
                    if(StringBuffer[i]==0x00) {Parametri=2; Param2[b]=0x00; break;}
                    Param2[b]=StringBuffer[i];
                    b++;
                }
            }

            if(StringBuffer[i]!=0x00)
            {
                b=0;
                for(i<20; i++;)
                {
                    if(StringBuffer[i]==0x20) {Parametri=3; Param3[b]=0x00;   break;}
                    if(StringBuffer[i]==0x00) {Parametri=3; Param3[b]=0x00; break;}
                    Param3[b]=StringBuffer[i];
                    b++;
                }
            }

            if(StringBuffer[i]!=0x00)
            {
                b=0;
                for(i<20; i++;)
                {
                    if(StringBuffer[i]==0x20) {Parametri=4; Param4[b]=0x00;   break;}
                    if(StringBuffer[i]==0x00) {Parametri=4; Param4[b]=0x00; break;}
                    Param4[b]=StringBuffer[i];
                    b++;
                }
            }

            if(StringBuffer[i]!=0x00)
            {
                b=0;
                for(i<20; i++;)
                {
                    if(StringBuffer[i]==0x20) {Parametri=5; Param5[b]=0x00;   break;}
                    if(StringBuffer[i]==0x00) {Parametri=5; Param5[b]=0x00; break;}
                    Param5[b]=StringBuffer[i];
                    b++;
                }
            }
            ///Fine ciclo

            //Verifica le stringhe
            //da completare salta al programma...
            if(strcmp(Param1,"HIGH")==FALSE) HighApp=1;
            if(strcmp(Param1,"LOW")==FALSE) LowApp=1;
            if(strcmp(Param1,"EXIT")==FALSE) ExitApp=1;
            if(strcmp(Param1,"REBOOT")==FALSE) SoftReset();
            if(strcmp(Param1,"SEND")==FALSE) SendApp=1;
            if(strcmp(Param1,"INITRF")==FALSE) InitRfApp=1;
            if(strcmp(Param1,"STATUSRF")==FALSE) StatusRfApp=1;
            if(strcmp(Param1,"READRF")==FALSE) ReadApp=1;
            if(strcmp(Param1,"SETTIME")==FALSE) SetTime=1;
            if(strcmp(Param1,"SETDATE")==FALSE) SetDate=1;


            if((HighApp==0)&&(LowApp==0)&&(ExitApp==0)&&(SendApp==0)&&(InitRfApp==0)&&(StatusRfApp==0)&&(ReadApp==0)&&(SetTime==0)&&(SetDate==0)) SyntaxError=1;

            if(SetTime)
            {
                SetTime=0;
                Ore[0]=Param2[0];
                Ore[1]=Param2[1];
                Minuti[0]=Param3[0];
                Minuti[1]=Param3[1];
                
                if((Ore[0]>=0x32)&&(Ore[1]>=0x34))
                {
                    sprintf(StringBuffer,"Ore invalide!");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,RED,NONE);
                }
                else if(Minuti[0]>=0x36)
                {
                    sprintf(StringBuffer,"Minuti  invalidi!");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,RED,NONE);
                }
                else{
                    
                    lastTime.hour=atobcd(&Ore[0]);
                    lastTime.min=atobcd(&Minuti[0]);               
                    RtccSetTimeDate(lastTime.l, lastDate.l);
                    sprintf(StringBuffer,"Time updated!");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                }
            }

            if(StatusRfApp)
            {
                StatusRfApp=0;
                StatusRead();
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.RG_FF_IT);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.POR);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.RGUR_FFOV);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.WKUP);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.EXT);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.LBD);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.FFEM);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.RSSI_ATS);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.DQD);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.CRL);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor+=16;
                sprintf(StringBuffer,"%02x ",TransceiverStatus.bits.ATGL);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                Ycursor=2;
            }

            if(InitRfApp)
            {
                InitRfApp=0;

                if(strcmp(Param2,"OFF")==FALSE)
                {
                    MRF49XA_Power_Down();
                    sprintf(StringBuffer,"RF Stopped!");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,RED,NONE);
                }

                else{
                    initRFPorts();
                    MRF49XA_Init();
                    InitRFData(&rfData);
                    sprintf(StringBuffer,"RF Initialized! %x",RF_IRQ);
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);

                }
            }

            if(ReadApp)///Test sniff pacchetti
            {
                WORD GENCREG2    = (0x8000|XTAL_LD_CAP_125);
                WORD CFSREG2                             ;
                WORD DRVSREG2                            ;
                WORD RXCREG2                             ;
                WORD PMCREG2 = 0x8201;
                WORD TXCREG2 = 0x9850;
                volatile BOOL RxPacketValid[BANK_SIZE];
                BYTE RxPacket[BANK_SIZE][80];
                volatile BYTE RxPacketLen[BANK_SIZE];
                WORD totalReceived = 0;
                unsigned char FreqBand=0,DataRate=0,Nop=0;
                ReadApp=0;
                sprintf(StringBuffer,"Reading..");
                  LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,AZZURRO);
                //Setta le porte
                mPORTFSetPinsDigitalOut(BIT_5);//SDO
                mPORTFSetPinsDigitalOut(BIT_13);//SCK
                mPORTBSetPinsDigitalOut(BIT_14);//CS
                mPORTBSetPinsDigitalOut(BIT_13);//FSEL
                mPORTESetPinsDigitalIn(BIT_9);//FINT
                mPORTESetPinsDigitalIn(BIT_8);//IRQ
                mPORTFSetPinsDigitalIn(BIT_4);//SDI
                mPORTFSetPinsDigitalIn(BIT_12);//INT

                SPI4CON = 0x0120;
                //SPI1BRG = 0x001F; // 64:1 prescale (slow display update)
                SPI4BRG = 0x0001; // 4:1 prescale (fast display update) 16Mhz spi clock at 72Mhz sys clock
                SPI4CONSET = 0x8000; // enables the spi

                RF_RSCLR;
                DelayUs(10);
                RF_RSSET;
                DelayMs(125);
                RF_CSSET;
                RF_FSELSET;
                //RF_SCKCLR;
                //RF_SDOCLR;
                ///Fine init porte

                i=Param2[0];

                //i=1;
                switch(i)
                {
                    case '1':
                        FreqBand = 1;
                        break;
                    case '2':
                        FreqBand = 2;
                        break;
                    case '3':
                        FreqBand = 3;
                        break;
                }
                GENCREG2 |= ((WORD)FreqBand << 4);

                i=Param3[0];
                //i=1;
                switch(i)
                {
                    case '1':
                        DataRate = 1;
                        DRVSREG2 = 0xC623;
                        break;
                    case '2':
                        DataRate = 2;
                        DRVSREG2 = 0xC611;
                        break;
                    case '3':
                        DataRate = 3;
                        DRVSREG2 = 0xC608;
                        break;
                    case '4':
                        DataRate = 4;
                        DRVSREG2 = 0xC605;
                        break;
                    case '5':
                        DataRate = 5;
                        DRVSREG2 = 0xC602;
                        break;
                }

                i=Param4[0];
                //i=4;
                switch(i)
                {
                    case '1':
                        RXCREG2 = 0x9421;
                        break;

                    case '2':
                        RXCREG2 = 0x9441;
                        break;

                    case '3':
                        RXCREG2 = 0x9461;
                        break;

                    case '4':
                        RXCREG2 = 0x9481;
                        break;

                    case '5':
                        RXCREG2 = 0x94A1;
                        break;

                    case '6':
                        RXCREG2 = 0x94C1;
                        break;
                }

                switch(FreqBand)
                {
                    case 1:
                        CFSREG2 = 0xA640;
                        break;

                    case 2:
                        CFSREG2 = 0xA640;
                        break;

                    case 3:
                        CFSREG2 = 0xA7D0;
                        break;

                    default:
                        break;
                }

                
                
                //Init RF
                SPI_Command(FIFORSTREG);
                SPI_Command( FIFORSTREG | 0x0002);
                SPI_Command(GENCREG2);
                SPI_Command(0xC4F7);
                SPI_Command(CFSREG2);
                SPI_Command(DRVSREG2);
                SPI_Command(PMCREG2);
                SPI_Command(RXCREG2);
                SPI_Command(TXCREG2);
                SPI_Command(PMCREG2 | 0x0020);
                DelayMs(5);
                SPI_Command(PMCREG2 | 0x0080);
                SPI_Command(GENCREG2 | 0x0040);
                SPI_Command(FIFORSTREG);
                SPI_Command( FIFORSTREG | 0x0002);
                SPI_Command(0x0000);

                //InitRFData(&rfData);
                sprintf(StringBuffer,"%x, %x, %x",Param2[0],Param3[0],Param4[0]);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,AZZURRO);
                sprintf(StringBuffer,"%x,%x",RF_IRQ,RF_INT);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,AZZURRO);
                while(TRUE)
                {
                    if((RF_IRQ==0)||(RF_INT==1))
                    {
                        
                        //nCS = 0;
                        RF_CSCLR;
                        Nop++;
                        if( SPI_SDI == 1 )
                        {
                            BYTE RxPacketPtr;
                            BYTE tmpPacketLen;
                            BYTE bIndex;
                            WORD counter;

                            // There is data in RX FIFO
                            //nCS = 1;
                            //nFSEL = 0;                   // FIFO selected
                            RF_CSSET;
                            RF_FSELCLR;

                            tmpPacketLen = SPI_Read();

                            for(bIndex = 0; bIndex < BANK_SIZE; bIndex++)
                            {
                                if( RxPacketValid[bIndex] == FALSE )
                                {
                                    break;
                                }
                            }

                            if( tmpPacketLen >= 80 || tmpPacketLen == 0 || bIndex >= BANK_SIZE )
                            {
                                IGNORE_HERE:
                                //nFSEL = 1;                          // bad packet len received
                                RF_FSELSET;
                                SPI_Command(PMCREG2);                // turn off the transmitter and receiver
                                SPI_Command(FIFORSTREG);            // reset FIFO
                                SPI_Command(GENCREG2);               // disable FIFO, TX_latch
                                SPI_Command(GENCREG2 | 0x0040);      // enable FIFO
                                SPI_Command(PMCREG2 | 0x0080);       // turn on receiver
                                SPI_Command(FIFORSTREG | 0x0002);   // FIFO synchron latch re-enabled
                                goto RETURN_HERE;
                            }

                            RxPacketLen[bIndex] = tmpPacketLen;
                            //RLED = 1;
                            //nFSEL = 1;
                            mPORTDSetBits(BIT_2);
                            RF_FSELSET;

                            RxPacketPtr = 0;
                            counter = 0;

                            while(1)
                            {
                                if( counter++ == 0xFFFF )
                                {
                                    goto IGNORE_HERE;
                                }
                                else if( RF_FINT == 1)
                                    {
                                    //nFSEL = 0;
                                    RF_FSELCLR;
                                    counter = 0;
                                    RxPacket[bIndex][RxPacketPtr++] = SPI_Read();

                                    if( RxPacketPtr >= RxPacketLen[bIndex] )
                                    {
                                        BYTE i;

                                        //nFSEL = 1;
                                        //nCS = 0;
                                        RF_FSELSET;
                                        RF_CSCLR;

                                        //SPI_SDO = 0;
                                        RF_SDOCLR;
                                        Nop++;
                                        for(i = 0; i < 8; i++)
                                        {
                                            //SPI_SCK = 1;
                                            //SPI_SCK = 0;                                       
                                            RF_SCKSET;
                                            Nop++;
                                            RF_SCKCLR;
                                            Nop++;
                                        }


                                        if( SPI_SDI == 0 )
                                        {
                                            goto IGNORE_HERE;
                                        }
                                        //nCS = 1;
                                        RF_CSSET;


                                        SPI_Command(FIFORSTREG);
                                        //RLED = 0;
                                        mPORTDClearBits(BIT_2);
                                        RxPacketValid[bIndex] = TRUE;
                                        SPI_Command(FIFORSTREG | 0x0002);            // FIFO synchron latch re-enable

                                        goto RETURN_HERE;
                                    }
                                    //nFSEL = 1;
                                    RF_FSELSET;
                                    }
                                }
                            }
                            else            // read the rest of the interrupts
                            {
                                SPI_Read();

                                //nCS = 1;
                                RF_CSSET;
                            }

                            RETURN_HERE:
                        Nop++;
                    }
                    
                    for(i = 0; i < BANK_SIZE; i++)
                    {
                        if( RxPacketValid[i] == TRUE )
                        {
                            BYTE j;
                            WORD received_crc;
                            WORD calculated_crc;
                
                            totalReceived++;  
                            //Printf("\r\n");
                            Xcursor-=8;
                            Ycursor=2;

                            sprintf(StringBuffer,"%04x | %04x |",totalReceived,RxPacketLen[i]);
                            LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                            //PrintChar(totalReceived>>8);
                            //PrintChar(totalReceived);

                            //Printf(" | ");
                            //PrintChar(RxPacketLen[i]);
                            //Printf(" | ");

                            for(j = 0; j < RxPacketLen[i]; j++)
                            {
                                sprintf(StringBuffer,"%02x ",RxPacket[i][j]);
                                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                                Ycursor+=12;
                                //PrintChar(RxPacket[i][j]);
                                //Printf(" ");
                            }
                            received_crc = ((WORD)RxPacket[i][RxPacketLen[i]-1]) + (((WORD)RxPacket[i][RxPacketLen[i]-2]) << 8);
                            calculated_crc = CRC16(RxPacket[i], RxPacketLen[i]-2);
                            if( received_crc != calculated_crc )
                            {
                                //Printf(" * CRC");
                                sprintf(StringBuffer," * CRC");
                                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
                            }
                            RxPacketValid[i] = FALSE;
                
                        }
                    }





















                    //i=MRF49XA_Receive_Packet(&rfData);
                    //DelayUs(50);
                    //if(i==3) break;
                    //if(i==2) break;
                    //if(i==1) break;
                    //sprintf(StringBuffer,"%x,%x,%x",RF_IRQ,RF_FINT,SPI_SDI);
                    //LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,AZZURRO);
                    if(PORTDbits.RD14==0) break;
                }
                Xcursor-=8;

                sprintf(StringBuffer,"Ricevuto! %d, 0x%02x, 0x%02x, 0x%02x, 0x%02x",i,rfData.buffer[0],rfData.buffer[1],rfData.buffer[2],rfData.buffer[3]);
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);


}
            if(SendApp)
            {
                SendApp=0;
                //LCD_FastRect(121,0,239,319,AZZURRO);
                AddRFData(&rfData,Param2[0]);
                MRF49XA_Send_Packet(&rfData);
		InitRFData(&rfData);

                sprintf(StringBuffer,"Dato inviato..");
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,BLACK,NONE);
            }
            if(HighApp)
            {
                HighApp=0;
                if(strcmp(Param2,"D2")==FALSE)
                {
                    sprintf(StringBuffer,"D2 Actived! 1");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,GREEN,NONE);
                    mPORTDSetPinsDigitalOut(BIT_2);
                    mPORTDSetBits(BIT_2);
                 }
                 else
                 {
                    sprintf(StringBuffer,"Port Not Found!");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,RED,NONE);
                 }
            }
            if(LowApp)
            {
                LowApp=0;
                if(strcmp(Param2,"D2")==FALSE)
                {
                    sprintf(StringBuffer,"D2 Deactived! 0");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,GREEN,NONE);
                    mPORTDSetPinsDigitalOut(BIT_2);
                    mPORTDClearBits(BIT_2);
                }
                else
                {
                    sprintf(StringBuffer,"Port Not Found!");
                    LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,RED,NONE);
                }
            }

            if(SyntaxError)
            {
                SyntaxError=0;
                sprintf(StringBuffer,"Syntax Error!");
                LCD_Text57Land(Xcursor,Ycursor,StringBuffer,1,RED,NONE);
            }

            if(ExitApp==1) break;
            
            Xcursor-=8;
            Ycursor=2;
            
            for(i=0; i<10; i++)
            {
                StringBuffer[i]=0x00;
                Param1[i]=0x00;
                Param2[i]=0x00;
                Param3[i]=0x00;
            }
        }
        if(PORTDbits.RD3==0) break;
    }
}
示例#20
0
int main(int argc, char** argv) {

    uchar status = 0;
    
    mPORTAClearBits(BIT_6);           //Clear bits to ensure the LED is off.
    //mPORTASetPinsDigitalOut(BIT_6);   //Set port as output
  
    // lets set the digital IO bits for the ethernet module
    mPORTASetPinsDigitalOut(BIT_7|BIT_6);
    mPORTGSetPinsDigitalOut(BIT_8 | BIT_9 | BIT_14 | BIT_0);
    mPORTBSetPinsDigitalOut(0x0000FFFF);
    mPORTESetPinsDigitalOut(0x000000FF);
    
    // set the control bits high
    mPORTASetBits(BIT_7);
    mPORTGSetBits(BIT_8 | BIT_9 | BIT_14);
    mPORTGClearBits(BIT_0);
    //mPORTGClearBits(BIT_0);
    //mPORTGClearBits(0x0000FFFF);
    //mPORTEClearBits(0x0000FFFF);
    //mPORTAClearBits(0x0000FFFF);
    //mPORTBClearBits(0x0000FFFF);
    
    //while(1){}

    // lets init the W5100
    struct W5100Context_t context;
    context.Mode = MR_RST;
    context.InterruptMask = 0xFF;
    context.RetryTimeValue = 0x0FA0; // 400 ms
    context.RetryCount = 1;
    
    context.GateAdd[0] = 10;
    context.GateAdd[1] = 1;
    context.GateAdd[2] = 1;
    context.GateAdd[3] = 3;
    
    context.SHardAdd[0] = 0;
    context.SHardAdd[1] = 1;
    context.SHardAdd[2] = 2;
    context.SHardAdd[3] = 3;
    context.SHardAdd[4] = 4;
    context.SHardAdd[5] = 5;
    
    context.Subnet[0] = 255;
    context.Subnet[1] = 255;
    context.Subnet[2] = 255;
    context.Subnet[3] = 0;
    
    context.SourceIP[0] = 10;
    context.SourceIP[1] = 1;
    context.SourceIP[2] = 1;
    context.SourceIP[3] = 2;
    
    context.sockets[0].Mem = MEM_2K;
    context.sockets[1].Mem = MEM_2K;
    context.sockets[2].Mem = MEM_2K;
    context.sockets[3].Mem = MEM_2K;
    
    ShortDelay_ms(100);
    
    W5100Init( &context );
  
    W5100ReadData(SHAR0, &status, 1);
    W5100ReadData(SHAR1, &status, 1);
    W5100ReadData(SHAR2, &status, 1);
    W5100ReadData(SHAR3, &status, 1);
    W5100ReadData(SHAR4, &status, 1);
    W5100ReadData(SHAR5, &status, 1);
    
    EstablishServer(&context);
    
    // lets try a random write
    //W5100WriteData(0x001A, 0x07, 1);
    //mPORTEWrite(0x07);
    
    
  
    
     while(1)
     {
     
        status = W5100PollStatus(&context, 0);
        if( status == SOCK_ESTABLISH)
            mPORTGSetBits(BIT_0);
        else
            mPORTGClearBits(BIT_0);
        
        if( status == SOCK_CLOSE_WAIT)
            EstablishServer(&context);
        
        
         //PORTAbits.RA2 = ~PORTAbits.RA2;
        mPORTAToggleBits(BIT_6);
        ShortDelay(US_TO_CT_TICKS*1000000);
        //delay_millis(1000);
   
     }
     
    return (EXIT_SUCCESS);
}