예제 #1
0
void MyCyclone_Init(void)
{
    // Configure Reset Pin = GPIO_2[10] = RD7
    mPORTDClearBits(RST_FPGA);
    mPORTDSetPinsDigitalOut(RST_FPGA);

    // Do a Reset
    mPORTDSetBits(RST_FPGA);
    mPORTDClearBits(RST_FPGA);

    // Do Interrupts Initialization
    // Set RD8/INT1 and RD9/INT2 as inputs
    mPORTDSetPinsDigitalIn(BIT_8 | BIT_9);
    // Clear corresponding bits in INTCON for falling edge trigger
    INTCONCLR = _INTCON_INT1EP_MASK | _INTCON_INT2EP_MASK;
    // Set up interrupt prioirty and sub-priority
    INTSetVectorPriority(INT_EXTERNAL_1_VECTOR, My_INT_EXTERNAL_1_PRIORITY);
    INTSetVectorSubPriority(INT_EXTERNAL_1_VECTOR, My_INT_EXTERNAL_1_SUB_PRIORITY);
    INTSetVectorPriority(INT_EXTERNAL_2_VECTOR, My_INT_EXTERNAL_2_PRIORITY);
    INTSetVectorSubPriority(INT_EXTERNAL_2_VECTOR, My_INT_EXTERNAL_2_SUB_PRIORITY);
    // Clear the interrupt flags
    INTClearFlag(INT_INT1);
    INTClearFlag(INT_INT2);
    // Enable INT1 & INT2
    INTEnable(INT_INT1, INT_ENABLED);
    INTEnable(INT_INT2, INT_ENABLED);
    // Enable KEY0 and KEY1 interrupts and IOs of the MyExpansionBoard_IO_v2
    MyCyclone_Write(CYCLONE_CONFIG,CYCLONE_ENABLE_INT_KEY0 | CYCLONE_ENABLE_INT_KEY1 | CYCLONE_ENABLE_IO_AB | CYCLONE_ENABLE_IO_CD);
}
예제 #2
0
파일: LCDTFT.c 프로젝트: AleSuky/SkP32v1.1
void vLCDTFTWriteData(UINT16 Data){
 
    mPORTGSetBits(LCD_PIN_RS);
    mPORTDClearBits(LCD_PIN_CS);  
    mPORTDClearBits(LCD_PIN_WR);  
    PMPMasterWrite(Data);
    mPORTDSetBits(LCD_PIN_WR);
    mPORTDSetBits(LCD_PIN_CS);
}
예제 #3
0
void lcdcmnd(unsigned char value)
{
	PORTE=value;
	delay(100);
 	mPORTDClearBits(BIT_5);   // RS=0 write
	mPORTDSetBits(BIT_4);
	delay(100);
	mPORTDClearBits(BIT_4);
	return;
}	
예제 #4
0
파일: LCDTFT.c 프로젝트: AleSuky/SkP32v1.1
UINT16 uiLCDTFTGetPointCurrent(void){
	UINT16 result;

	mPORTGSetBits(LCD_PIN_RS);		// RS = 1 .. Data
    mPORTDClearBits(LCD_PIN_CS); 	// CS = 0
	mPORTDClearBits(LCD_PIN_RD);
	Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();
	Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();Nop();
    result=PMDIN;
    mPORTDSetBits(LCD_PIN_RD);    
    mPORTDSetBits(LCD_PIN_CS);	// CS = 1
    
    return (result);
}
예제 #5
0
int main(void)
{
    long i;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 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..
    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);


    // Explorer16 LEDs are on lower 8-bits of PORTA and to use all LEDs, JTAG port must be disabled.
    mJTAGPortEnable(DEBUG_JTAGPORT_OFF);

    // Make all lower 8-bits of PORTA as output. Turn them off before changing
    // direction so that we don't have unexpected flashes
    mPORTDClearBits(BIT_2 | BIT_1 | BIT_0 );

    mPORTDSetPinsDigitalOut(BIT_2 | BIT_1 | BIT_0 );

    while (1) 
    {
        BlinkLeds();                            
        i = 1024*1024*30;
        while(i--);
    //                i = 1024*1024*1024;
    //    while(i--);
    }


}
void initLEDs()
{
    mPORTDClearBits(BIT_1); //yellow
    mPORTGClearBits(BIT_6); //green
    notifyOnCommandProcessed();
    notifyOffCommandProcessed();
}
예제 #7
0
void SSD1351::writeData(uint8_t c) {
  while(mIsPMPBusy());                // Wait for PMP to be free
//  digitalWrite(SSD1351_DC, 1);        // High -- data mode 
  mPORTCSetBits(OLED_DC);           // Hight -- command mode 

//  PMPMasterWrite( c );                // write character

  mPORTEWrite( (uint16_t)c );    // Setup data
  mPORTDClearBits(OLED_RW);      // RW# 0 (write mode)
  mPORTDSetBits(OLED_EN);      // EN 1 (enable)
  mPORTDClearBits(OLED_CS);      // CS active   
//  delay(1);
  mPORTDSetBits(OLED_CS);      // CS inactive  
  mPORTDClearBits(OLED_EN);      // EN 0 (disable) 

}
예제 #8
0
int main(void){
    mPORTBSetPinsAnalogIn(0xFFFF);             //Enable all analog
    mPORTDClearBits(BIT_0 |BIT_1 | BIT_8);
    mPORTDSetPinsDigitalOut(BIT_0 | BIT_1 | BIT_8);

    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);
    CloseADC10();
    SetChanADC10(INITCH);
    OpenADC10(CONFIG1, CONFIG2, CONFIG3, CFGPORT, CFGSCAN);
    ConfigIntADC10(CFGINT);
    EnableADC10();

    mPMPOpen(PMP_CONTROL, PMP_MODE, PMP_PORT, PMP_INT);
    mPMPEnable();

    //mPORTDClearBits(BIT_0 |BIT_1 | BIT_8);
    INTEnableSystemMultiVectoredInt();

    OpenTimer2(T2_ON | T2_PS_1_64, 256);
    ConfigIntTimer2(T2_INT_ON | T2_INT_PRIOR_5 | T2_INT_SUB_PRIOR_2);
    EnableIntT2;
    
    mPORTDToggleBits(BIT_0);

    while(1){
        //Blink so we know we're still running
        noteOn(67, 100);
        //delayMs(1000);
        mPORTDToggleBits(BIT_0);
        //noteOff(67);
        DelayMs(1000);
        //mPORTDToggleBits(BIT_0);
    }
    return 0;
}
void __ISR(_TIMER_2_VECTOR, ipl2) interruptForCheckingIRSignals(void)
{
    if (IFS0bits.T2IF)
    {
        if (!processIRCommand)
        {
            //IFS0bits.T2IF = 0;
            //printf("i\r\n");
            irDurationCounter10us++;

            BOOL status = IR_INPUT_READ;
            if (portD != status)
            {
                handlePortStatus(status);

                if (status)
                {
                    //mPORTBClearBits(BIT_12);
                    mPORTDClearBits(BIT_1);
                }
                else
                {
                    //mPORTBSetBits(BIT_12);
                    mPORTDSetBits(BIT_1);
                }

                portD = status;
            }
        }
        mT2ClearIntFlag();
    }
}
예제 #10
0
void InitLEDs(void)
{
  	// Config PORTD pins RD0, RD1 and RD2 as outputs, and clear
    // (MMc: These macros from "ports.h" are kinda useless, imho)
    //
	mPORTDSetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2); // Same as TRISDCLR = 0x0007
	mPORTDClearBits(BIT_0 | BIT_1 | BIT_2);         // Same as LATDCLR = 0x0007
}
예제 #11
0
void InitializeIO(void)
{
    //Initializing CSN and CE pins as output
    mPORTFSetPinsDigitalOut(BIT_0 | BIT_1);
    mPORTFClearBits(BIT_0 | BIT_1);
    //Initializing IRQ pin as input
    mPORTDSetPinsDigitalIn(BIT_13);
    mPORTDClearBits(BIT_13);
    //Setting CSN bit active
    LATFbits.LATF1 = 1;
    //Initializing LEDs
    mPORTDSetPinsDigitalOut(BIT_1 | BIT_2);
    mPORTDClearBits(BIT_1 | BIT_2);
    //Initializing MOSI/SDO1 and SCK as output
    mPORTDSetPinsDigitalOut(BIT_10);
    mPORTDSetPinsDigitalOut(BIT_0);
    //Initializing MISO/SDI1 as input
    mPORTCSetPinsDigitalIn(BIT_4);
}
예제 #12
0
void SendNotes(int note){
    mPORTDSetBits(BIT_8);
    if((txFlag & (1<<note))>>note){
        while(!mIsPMPSlaveBufferEmpty());
        mPMPSlaveWrite(note);
        while(!mIsPMPSlaveBufferEmpty());
        mPMPSlaveWrite(txBuff[note]);
        txFlag -= (1 << note);
    }
    mPORTDClearBits(BIT_8);
}
예제 #13
0
void lcddata(unsigned char value)
{
	PORTE=value;
	delay(250);
	//mPORTBSetBits(BIT_15); 
	mPORTDSetBits(BIT_5);//RS=1 write
	mPORTDSetBits(BIT_4);
	delay(100);
	mPORTDClearBits(BIT_4);
	return;
}
예제 #14
0
파일: gpio.c 프로젝트: ChakChel/Ix
/**
 * @fn      void gpioInit( void );
 * @brief   Configuration des GPIO
 */
