예제 #1
0
/*
 * Initialize the board
 * Timers, Communication, etc
 * Note : Should only be called once at the begginning of the main
 */
void InitBoard(void)
{
    // Initialize clock
    SYSTEMConfigPerformance(GetSystemClock());
    SYSTEMConfig(GetSystemClock(), SYS_CFG_PCACHE);
    SYSTEMConfig(GetSystemClock(), SYS_CFG_PB_BUS);
    SYSTEMConfigPB(GetSystemClock());
    INTEnableSystemMultiVectoredInt();

    //Disable JTAG port
    DDPCONbits.JTAGEN = 0;

    // Initialize LEDs
    LED1_TRIS = 0;
    LED2_TRIS = 0;

    // Initialize Timers
    InitTimers();

    // Initialize CAN bus
    CRX1_TRIS = 1;
    CTX1_TRIS = 0;
    netv_init_can_driver(GetBoardID(),CAN1);
    
    // Initialize digital IOs as inputs
    DIO_TRIS |= DIO_MASK;
    
    // Initialize Relays (low)
    RELAY1_TRIS = 0;
    RELAY2_TRIS = 0;
    RELAY1 = 0;
    RELAY2 = 0;
    
    // Initialize SPI pins as inputs
    SPICLK_TRIS = 1;
    SPISDO_TRIS	= 1;
    SPI_CS_TRIS = 1;
    SPISDI_TRIS	= 1;
    
    //TODO: Init unused pins as inputs
    
    // Read the board ID
    m_unBoardId = (DIO_PORT & DIO_MASK) ^ DIO_MASK;

    // Read the parameters previously saved in flash
    loadDataFromMemory();
    
    //Enables the core to handle any pending interrupt requests
    asm volatile ("ei"); 
}
예제 #2
0
파일: MainDemo.c 프로젝트: ftapparo/Arduino
/****************************************************************************
  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)
{	
	// LEDs
	LED0_TRIS = 0;
	LED1_TRIS = 0;
	LED2_TRIS = 0;
	LED3_TRIS = 0;
	LED4_TRIS = 0;
	LED5_TRIS = 0;
	LED6_TRIS = 0;
	LED_PUT(0x00);

	// 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
	DelayMs(50);
	DDPCONbits.JTAGEN = 0;
	LED_PUT(0x00);				// Turn the LEDs off
	
	AD1PCFGbits.PCFG2 = 0;		// Disable digital input on AN2 (potentiometer)
		
	// ADC
	AD1CON1 = 0x84E4;			// Turn on, auto sample start, auto-convert, 12 bit mode (on parts with a 12bit A/D)
	AD1CON2 = 0x0404;			// AVdd, AVss, int every 2 conversions, MUXA only, scan
	AD1CON3 = 0x1003;			// 16 Tad auto-sample, Tad = 3*Tcy
	// PIC32MX460F512L PIM has different pinout to accomodate USB module
	AD1CSSL = 1<<2;				// Scan pot
}
예제 #3
0
파일: main.c 프로젝트: timwuu/PK2BL32
void setup() {

    int value;

    value = SYSTEMConfigWaitStatesAndPB(GetSystemClock());

    // Enable the cache for the best performance
    CheKseg0CacheOn();

    INTEnableSystemMultiVectoredInt();

    value = OSCCON;
    while (!(value & 0x00000020)) {
        value = OSCCON; // Wait for PLL lock to stabilize
    }

    LATB=0;

    ANSELA = 0x00;
    ANSELB = 0x00;
    TRISA = 0xFFFF;
    TRISB = 0xFFFF;

    TRISBbits.TRISB1= OUTPUT_PIN;
    TRISBbits.TRISB2= OUTPUT_PIN;
    TRISBbits.TRISB3= OUTPUT_PIN;

    //?timijk debug
    //TRISBbits.TRISB4= OUTPUT_PIN;
    
    ConfigurePinReMap();
    
}
예제 #4
0
파일: main.c 프로젝트: AleSuky/SkP32v1.1
// *--------------------------------------------------------------------------------*
int main(){
	
    mJTAGPortEnable(0);							// JTAG des-habilitado
	SYSTEMConfigPerformance(GetSystemClock()); 	// Activa pre-cache.-
	
	AD1PCFG = 0xFFFF;
	LED1_OUTPUT();
	LED2_OUTPUT();
	SW1_INPUT();
	SW2_INPUT();
	
	buttonCount = 0;
    buttonPressed = FALSE;
    stringPrinted = TRUE;
	
	USBDeviceInit();	
	while(1){
		#if defined(USB_INTERRUPT)
		if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE)){
			USBDeviceAttach();
		}
		#endif
		#if defined(USB_POLLING)
			// Check bus status and service USB interrupts.
			USBDeviceTasks();
		#endif
		ProcessIO();
	}
}
예제 #5
0
파일: uart.c 프로젝트: JugaadSolutions/SCS
void UART2_init(unsigned long baudRate)
{
	UINT8 uartConfig= USART_TX_INT_OFF &
				USART_RX_INT_ON &
				USART_ASYNCH_MODE &
				USART_EIGHT_BIT &
				USART_CONT_RX &
				USART_BRGH_HIGH;

	baudRate += (unsigned long)1;
	baudRate *= (unsigned long)16;
	baudRate = GetSystemClock() / baudRate;

	Open2USART( uartConfig ,
				baudRate);
// Enable interrupt priority
//  	RCONbits.IPEN = 1;
	RCSTA2bits.SPEN = 1;
	TXSTA2bits.TXEN = 1;	//enable transmission
	TXSTA2bits.CSRC = 0;
	PIE3bits.RC2IE = 1;

	IPR1bits.TXIP = 1;	//make transmit interrupt high priority



  	// Make receive interrupt high priority
//  	IPR3bits.RC2IP = 1;

}
예제 #6
0
파일: system.c 프로젝트: Athuli7/Microchip
/****************************************************************************
  Function:
    void SYS_Init(void)

  Summary:
    Initialize the PIC32 core to the correct modes and clock speeds

  Description:
    Initialize the PIC32 core to the correct modes and clock speeds

  Precondition:
    Only runs on PIC32

  Parameters:
    None

  Return Values:
    None

  Remarks:
    None
  ***************************************************************************/