void gpioInit( void ) {
    
    // Désactivation du JTAG pour accéder aux LEDs
    mJTAGPortEnable( DEBUG_JTAGPORT_OFF );

    // RD1 en sortie
    PORTSetPinsDigitalOut( IOPORT_D, BIT_1 );

    // Initialisation de RD1 au niveau bas
    mPORTDClearBits( BIT_1 );
}
예제 #15
0
파일: main.c 프로젝트: robopanda333/RTOS
/*-----------------------------------------------------------*/
static void prvSetupHardware(void)
{
    /* Setup the CPU clocks, and configure the interrupt controller. */
    SYSTEMConfigPerformance(configCPU_CLOCK_HZ);
    mOSCSetPBDIV(OSC_PB_DIV_2);
    INTEnableSystemMultiVectoredInt();

    /* LEDs off. */
    mPORTDClearBits(BIT_0 | BIT_1 | BIT_2);

    /* LEDs are outputs. */
    mPORTDSetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2);
}
예제 #16
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();
}
예제 #17
0
/*****************************************************************************
*	CONFIG_3909()
*
*	This function configures the MCP3909 to transmit data from its two
*	A/D converters to the PIC32 via the SPI port
*****************************************************************************/
void CONFIG_3909()
{
	
	DBPRINTF("CONFIG_3909...\n");

	// SPI mode code
	int code = 0xA4;
	
	// set CS high
	mPORTDSetBits(BIT_9);
	// set MCLR low 
	mPORTEClearBits(BIT_0);
	// delay
	DelayMs(5);
	// set MCLR high
	mPORTESetBits(BIT_0);
	// set CS low
	mPORTDClearBits(BIT_9);

	// feed SPI mode code to MCP3909
	SpiChnPutC(1, code);

	DelayMs(1000);

	SpiChnPutC(1, 0x12345678);
	
	int data;
	data = getcSPI1();
	char a = (char)data;
	char * c;
	c = &a;
	DBPUTC(c);

	data = getcSPI1();
	a = (char)data;
	c = &a;
	DBPUTC(c);
}
예제 #18
0
파일: led.c 프로젝트: Tpimp/elevatorpic32
void TURN_OFF_LED(short lednumber)
{
    switch(lednumber)
    {
    case 0:
    {}
    case 1:
    {}
    case 2:
    {
        mPORTDClearBits(1 << lednumber);
        break;
    }
    case 3:
    {}
    case 4:
    {
        mPORTBClearBits(1 << (lednumber+1));
    }
    default: {
        break;
    }
    }
}
void switchSTBOff()
{
    mPORTDClearBits(BIT_3);
}
int main(void)
{
	unsigned int temp;

	// 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..
	SYSTEMConfig(GetSystemClock(), SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

/*PORT CONFIGURATION for UART*/
	// Blinky LED for Uart activity
	//mPORTAClearBits(BIT_7);
	//mPORTASetPinsDigitalOut(BIT_7);

// PINS used for the buttons
    PORTSetPinsDigitalIn(IOPORT_B, BIT_2 | BIT_3 | BIT_4);
	#define CONFIG          (CN_ON | CN_IDLE_CON)
	#define INTERRUPT       (CHANGE_INT_ON | CHANGE_INT_PRI_2)
	mCNOpen(CONFIG, CN4_ENABLE | CN5_ENABLE | CN6_ENABLE,
			CN4_PULLUP_ENABLE | CN5_PULLUP_ENABLE | CN6_PULLUP_ENABLE);
	temp = mPORTBRead();

//Analog input
	CloseADC10();
	#define PARAM1 ADC_MODULE_ON | ADC_FORMAT_INTG32 | ADC_CLK_AUTO | ADC_AUTO_SAMPLING_ON
	#define PARAM2 ADC_VREF_AVDD_AVSS | ADC_SCAN_ON | ADC_SAMPLES_PER_INT_2 | ADC_BUF_16 | ADC_ALT_INPUT_OFF
	#define PARAM3 ADC_CONV_CLK_INTERNAL_RC | ADC_SAMPLE_TIME_5
	#define PARAM4	ENABLE_AN0_ANA | ENABLE_AN1_ANA
	#define PARAM5	SKIP_SCAN_AN2 | SKIP_SCAN_AN3 | SKIP_SCAN_AN4 | SKIP_SCAN_AN5 | SKIP_SCAN_AN6 | SKIP_SCAN_AN7 | SKIP_SCAN_AN8 | SKIP_SCAN_AN9 | SKIP_SCAN_AN10 | SKIP_SCAN_AN11 | SKIP_SCAN_AN12 | SKIP_SCAN_AN13 | SKIP_SCAN_AN14 | SKIP_SCAN_AN15
	SetChanADC10( ADC_CH0_NEG_SAMPLEA_NVREF | ADC_CH0_POS_SAMPLEA_AN0);
	OpenADC10( PARAM1, PARAM2, PARAM3, PARAM4, PARAM5 );
	EnableADC10();

//PORT D for motors
	mPORTDClearBits(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); 		// Turn off PORTD on startup.
	mPORTDSetPinsDigitalOut(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);	// Make PORTD output.


	// Explorer-16 uses 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(), DESIRED_BAUDRATE);
    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);


	// Congifure Change/Notice Interrupt Flag
	ConfigIntCN(INTERRUPT);

    // configure for multi-vectored mode
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);

    // enable interrupts
    INTEnableInterrupts();


	WriteString("*** UART Interrupt-driven Example ***\r\n");

	unsigned int channel1, channel2;
	unsigned int motor1Time, motor2Time;
	// Let interrupt handler do the work
	while (1) {
		
		while ( ! mAD1GetIntFlag() );

		channel1 = ReadADC10(0);
		channel2 = ReadADC10(1);
		motor1Time = (channel1*(60000)/(1023) + 80000);
		motor2Time = (channel2*(60000)/(1023) + 80000);
		//maximo valor de motorTime = 140000

		//use motor time for stepping delay		
		if (MotorsON) {
			if (M1forward) {
				adelante(1, motor1Time, 1);
			} else {
				atras(1, motor1Time, 1);
			}

			if (M2forward) {
				adelante(1, motor2Time, 3);
			} else {
				atras(1, motor2Time, 3);
			}

		}
	
			mAD1ClearIntFlag();
		}
			
		return 0;
}
void notifyOnCommandProcessed()
{
    stbActivationInProgress = FALSE;
    mPORTDClearBits(BIT_6);
}
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;
}
void notifyOffCommandProcessed()
{
    mPORTDClearBits(BIT_5);
}
예제 #24
0
파일: main.c 프로젝트: dtrejod/myece4532
int main() {
    // Initialize Sockets and IP address containers
    //
    SOCKET 	serverSock, clientSock = INVALID_SOCKET;
    IP_ADDR	curr_ip, ip;

    // Initialize buffer length variables
    //
    int rlen, sent, bytesSent;
    
    // Initialize the Send/Recv buffers
    //
    char rbfr[10];

    // Socket struct descriptor
    //
    struct sockaddr_in addr;
    int addrlen = sizeof(struct sockaddr_in);

    // System clock containers
    //
    unsigned int sys_clk, pb_clk;

    // Initialize LED Variables:
    // Setup the LEDs on the PIC32 board
    // RD0, RD1 and RD2 as outputs
    //
    mPORTDSetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2 ); 
    mPORTDClearBits(BIT_0 | BIT_1 | BIT_2); // Clear previous LED status.
    
    // Setup the switches on the PIC32 board as inputs
    //		
    mPORTDSetPinsDigitalIn(BIT_6 | BIT_7 | BIT_13);     // RD6, RD7, RD13 as inputs

    // Setup the system clock to use CPU frequency
    //
    sys_clk = GetSystemClock();
    pb_clk = SYSTEMConfigWaitStatesAndPB(sys_clk);

    // interrupts enabled
    INTEnableSystemMultiVectoredInt();

    // system clock enabled
    SystemTickInit(sys_clk, TICKS_PER_SECOND);

    // Initialize TCP/IP
    //
    TCPIPSetDefaultAddr(DEFAULT_IP_ADDR, DEFAULT_IP_MASK, DEFAULT_IP_GATEWAY,
            DEFAULT_MAC_ADDR);

    if (!TCPIPInit(sys_clk)) return -1;
    DHCPInit();

    // Port to bind socket to
    //
    addr.sin_port = 6653;
    addr.sin_addr.S_un.S_addr = IP_ADDR_ANY;

    // Initialize TCP server socket
    //
    if((serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == 
        SOCKET_ERROR)  return -1;
       
    // Ensure we bound to the socket. End Program if bind fails
    //
    if(bind(serverSock, (struct sockaddr*) &addr, addrlen ) == 
        SOCKET_ERROR)
        return -1;

    // Listen to up to five clients on server socket
    //
    listen(serverSock, 5);

    // We store our desired transfer paragraph 
    //
    char myStr[] = "TCP/IP (Transmission Control Protocol/Internet Protocol) is "
        "the basic  communication language or protocol of the Internet. "
        "It can also be used as a communications protocol in a private "
        "network (either an intranet or an extranet). When you are set up "
        "with direct access to the Internet, your computer is provided "
        "with a copy of the TCP/IP program just as every other computer "
        "that you may send messages to or get information from also has "
        "a copy of TCP/IP. TCP/IP is a two-layer program. The higher "
        "layer, Transmission Control Protocol, manages the assembling "
        "of a message or file into smaller packets that are transmitted "
        "over the Internet and received by a TCP layer that reassembles "
        "the packets into the original message. The lower layer, "
        "Internet Protocol, handles the address part of each packet so "
        "that it gets to the right destination. Each gateway computer on "
        "the network checks this address to see where to forward the "
        "message. Even though some packets from the same message are "
        "routed differently than others, they'll be reassembled at the "
        "destination.\0";
    
    // Chunk up our data
    //
    // Copy our string into our buffer
    //
    int tlen = strlen(myStr);
    
    char tbfr1[tlen1+1];

    // Loop forever
    //
    while(1) {
        // Refresh TCIP and DHCP
        //
        TCPIPProcess();
        DHCPTask();

        // Get the machines IP address and save to variable
        //
        ip.Val = TCPIPGetIPAddr();

        // DHCP server change IP address?
        //
        if(curr_ip.Val != ip.Val) curr_ip.Val = ip.Val;	

        // TCP Server Code
        //
        if(clientSock == INVALID_SOCKET) {
            // Start listening for incoming connections
            //
            clientSock = accept(serverSock, (struct sockaddr*) &addr, &addrlen);

            // Upon connection to a client blink LEDS.
            //
            if(clientSock != INVALID_SOCKET) {
                setsockopt(clientSock, SOL_SOCKET, TCP_NODELAY, 
                    (char*)&tlen, sizeof(int));
                mPORTDSetBits(BIT_0);   // LED1=1
                DelayMsec(50);
                mPORTDClearBits(BIT_0); // LED1=0
                mPORTDSetBits(BIT_1);   // LED2=1
                DelayMsec(50);
                mPORTDClearBits(BIT_1); // LED2=0
                mPORTDSetBits(BIT_2);   // LED3=1
                DelayMsec(50);
                mPORTDClearBits(BIT_2); // LED3=0
            }
        }
        else {
            // We are connected to a client already. We start
            // by receiving the message being sent by the client
            //
            rlen = recvfrom(clientSock, rbfr, sizeof(rbfr), 0, NULL, 
                NULL);

            // Check to see if socket is still alive
            //
            if(rlen > 0) {
                // If the received message first byte is '02' it signifies
                // a start of message
                //
                if (rbfr[0]==2) {
                    //mPORTDSetBits(BIT_0);	// LED1=1

                    // Check to see if message begins with
                    // '0271' to see if the message is a a global reset
                    //
                    if(rbfr[1]==71) {
                        mPORTDSetBits(BIT_0);   // LED1=1
                        DelayMsec(50);
                        mPORTDClearBits(BIT_0); // LED1=0
                    }
                }
                // If the received message starts with a second byte is
                // '84' it signifies a initiate transfer
                //
                if(rbfr[1]==84){
                    mPORTDSetBits(BIT_2);   // LED3=1
                    bytesSent = 0;
                    //sent = 0;
                    while (bytesSent < tlen){
                        memcpy(tbfr1, myStr+bytesSent, tlen1);
                        if (bytesSent > 1049){
                            tbfr1[tlen-bytesSent+1] = '\0';
                            send(clientSock, tbfr1, tlen-bytesSent+1, 0);
                        }
                        else{
                            tbfr1[tlen1] = '\0';
                            // Loop until we send the full message
                            //
                            send(clientSock, tbfr1, tlen1+1, 0);
                        }
                        bytesSent += tlen1;
                        DelayMsec(50);
                    }
                    mPORTDClearBits(BIT_2);	// LED3=0
                }
                mPORTDClearBits(BIT_0); // LED1=0
            }

            // The client has closed the socket so we close as well
            //
            else if(rlen < 0) {
                closesocket(clientSock);
                clientSock = SOCKET_ERROR;
            }
        }
    }
}
예제 #25
0
int main(void)
{
	DBINIT();
	DBPRINTF("MAIN.... \n");
   	unsigned int temp;
	int POWER;
	//bool RELAY;

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //STEP 1. Configure cache, wait states and peripheral bus clock
	SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // STEP 2. configure the port registers
    mPORTDSetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2 | BIT_9);
	mPORTESetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // STEP 3. initialize the port pin states = outputs low
    mPORTDClearBits(BIT_0 | BIT_1 | BIT_2);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // STEP 4. enable change notice, enable discrete pins and weak pullups
    mCNOpen(CONFIG, PINS, PULLUPS);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // STEP 5. read port(s) to clear mismatch on change notice pins
    temp = mPORTDRead();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // STEP 6. clear change notice interrupt flag
    ConfigIntCN(INTERRUPT);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // STEP 7. enable multi-vector interrupts
    INTEnableSystemMultiVectoredInt();

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// STEP 8. configure SPI port and MCP3909
	OpenSPI1(FRAME_ENABLE_ON | ENABLE_SDO_PIN | SPI_MODE32_ON | SPI_CKE_ON | SLAVE_ENABLE_OFF | CLK_POL_ACTIVE_LOW | MASTER_ENABLE_ON , SPI_ENABLE | SPI_FRZ_CONTINUE | SPI_IDLE_STOP | SPI_RX_OVFLOW_CLR);
	CONFIG_3909();

	DBPRINTF("CONFIGURED.... \n");


   while(1)
   {
		// Toggle LED's to signify code is looping
		mPORTDToggleBits(BIT_0);     // toggle LED1 (same as LATDINV = 0x0002)

		SAMPLE();

		POWER = MEASURE_POWER();

		DBPRINTF("power measured! \n");

		DelayMs(1000);

		/************************
		*ETHERNET COMMUNICATIONS*
		************************/

   };

}
예제 #26
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;
    }
}
예제 #27
0
 void ENABLE_CS(void)     
 {
    mPORTDClearBits(BIT_12);
	Delay(50000);  //50ns
 }