void SYS_Init(void)
{
    int  value;

    #if defined(RUN_AT_60MHZ)
        // Use OSCCON default
    #else
        OSCCONCLR = 0x38000000; //PLLODIV
        #if defined(RUN_AT_48MHZ)
            OSCCONSET = 0x08000000; //PLLODIV /2
        #elif defined(RUN_AT_24MHZ)
            OSCCONSET = 0x10000000; //PLLODIV /4
        #else
            #error Cannot set OSCCON
        #endif
    #endif

    value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() );

    // Enable the cache for the best performance
    CheKseg0CacheOn();

    INTEnableSystemMultiVectoredInt();

    DDPCONbits.JTAGEN = 0;

    value = OSCCON;
    while (!(value & 0x00000020))
    {
        value = OSCCON;    // Wait for PLL lock to stabilize
    }

    INTEnableInterrupts();
}
예제 #7
0
파일: main.c 프로젝트: wonkill/W7500P
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main()
{

    /* External Clock */
    CRG_PLL_InputFrequencySelect(CRG_OCLK);


    /* Set Systme init */
    SystemInit();

    /* CPIO configuration */
    GPIO_Setting();

    /* Get System Clock */
    sysclock = GetSystemClock();

    /* SysTick_Config */
    SysTick_Config((sysclock/1000));

    while(1)
    {
        delay(1000);
        /* RED LED toggled */
        if(GPIO_ReadOutputDataBit(GPIOC,GPIO_Pin_0) != (uint32_t)Bit_RESET)
            GPIO_ResetBits(GPIOC, GPIO_Pin_0);
        else
            GPIO_SetBits(GPIOC, GPIO_Pin_0);
    }

}
예제 #8
0
BOOL InitializeSystem ( void )
{

    int  value;

    value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() );

    // Enable the cache for the best performance
    CheKseg0CacheOn();

    INTEnableSystemMultiVectoredInt();

    value = OSCCON;
    while (!(value & 0x00000020))
    {
        value = OSCCON;    // Wait for PLL lock to stabilize
    }

    // Init UART
    UART2Init();
    // Set Default demo state
    DemoState = DEMO_INITIALIZE;
	if(USBHostIsochronousBuffersCreate(&isocData,2,1024)){
    	UART2PrintString( "CreateIsochronousBuffers\r\n" );
	}else{
        UART2PrintString( "Fail:CreateIsochronousBuffers\r\n" );
	}

    return TRUE;
} // InitializeSystem
예제 #9
0
void TheApp::Update() {
    static double lastTime = GetCurrentSeconds();
    double currentTime = GetCurrentSeconds();
    double deltaSeconds = currentTime - lastTime;
    lastTime = currentTime;

    if(deltaSeconds > 0.5) {
        deltaSeconds = 0.5;
    }

    //system clock
    GetSystemClock().AdvanceTime(deltaSeconds);

    deltaSeconds = GetSystemClock().GetChild("GameClock")->GetDeltaSeconds();

    if(m_world) {
        m_world->Update(deltaSeconds );
    }

    if (m_jobManager) {
        m_jobManager->Update();
    }

    if (m_networkSystem) {
        m_networkSystem->Update();
    }

    //update debug shapes
    if (m_renderer) {
        g_debugShapes.Update(deltaSeconds);
    }

// 	if(m_soundSystem){
// 		m_soundSystem->Update();
// 	}

    if (m_textSystem) {
        m_textSystem->Update(deltaSeconds);
    }

    if (m_particleSystem) {
        m_particleSystem->Update(deltaSeconds);
    }

}
예제 #10
0
void SetFlashWaitStates_old()
{
	SystemUnlock();
#if defined(PIC32_PINGUINO_220)||defined(GENERIC32MX250F128)||defined(GENERIC32MX220F032)
	PMMODEbits.WAITB = 0b00;					// Data wait of 1 TPB
#else
	CHECON = (GetSystemClock() / 20) - 1;		// FlashWaitStates
#endif
	SystemLock();
}
예제 #11
0
//////////////////////////////////////////////////////////////////////////////////
// LED-Strip Writer
//////////////////////////////////////////////////////////////////////////////////
void lw_setup() {
	// start by writting zeros to wake-up latch(s)
	lw_state = LW_S_WAIT_TO_WRITE_ZEROS;
	lw_pixelIndex = 0;
	lw_zeroCounter = ZEROS_NEEDED;

	SPI_init();
	/* 10mhz - faster is not working */
	SPI_clock(GetSystemClock() / SPI_PBCLOCK_DIV8);
	SPI_mode(SPI_MASTER);
	BUFFER = 0x00; // Trigger STATRX
}
예제 #12
0
파일: delay.c 프로젝트: jrapp01/SrDesign
void DelayMs(WORD delay)
{
    unsigned int int_status;
    while( delay-- )
    {
        OpenCoreTimer(GetSystemClock() / 2000);
        mConfigIntCoreTimer((CT_INT_ON | CT_INT_PRIOR_2 | CT_INT_SUB_PRIOR_0));
		while(!dflag);
   		dflag=0;
    }
	mDisableIntCoreTimer();
}
예제 #13
0
void SetFlashWaitStates_old()
{
    SystemUnlock();
    #if !defined(PIC32_PINGUINO_220) && \
        !defined(PINGUINO32MX220)    && \
        !defined(PINGUINO32MX250)    && \
        !defined(PINGUINO32MX270)
    
        CHECON = (GetSystemClock() / 20) - 1;		// FlashWaitStates
    
    #endif
    SystemLock();
}
예제 #14
0
파일: us_ticker.c 프로젝트: Babody/mbed
void us_ticker_init(void)
{
    if (us_ticker_inited) return;
    us_ticker_inited = 1;

    SystemCoreClockUpdate();
    TimerInitType.PWM_CHn_PR = (GetSystemClock() / 1000000) -1;
    TimerInitType.PWM_CHn_LR = 0xFFFFFFFF;
    TimerInitType.PWM_CHn_PDMR = 1;

    PWM_TimerModeInit(TIMER_1, &TimerInitType);
    PWM_CHn_Start(TIMER_1);
}
예제 #15
0
파일: user.c 프로젝트: eelcor/Wireless_PIC
 //*****************************************************************************
 // DelayMs creates a delay of given miliseconds using the Core Timer
 //
 void DelayMs(WORD delay)
 {
     unsigned int int_status;
     while( delay-- )
     {
         int_status = INTDisableInterrupts();
         OpenCoreTimer(GetSystemClock() / 2000);
         INTRestoreInterrupts(int_status);
         mCTClearIntFlag();
         while( !mCTGetIntFlag() );
     }
     mCTClearIntFlag();
 }
예제 #16
0
파일: main.c 프로젝트: AleSuky/SkP32v1.1
// *--------------------------------------------------------------------------------*
int main(){
	UINT16 Count=0;
	
    mJTAGPortEnable(0);							// JTAG des-habilitado
	SYSTEMConfigPerformance(GetSystemClock()); 	// Activa pre-cache.-
	
	LED1_OUTPUT();
	LED2_OUTPUT();
	INTEnableSystemMultiVectoredInt();
	deviceAttached = FALSE;
    //Initialize the stack
    USBInitialize(0);
    
	while(1){
		//USB stack process function
        USBTasks();
		if(++Count==0){
			LED1_TOGGLE();
		}
        //if thumbdrive is plugged in
        if(USBHostMSDSCSIMediaDetect()){
            deviceAttached = TRUE;
            LED1_OFF();
            //now a device is attached
            //See if the device is attached and in the right format
            if(FSInit()){
                //Opening a file in mode "w" will create the file if it doesn't
                //  exist.  If the file does exist it will delete the old file
                //  and create a new one that is blank.
                myFile = FSfopen("test.txt","w");

                //Write some data to the new file.
                FSfwrite("This is a test.",1,15,myFile);                

                //Always make sure to close the file so that the data gets
                //  written to the drive.
                FSfclose(myFile);

                //Just sit here until the device is removed.
                while(deviceAttached == TRUE){
                    USBTasks();
                    if(++Count==0){
						LED2_TOGGLE();
					}
                }
                LED2_OFF();
            }
        }
	}
}
예제 #17
0
//////////////////////////////////////////////////////////////////////////////////
// MAIN Setup & process
//////////////////////////////////////////////////////////////////////////////////
void setup() {
  // for delays - CP0Count counts at half the CPU rate
  Fcp0 = GetSystemClock() / 1000000 / 2;   // max = 40 for 80MHz

  // setup-buffers
  lw_buffer = pixel_buff_one;
  pixels = pixel_buff_two;
  
  //CDCprintf("Setup..\n");

  //lb_setup();
  lw_setup();
  lwn_setup();
  dataLink_setup();
}
예제 #18
0
파일: main.c 프로젝트: PedroDiogo/POV
void mySetLineCodingHandler(void)
{
    //If the request is not in a valid range
    if(cdc_notice.GetLineCoding.dwDTERate.Val > 115200)
    {
        //NOTE: There are two ways that an unsupported baud rate could be
        //handled.  The first is just to ignore the request and don't change
        //the values.  That is what is currently implemented in this function.
        //The second possible method is to stall the STATUS stage of the request.
        //STALLing the STATUS stage will cause an exception to be thrown in the 
        //requesting application.  Some programs, like HyperTerminal, handle the
        //exception properly and give a pop-up box indicating that the request
        //settings are not valid.  Any application that does not handle the
        //exception correctly will likely crash when this requiest fails.  For
        //the sake of example the code required to STALL the status stage of the
        //request is provided below.  It has been left out so that this demo
        //does not cause applications without the required exception handling
        //to crash.
        //---------------------------------------
        //USBStallEndpoint(0,1);
    }
    else
    {
        DWORD_VAL dwBaud;

        //Update the baudrate info in the CDC driver
        CDCSetBaudRate(cdc_notice.GetLineCoding.dwDTERate.Val);
        
        //Update the baudrate of the UART
        #if defined(__18CXX)
            dwBaud.Val = (DWORD)(GetSystemClock()/4)/line_coding.dwDTERate.Val-1;
            SPBRG = dwBaud.v[0];
            SPBRGH = dwBaud.v[1];
        #elif defined(__C30__)
            #if defined(__dsPIC33EP512MU810__) || defined (__PIC24EP512GU810__)
            dwBaud.Val = ((GetPeripheralClock()/(unsigned long)(16 * line_coding.dwDTERate.Val)))- 1;
            #else
            dwBaud.Val = (((GetPeripheralClock()/2)+(BRG_DIV2/2*line_coding.dwDTERate.Val))/BRG_DIV2/line_coding.dwDTERate.Val-1);
            #endif
            U2BRG = dwBaud.Val;
        #elif defined(__C32__)
            U2BRG = ((GetPeripheralClock()+(BRG_DIV2/2*line_coding.dwDTERate.Val))/BRG_DIV2/line_coding.dwDTERate.Val-1);
            //U2MODE = 0;
            U2MODEbits.BRGH = BRGH2;
            //U2STA = 0;
        #endif
    }
}
void DelayMs(WORD time)
{
    while(time--)
    {
        unsigned int    int_status;

        int_status = INTDisableInterrupts();
        OpenCoreTimer(GetSystemClock() / 2000); // core timer is at 1/2 system clock
        INTRestoreInterrupts(int_status);

        mCTClearIntFlag();

        while(!mCTGetIntFlag());
    }

    mCTClearIntFlag();
}
예제 #20
0
파일: pwmout_api.c 프로젝트: Babody/mbed
void pwmout_init(pwmout_t* obj, PinName pin)
{
    // Get the peripheral name from the pin and assign it to the object
    obj->PWM_CHx = (PWM_CHn_TypeDef *)pinmap_peripheral(pin, PinMap_PWM);

    if (obj->PWM_CHx == (PWM_CHn_TypeDef *)NC) {
        error("PWM error: pinout mapping failed.");
    }

    // Configure GPIO
    pinmap_pinout(pin, PinMap_PWM);
    
    GetSystemClock();

    obj->pin = pin;
    
    pwmout_period_us(obj, 20000); // 20 ms per default
}
예제 #21
0
void NetworkSession::Update(){

	//incoming?
	UpdateIncomingTraffic();

	static float secondsSinceLastUpdate = 0.0;
	double deltaSeconds = GetSystemClock().GetDeltaSeconds();
	if (secondsSinceLastUpdate < (1 / m_sendFreqHz) ) {
		secondsSinceLastUpdate += (float)deltaSeconds;
	}
	else {
		//outgoing?
		UpdateSessionConnections();

		secondsSinceLastUpdate = 0.0f; //reset seconds since last
	}


}
void SYS_Initialize ( void* data )
{

    SYSTEMConfig(GetSystemClock(), SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);
    
    /* Disable JTAG to free up PORTA pins */
    mJTAGPortEnable(DEBUG_JTAGPORT_OFF);

    BSP_Initialize();
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();
    BSP_WriteString("*** UART Interrupt-driven Application Example ***\r\n");
    BSP_WriteString("*** Type some characters and observe echo ***\r\n");


    /* Initialize the Application */
    APP_Initialize ( );

}
예제 #23
0
void S_UART_SetBaud(uint32_t baud)
{
    uint32_t uartclock = 0x00, integer_baud = 0x00;

    assert_param(IS_UART_MODE(S_UART_InitStruct->UART_Mode));

    if(CRG->FCLK_SSR == CRG_FCLK_SSR_RCLK)
    {
        uartclock = INTERN_XTAL;  
    }
    else if(CRG->FCLK_SSR == CRG_FCLK_SSR_OCLK)
    {
        uartclock = EXTERN_XTAL;
    }
    else
    {
        uartclock = GetSystemClock();
    }

    integer_baud = (uint32_t)(uartclock / baud);
    UART2->BAUDDIV = integer_baud;
}
예제 #24
0
파일: us_ticker.c 프로젝트: Babody/mbed
void us_ticker_set_interrupt(timestamp_t timestamp)
{
    int32_t dev = 0;
    
    if (!us_ticker_inited)
    {
        us_ticker_init();
    }
    
    dev = (int32_t)(timestamp - us_ticker_read());
    dev = dev * ((GetSystemClock() / 1000000) / 16);     

    if(dev <= 0)
    {
        us_ticker_irq_handler();
        return;
    }
    
    DUALTIMER_ClockEnable(TIMER_0);
    DUALTIMER_Stop(TIMER_0);
    
    TimerHandler.TimerControl_Mode       = DUALTIMER_TimerControl_Periodic;
    TimerHandler.TimerControl_OneShot    = DUALTIMER_TimerControl_OneShot;
    TimerHandler.TimerControl_Pre        = DUALTIMER_TimerControl_Pre_16;
    TimerHandler.TimerControl_Size       = DUALTIMER_TimerControl_Size_32;
    
    TimerHandler.TimerLoad      = (uint32_t)dev;
    
    DUALTIMER_Init(TIMER_0, &TimerHandler);
    
    DUALTIMER_IntConfig(TIMER_0, ENABLE);
    
    NVIC_EnableIRQ(TIMER_IRQn);
    
    DUALTIMER_Start(TIMER_0);
    

}
예제 #25
0
파일: main.c 프로젝트: AleSuky/SkP32v1.1
// *--------------------------------------------------------------------------------*
int main(){
	UINT8 k=0;
	UINT16 Conversion;
	
    mJTAGPortEnable(0);							// JTAG des-habilitado
	SYSTEMConfigPerformance(GetSystemClock()); 	// Activa pre-cache.-
	
	LED1_OUTPUT();
	LED2_OUTPUT();
	LED3_OUTPUT();
	LED4_OUTPUT();
	SW1_INPUT();
	SW2_INPUT();
	
	PORTSetPinsDigitalOut(IOPORT_D, BIT_1);		// Backlight del TFT
	mPORTDSetBits(BIT_1);
	vLCDTFTInit();
	vLCDTFTFillScreen(ColorWhite);
	vADC_Init();
	while(1){
		if(SW1_STATUS()==0){
			vLCDTFTRectangle(0,0,200,319,1,Colores[k]);
			if(++k==6){k=0;}
			DelayMs(250);
		}
		if(SW2_STATUS()==0){
			LED2_TOGGLE();
			LED4_TOGGLE();
			DelayMs(250);
		}
		Conversion=ADC_Conversion();
		vLCDTFTRectangle(201,0,239,319,1,ColorWhite);
		// 1023 -> 0; 0 -> 239
		vLCDTFTRectangle(202,((-0.31183*Conversion)+319.0),238,319,1,ColorRed);
		DelayMs(50);
	}
}
예제 #26
0
파일: usb_cdc.c 프로젝트: JP7FKF/picproject
void mySetLineCodingHandler(void)
{
#if		MAX_BAUDRATE
	//If the request is	not	in a valid range
	if(cdc_notice.GetLineCoding.dwDTERate.Val >	MAX_BAUDRATE)
	{
		//NOTE:	There are two ways that	an unsupported baud	rate could be
		//handled.	The	first is just to ignore	the	request	and	don't change
		//the values.  That	is what	is currently implemented in	this function.
		//The second possible method is	to stall the STATUS	stage of the request.
		//STALLing the STATUS stage	will cause an exception	to be thrown in	the	
		//requesting application.  Some	programs, like HyperTerminal, handle the
		//exception	properly and give a	pop-up box indicating that the request
		//settings are not valid.  Any application that	does not handle	the
		//exception	correctly will likely crash	when this requiest fails.  For
		//the sake of example the code required	to STALL the status	stage of the
		//request is provided below.  It has been left out so that this	demo
		//does not cause applications without the required exception handling
		//to crash.
		//---------------------------------------
		//USBStallEndpoint(0,1);
	}else
#endif
	{
		DWORD_VAL dwBaud;

		//Update the baudrate info in the CDC driver
		CDCSetBaudRate(cdc_notice.GetLineCoding.dwDTERate.Val);
		
		//Update the baudrate of the UART
		#if	defined(__18CXX)
			dwBaud.Val = (GetSystemClock()/4)/line_coding.dwDTERate.Val-1;
			SPBRG  = dwBaud.v[0];
			SPBRGH = dwBaud.v[1];
		#endif
	}
}
예제 #27
0
파일: main.c 프로젝트: Wiznet/W7500P
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main()
{
    //uint8_t tx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    //uint8_t rx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x01, 0x02, 0x03}; 
    uint8_t src_addr[4] = {192, 168,  0,  9};
    uint8_t gw_addr[4]  = {192, 168,  0,  1};
    uint8_t sub_addr[4] = {255, 255, 255,  0};		
    //uint8_t dns_server[4] = {8, 8, 8, 8};           // for Example domain name server
    uint8_t tmp[8];
		
		int32_t ret;
		uint16_t port=5000, size = 0, sentsize=0;
		uint8_t destip[4];
		uint16_t destport;

		*(volatile uint32_t *)(0x41001014) = 0x0060100; //clock setting 48MHz
		
		/* External Clock */
    //CRG_PLL_InputFrequencySelect(CRG_OCLK);

    /* Set Systme init */
    SystemInit();
		
		SSP0_Initialize();
		SSP1_Initialize();
		GPIO_Initialize();	

		GPIO_SetBits(GPIOC, GPIO_Pin_8); // LED red off
		GPIO_SetBits(GPIOC, GPIO_Pin_9); // LED green off
		GPIO_ResetBits(GPIOC, GPIO_Pin_6); // Test off

    /* UART Init */
    UART_StructInit(&UART_InitStructure);
    UART_Init(UART1,&UART_InitStructure);

    /* SysTick_Config */
    SysTick_Config((GetSystemClock()/1000));

    /* Set WZ_100US Register */
    setTIC100US((GetSystemClock()/10000));
    //getTIC100US();	
    //printf(" GetSystemClock: %X, getTIC100US: %X, (%X) \r\n", 
    //      GetSystemClock, getTIC100US(), *(uint32_t *)TIC100US);        


#ifdef __DEF_USED_IC101AG__ //For using IC+101AG
    *(volatile uint32_t *)(0x41003068) = 0x64; //TXD0 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x4100306C) = 0x64; //TXD1 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003070) = 0x64; //TXD2 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003074) = 0x64; //TXD3 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003050) = 0x64; //TXE  - set PAD strengh and pull-up
#endif	
    printf("PHY is linked. \r\n"); 
#ifdef __DEF_USED_MDIO__ 
    /* mdio Init */
    mdio_init(GPIOB, MDC, MDIO );
    //mdio_error_check(GPIOB, MDC, MDIO); //need verify...
    /* PHY Link Check via gpio mdio */
    while( link() == 0x0 )
    {
        printf(".");  
        delay(500);
    }
    printf("PHY is linked. \r\n");  
#else
    delay(1000);
    delay(1000);
#endif

    /* Network Configuration */
    setSHAR(mac_addr);
    setSIPR(src_addr);
    setGAR(gw_addr);
    setSUBR(sub_addr);

    getSHAR(tmp);
    printf(" MAC ADDRESS : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\r\n",tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5]); 
    getSIPR(tmp);
    printf("IP ADDRESS : %d.%d.%d.%d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getGAR(tmp);
    printf("GW ADDRESS : %d.%d.%d.%d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getSUBR(tmp);
    printf("SN MASK: %d.%d.%d.%d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
   
    /* Set Network Configuration */
    //wizchip_init(tx_size, rx_size);

    printf(" TEST- START \r\n");  
		
    while(1)
    {
        switch(getSn_SR(SOCK_NUM))
				{
					case SOCK_ESTABLISHED:
					if(getSn_IR(SOCK_NUM) & Sn_IR_CON)
					{
						getSn_DIPR(SOCK_NUM, destip);
						destport = getSn_DPORT(SOCK_NUM);
						printf("%d:Connected - %d.%d.%d.%d : %d\r\n",SOCK_NUM, destip[0], destip[1], destip[2], destip[3], destport);
						setSn_IR(SOCK_NUM,Sn_IR_CON);
					}
					if((size = getSn_RX_RSR(SOCK_NUM)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
					{
						if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
						ret = recv(SOCK_NUM, test_buf, size);

						if(ret <= 0) return ret;      // check SOCKERR_BUSY & SOCKERR_XXX. For showing the occurrence of SOCKERR_BUSY.
						
						 /* Send only data to SSP1 */ 
						for (TxIdx=0; TxIdx<size; TxIdx++)
						{
							SSP_SendData(SSP0, test_buf[TxIdx]);
							while( SSP_GetFlagStatus(SSP0, SSP_FLAG_BSY) );
						}
						
						/* Receive only data from SSP0 */
						while(SSP_GetFlagStatus(SSP1, SSP_FLAG_RNE))
						{
							SSP1_Buffer_Rx[RxIdx] = SSP_ReceiveData(SSP1);
							RxIdx++;
						} 
						RxIdx=0;
						
						sentsize = 0;

						while(size != sentsize)
						{
							ret = send(SOCK_NUM, SSP1_Buffer_Rx+sentsize, size-sentsize);
							if(ret < 0)
							{
								close(SOCK_NUM);
								return ret;
							}
							sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
						}
					}
						break;
					case SOCK_CLOSE_WAIT:
						printf("%d:CloseWait\r\n",SOCK_NUM);
						if((ret = disconnect(SOCK_NUM)) != SOCK_OK) return ret;
						printf("%d:Socket Closed\r\n", SOCK_NUM);

						break;
					case SOCK_INIT:
						printf("%d:Listen, TCP server loopback, port [%d]\r\n", SOCK_NUM, port);
						if( (ret = listen(SOCK_NUM)) != SOCK_OK) return ret;
						break;
					
					case SOCK_CLOSED:
						
						printf("%d:TCP server loopback start\r\n",SOCK_NUM);
						if((ret = socket(SOCK_NUM, Sn_MR_TCP, port, 0x00)) != SOCK_NUM) return ret;
						printf("%d:Socket opened\r\n",SOCK_NUM);
					
						break;
					
					default:
						break;
					
				}
    }

}
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main()
{
    //uint8_t tx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    //uint8_t rx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x11, 0x22, 0x34};
    uint8_t src_addr[4] = {192, 168,  0,  80};
    uint8_t gw_addr[4]  = {192, 168,  0,  1};
    uint8_t sub_addr[4] = {255, 255, 255,  0};		
    //uint8_t dns_server[4] = {8, 8, 8, 8};           // for Example domain name server
    uint8_t tmp[8];
#if LOOPBACK_MODE == LOOPBACK_MAIN_NOBLOCK
    int ret;
    uint8_t sn;
#if defined(TEST_TCPC)
    int32_t loopback_ret;
    struct sockaddr_in sa;
    uint32_t s_addr;
#endif
#endif

    // For TCP client loopback examples; destination network info
    //uint8_t destip[4] = {192, 168, 0, 2};
    //uint16_t destport = 5000;
    //int32_t loopback_ret;

    /* External Clock */
    CRG_PLL_InputFrequencySelect(CRG_OCLK);

    /* Set Systme init */
    SystemInit();

    /* UART Init */
    UART_StructInit(&UART_InitStructure);
    UART_Init(UART1,&UART_InitStructure);

    /* SysTick_Config */
    SysTick_Config((GetSystemClock()/1000));

    /* Set WZ_100US Register */
    setTIC100US((GetSystemClock()/10000));
    //getTIC100US();	
    //printf(" GetSystemClock: %X, getTIC100US: %X, (%X) \r\n", 
    //      GetSystemClock, getTIC100US(), *(uint32_t *)TIC100US);        

#ifdef _MAIN_DEBUG_
	uint8_t tmpstr[6] = {0,};

	ctlwizchip(CW_GET_ID,(void*)tmpstr);
    printf("\r\n============================================\r\n");
	printf(" WIZnet %s EVB Demo v%d.%.2d\r\n", tmpstr, VER_H, VER_L);
	printf("============================================\r\n");
	printf(" WIZwiki Platform based Loopback Example\r\n");
	printf("============================================\r\n");
#endif

#ifdef __DEF_USED_IC101AG__ //For using IC+101AG
    *(volatile uint32_t *)(0x41003068) = 0x64; //TXD0 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x4100306C) = 0x64; //TXD1 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003070) = 0x64; //TXD2 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003074) = 0x64; //TXD3 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003050) = 0x64; //TXE  - set PAD strengh and pull-up
#endif

#ifdef __DEF_USED_MDIO__ 
    /* mdio Init */
    mdio_init(GPIOB, MDC, MDIO );
    /* PHY Link Check via gpio mdio */
    while( link() == 0x0 )
    {
        printf(".");  
        delay(500);
    }
    printf("PHY is linked. \r\n");  
#else
    delay(1000);
    delay(1000);
#endif

    /* Network Configuration */
    setSHAR(mac_addr);
    setSIPR(src_addr);
    setGAR(gw_addr);
    setSUBR(sub_addr);

    getSHAR(tmp);
    printf("MAC ADDRESS : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\r\n",tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5]);
    getSIPR(tmp);
    printf("IP ADDRESS : %.3d.%.3d.%.3d.%.3d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getGAR(tmp);
    printf("GW ADDRESS : %.3d.%.3d.%.3d.%.3d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getSUBR(tmp);
    printf("SN MASK: %.3d.%.3d.%.3d.%.3d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 

    /* Set Network Configuration */
    //wizchip_init(tx_size, rx_size);

#if LOOPBACK_MODE == LOOPBACK_MAIN_NOBLOCK
#if defined(TEST_TCPS) || defined(TEST_TCPC)
	ret = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#elif defined(TEST_UDPS)
    ret = socket(AF_INET, SOCK_STREAM, IPPROTO_UDP);
#endif
#if defined(TEST_TCPC)
    memset(&sa, 0, sizeof(sa));
    sa.sin_len = (uint16_t)sizeof(sa);
    sa.sin_family = AF_INET;
    sa.sin_port = htons(destport);
    s_addr = (((((destip[0] << 8) | destip[1]) << 8) | destip[2]) << 8) | destip[3];
    sa.sin_addr.s_addr = htonl(s_addr);
#endif

    if(ret == -1)
    {
#ifdef _LOOPBACK_DEBUG_
        printf("%d:Socket Error\r\n", ret);
#endif
        return ret;
    }
    sn = ret;
#endif

    while(1)
    {
		/* Loopback Test: TCP Server and UDP */
#if LOOPBACK_MODE == LOOPBACK_MAIN_NOBLOCK
#if defined(TEST_TCPS)
			loopback_tcps_bsd(sn, gDATABUF, TEST_PORT);
#elif defined(TEST_UDPS)
			loopback_udps_bsd(sn, gDATABUF, TEST_PORT);
#elif defined(TEST_TCPC)
			loopback_ret = loopback_tcpc_bsd(sn, gDATABUF, (struct sockaddr*)&sa);
			if(loopback_ret < 0) printf("loopback ret: %ld\r\n", loopback_ret); // TCP Socket Error code
#endif
#elif LOOPBACK_MODE == LOOPBACK_MAIN_SAMPLE
#if defined(TEST_TCPS)
			loopback_tcps_bsd(test_buf);
#elif defined(TEST_TCPC)
			loopback_tcpc_bsd(test_buf);
#endif
#endif
    }

}
int main(void)
{
//LOCALS
	unsigned int temp;
	unsigned int channel1, channel2;
	M1_stepPeriod = M2_stepPeriod = M3_stepPeriod = M4_stepPeriod = 50; // in tens of u-seconds
	unsigned char M1_state = 0, M2_state = 0, M3_state = 0, M4_state = 0;

	SYSTEMConfig(GetSystemClock(), SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

/* TIMER1 - now configured to interrupt at 10 khz (every 100us) */
	OpenTimer1(T1_ON | T1_SOURCE_INT | T1_PS_1_1, T1_TICK);
	ConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_2);
/* TIMER2 - 100 khz interrupt for distance measure*/
	OpenTimer2(T2_ON | T2_SOURCE_INT | T2_PS_1_1, T2_TICK);
	ConfigIntTimer2(T2_INT_ON | T2_INT_PRIOR_3); //It is off until trigger

/* PORTA b2 and b3 for servo-PWM */
	mPORTAClearBits(BIT_2 | BIT_3);
	mPORTASetPinsDigitalOut(BIT_2 | BIT_3);

/* ULTRASONICS: some bits of PORTB for ultrasonic sensors */
	PORTResetPins(IOPORT_B, BIT_8 | BIT_9| BIT_10 | BIT_11 );	
	PORTSetPinsDigitalOut(IOPORT_B, BIT_8 | BIT_9| BIT_10 | BIT_11); //trigger
/* Input Capture pins for echo signals */
	//interrupt on every risging/falling edge starting with a rising edge
	PORTSetPinsDigitalIn(IOPORT_D, BIT_8| BIT_9| BIT_10| BIT_11); //INC1, INC2, INC3, INC4 Pin
	mIC1ClearIntFlag();
	OpenCapture1(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//front
	ConfigIntCapture1(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);
	OpenCapture2(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//back
	ConfigIntCapture2(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);
	OpenCapture3(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//left
	ConfigIntCapture3(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);
	OpenCapture4(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//right
	ConfigIntCapture4(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);

/* PINS used for the START (RD13) BUTTON */
    PORTSetPinsDigitalIn(IOPORT_D, BIT_13);
	#define CONFIG          (CN_ON | CN_IDLE_CON)
	#define INTERRUPT       (CHANGE_INT_ON | CHANGE_INT_PRI_2)
	mCNOpen(CONFIG, CN19_ENABLE, CN19_PULLUP_ENABLE);
	temp = mPORTDRead();

/* PORT D and E for motors */
	//motor 1
	mPORTDSetBits(BIT_4 | BIT_5 | BIT_6 | BIT_7); 		// Turn on PORTD on startup.
	mPORTDSetPinsDigitalOut(BIT_4 | BIT_5 | BIT_6 | BIT_7);	// Make PORTD output.
	//motor 2
	mPORTCSetBits(BIT_1 | BIT_2 | BIT_3 | BIT_4); 		// Turn on PORTC on startup.
	mPORTCSetPinsDigitalOut(BIT_1 | BIT_2 | BIT_3 | BIT_4);	// Make PORTC output.
	//motor 3 and 4
	mPORTESetBits(BIT_0 | BIT_1 | BIT_2 | BIT_3 |
					BIT_4 | BIT_5 | BIT_6 | BIT_7); 		// Turn on PORTE on startup.
	mPORTESetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2 | BIT_3 |
					BIT_4 | BIT_5 | BIT_6 | BIT_7);	// Make PORTE output.

// UART2 to connect to the PC.
	// This initialization assumes 36MHz Fpb clock. If it changes,
	// you will have to modify baud rate initializer.
    UARTConfigure(UART2, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART2, GetPeripheralClock(), BAUD);
    UARTEnable(UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));
	// Configure UART2 RX Interrupt
	INTEnable(INT_SOURCE_UART_RX(UART2), INT_ENABLED);
    INTSetVectorPriority(INT_VECTOR_UART(UART2), INT_PRIORITY_LEVEL_2);
    INTSetVectorSubPriority(INT_VECTOR_UART(UART2), INT_SUB_PRIORITY_LEVEL_0);


/* PORTD for LEDs - DEBUGGING */
	mPORTDClearBits(BIT_0 | BIT_1 | BIT_2);
	mPORTDSetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2);

	

// Congifure Change/Notice Interrupt Flag
	ConfigIntCN(INTERRUPT);
// configure for multi-vectored mode
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
// enable interrupts
    INTEnableInterrupts();


	counterDistanceMeasure=600; //measure ULTRASONICS distance each 60 ms

	while (1) {
	
/***************** Robot MAIN state machine *****************/
		unsigned char ret = 0;
		switch (Robo_State) {
			case 0:
				MotorsON = 0;
				Robo_State = 0;

				InvInitialOrientation(RESET);
				TestDog(RESET);
				GoToRoom4short(RESET);
				BackToStart(RESET);
				InitialOrientation(RESET);
				GoToCenter(RESET);
				GoToRoom4long(RESET);
				break;
			case 1:
				ret = InvInitialOrientation(GO);
				if (ret == 1) {
					Robo_State = 2;
				}
				break;
			case 2:
				ret = TestDog(GO);
				if (ret == 1) {
					Robo_State = 3;		//DOG not found
				} else if (ret == 2) {
					Robo_State = 4;		//DOG found
				}
				break;
			case 3:
				ret = GoToRoom4short(GO);
				if (ret == 1) {
					Robo_State = 0;
				}
				break;
			case 4:
				ret = BackToStart(GO);
				if (ret == 1) {
					Robo_State = 5;
				}
				break;
			case 5:
				ret = GoToCenter(GO);
				if (ret == 1) {
					Robo_State = 6;
				}
				break;
			case 6:
				ret = GoToRoom4long(GO);
				if (ret == 1) {
					Robo_State = 0;
				}
				break;
		}

		if (frontDistance < 30 || backDistance < 30 || leftDistance < 30 || rightDistance < 30)
			mPORTDSetBits(BIT_0);
		else 
			mPORTDClearBits(BIT_0);
/***************************************************************/


/***************** Motors State Machine ************************/

		if (MotorsON) {
			/****************************
			MOTOR MAP
				M1 O-------------O M2   ON EVEN MOTORS, STEPS MUST BE INVERTED
					|	 /\		|			i.e. FORWARD IS BACKWARD
					|	/  \	|
					|	 || 	|
					|	 ||		|
				M3 O-------------O M4
			*****************************/
			if (M1_counter == 0) {
				switch (M1_state) {
					case 0: // set 0011
						step (0x3 , 1);
						if (M1forward)
							M1_state = 1;
						else
							M1_state = 3;
						break;
					case 1: // set 1001
						step (0x9 , 1);
						if (M1forward)
							M1_state = 2;
						else
							M1_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 1);
						if (M1forward)
							M1_state = 3;
						else
							M1_state = 1;
						break;
					case 3: // set 0110
					default:
						step (0x6 , 1);
						if (M1forward)
							M1_state = 0;
						else
							M1_state = 2;
						break;	
				}
				M1_counter = M1_stepPeriod;
				step_counter[0]--;
				if (directionNow == countingDirection)
					step_counter[1]--;
			}
			
			if (M2_counter == 0) {
				switch (M2_state) {
					case 0: // set 0011
						step (0x3 , 2);
						if (M2forward)
							M2_state = 1;
						else
							M2_state = 3;
						break;
					case 1: // set 0110
						step (0x6 , 2);
						if (M2forward)
							M2_state = 2;
						else
							M2_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 2);
						if (M2forward)
							M2_state = 3;
						else
							M2_state = 1;
						break;
					case 3: // set 1001
					default:
						step (0x9 , 2);
						if (M2forward)
							M2_state = 0;
						else
							M2_state = 2;
						break;	
				}
				M2_counter = M2_stepPeriod;
			}

			if (M3_counter == 0) {
				switch (M3_state) {
					case 0: // set 0011
						step (0x3 , 3);
						if (M3forward)
							M3_state = 1;
						else
							M3_state = 3;
						break;
					case 1: // set 1001
						step (0x9 , 3);
						if (M3forward)
							M3_state = 2;
						else
							M3_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 3);
						if (M3forward)
							M3_state = 3;
						else
							M3_state = 1;
						break;
					case 3: // set 0110
					default:
						step (0x6 , 3);
						if (M3forward)
							M3_state = 0;
						else
							M3_state = 2;
						break;	
				}
				M3_counter = M3_stepPeriod;
			}
			
			if (M4_counter == 0) {
				switch (M4_state) {
					case 0: // set 0011
						step (0x3 , 4);
						if (M4forward)
							M4_state = 1;
						else
							M4_state = 3;
						break;
					case 1: // set 0110
						step (0x6 , 4);
						if (M4forward)
							M4_state = 2;
						else
							M4_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 4);
						if (M4forward)
							M4_state = 3;
						else
							M4_state = 1;
						break;
					case 3: // set 1001
					default:
						step (0x9 , 4);
						if (M4forward)
							M4_state = 0;
						else
							M4_state = 2;
						break;	
				}
				M4_counter = M4_stepPeriod;
			}
		} else {
			//motors off
			mPORTDSetBits(BIT_4 | BIT_5 | BIT_6 | BIT_7);
			mPORTCSetBits(BIT_1 | BIT_2 | BIT_3 | BIT_4);
			mPORTESetBits(BIT_0 | BIT_1 | BIT_2 | BIT_3 |
					BIT_4 | BIT_5 | BIT_6 | BIT_7);
		}
/************************************************************/
		

/******* TEST CODE, toggles the servos (from 90 deg. to -90 deg.) every 1 s. ********/
/*		if (auxcounter == 0) {
			
			servo1_angle = 0;

			if (servo2_angle == 90)
				servo2_angle = -90;
			else
				servo2_angle = 90;

			auxcounter = 20000;		// toggle angle every 2 s.
		}
*/

		servo1_angle = 0;
		servo2_angle = -90;
	/*
		if (frontDistance > 13 && frontDistance < 17) {
			servo2_angle = 90;
		}
		else
			servo2_angle = -90;
	*/
/*******************************************************************/


/****************** SERVO CONTROL ******************/
		/*
			Changing the global servoX_angle at any point in the code will 
			move the servo to the desired angle.
		*/
		servo1_counter = (servo1_angle + 90)*(18)/180 + 6; // between 600 and 2400 us
		if (servo1_period == 0) {
			mPORTASetBits(BIT_2);
			servo1_period = SERVOMAXPERIOD; 		/* 200 * 100us = 20000us period  */
		}

		servo2_counter = (servo2_angle + 90)*(18)/180 + 6; // between 600 and 2400 us
		if (servo2_period == 0) {
			mPORTASetBits(BIT_3);
			servo2_period = SERVOMAXPERIOD; 		/* 200 * 100us = 20000us period  */
		}
/*****************************************************/
	
	} /* end of while(1)  */
		
	return 0;
}
예제 #30
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


}