Exemplo n.º 1
0
void spi_init(void)
{

		//initialize ports
		TRISCbits.TRISC2 = 0;	//chip select output
		TRISCbits.TRISC3 = 0; //clock is output
		TRISCbits.TRISC4 = 1; //SDI is input
		TRISCbits.TRISC5 = 0; //SDI is output

		OpenSPI(SPI_FOSC_16,MODE_11,SMPEND);

		/*
		_asm
			// Set up the SPI Support
			movlw 0x00
			movwf   TRISC,0       //all Outputs
			movlw 0x06
			movwf   ADCON1,0      //so PORTC can be used
	
			// Set up the SPI Port
			movlw   0x10        //SCK is output (Master), SDI is input, 
			movwf   TRISC,0     //SDO is output, all others output
			movlw   0x00        //Mode 1,1 SPI, sample on rising edge
			movwf   SSPSTAT,0   
			movlw	0x31
			movwf	SSPCON1,0	//Mode 1,1 SPI Master Mode, 1/16 Tosc bit time, clock idles high
		_endasm
		*/



}
Exemplo n.º 2
0
// *------------------------------------------------------*
void vInitMemoryFM25L16(void){

	FM25L16_CS_TRIS=0;
	FM25L16_CS=1;
	OpenSPI(SPI_START_CFG_1, SPI_START_CFG_2);
	SPIBRG=39; // a 80 MHz -> 2MHz SPI
}
Exemplo n.º 3
0
/******************************************************************************
 * Function:        void InitTempSensor(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Initializes SPI interface & chip select line
 *
 * Note:            None
 *****************************************************************************/
void InitTempSensor(void)
{
    #if defined(PICDEM_FS_USB)
    cs_temp_sensor = 1;
    tris_cs_temp_sensor = OUTPUT_PIN;
    OpenSPI(SPI_FOSC_64, MODE_11, SMPMID);
    
    // Initialize readable values - default to room temperature
    temperature.Val = 0x0C87;       // 25 degree celsius
    UpdateCelsiusASCII();

	#elif defined(PIC18F87J50_PIM)
    temperature.Val = 0x0C87;       // 25 degree celsius
    UpdateCelsiusASCII();

	//Need to initialize I2C Module to prepare for communication with
	//TC74 temperature sensor on the HPC Explorer board.
	mInitI2CPins();				// See io_cfg.h
	SSP1STAT = 0xC0;			// Slew rate control disabled, SMBus
	SSP1CON1 = 0x08;			// I2C Master mode
	SSP1CON2 = 0x00;
	SSP1ADD = 0x7D;				// Just under 100kHz at 48MHz core frequency
	SSP1CON1bits.SSPEN = 1;		// Enable MSSP module	

	I2CStateVariable = 0;		// Initial state for I2C state machine

    #endif    
}//end InitTempSensor
void Open_nRF24L01_SPI (void)
{
	unsigned char result;

	SPI_CSN_TRIS = 0;
	SPI_CE_TRIS	= 0;
	SPI_IRQ_TRIS = 1;
	SPI_SO_TRIS = 0;
	SPI_SCK_TRIS = 0;
	
	SPI_CE = 1;
	SPI_CSN = 1;

	OpenSPI(SPI_FOSC_4, MODE_00, SMPMID); //open SPI1
	
	Delay1KTCYx(3);

	result = Test_SPI();
	if (result)
	{
		LED_ON
		while (1);				// se retornou 1 é porque tem falha comunicação c/ SPi
	}

	configure_Radio();

}//
//sets up the analog to digital converter
void ADC_Initialize(void)
{
	/////stole Krishna's code for setting up the ADC/////////
	/*these were in Krishna's code, but I'm not entirely certian what needs
		//to be a 1 and what needs to be a zero
    TRISA = 0x0F;
  	TRISB = 0x08;
  	TRISC = 0x80;
  	TRISD = 0x00;
  	TRISE = 0x00;//*/
	
	TRISA |= 0x0F;		//need to ensure that the references are set to inputs
	ADCON1 = 0x3B;  //ADCON1 to now accept external reference voltage
		
	OpenSPI(SPI_FOSC_64,MODE_00,SMPMID); // 
  	// Configure ADC - External
	OpenADC( ADC_FOSC_32      &     // OpenADC (ADC_"V3", 4, 5, 6)
    ADC_RIGHT_JUST   &     // Be sure I/O is config corectly - TRISA inc.
    ADC_12_TAD,
    ADC_CH0          &
	ADC_VREFPLUS_EXT	&
	ADC_VREFMINUS_EXT	&
    ADC_INT_OFF,  ADC_4ANA   );
	return;
}
Exemplo n.º 6
0
void initialize_pic(void)
{
    if(RCONbits.POR==0)  //*** delete if not needed, or prog does not run
        RCONbits.POR=1; //A Power-on Reset has not occurred p64
    
    //run internal oscillator at 8 MHz (INTOSC drives clock directly) p44
    OSCCON= OSCCON | 0b01110000; 
    while (OSCCONbits.OSTS == 0); // wait for oscillator to be ready p44
	
    ANCON1bits.PCFG12= 1;   // B0 is set as a digital input p353
	TRISCbits.TRISC3 = 0;	// SDO output
	TRISCbits.TRISC5 = 0;   // SCK output
	TRISCbits.TRISC2 = 0;	// CSN output
	TRISCbits.TRISC1 = 0;	// CE output
	TRISBbits.TRISB0 = 1;	// IRQ input
	CSN = 1;			    // CSN high
	SCK = 0;			    // SCK low
	CE	= 0;			    // CE low
	TRISCbits.TRISC0 = 0; 	// LED output
    
    
    OpenSPI(SPI_FOSC_16, MODE_00, SMPMID); //open SPI1
	OpenTimer0( TIMER_INT_OFF &
            	T0_16BIT &
            	T0_SOURCE_INT &
            	T0_PS_1_256 );
}
Exemplo n.º 7
0
// Configure SPI module in 16-bit master mode
void initMPUSPI_master16(uint16_t priPre, uint16_t secPre)
{
	uint16_t SPICON1Value;      // holds the information about SPI configuration
	uint16_t SPICON2Value;
	uint16_t SPISTATValue;      // holds the information about SPI Enable/Disable

	MPU_SS = 1;                 // deassert MPU SS
	MPU_SS_TRIS = 0;            // make MPU SS an output
	CloseSPI();                 // turn off SPI module
	ConfigIntSPI(SPI_INT_DIS & SPI_INT_PRI_6);

#if defined(__dsPIC33E__)
	SPICON1Value =
	    ENABLE_SDO_PIN & SPI_MODE16_ON & ENABLE_SCK_PIN &
	    SPI_SMP_OFF & SPI_CKE_OFF &
	    SLAVE_ENABLE_OFF &
	    CLK_POL_ACTIVE_LOW &
	    MASTER_ENABLE_ON &
	    secPre & priPre;
	SPICON2Value = FRAME_ENABLE_OFF & FRAME_SYNC_OUTPUT; // & FIFO_BUFFER_DISABLE;
	SPISTATValue = SPI_ENABLE & SPI_IDLE_CON & SPI_RX_OVFLOW_CLR & BUF_INT_SEL_5;
	// BUF_INT_SEL_5 == Interrupt when the last bit is shifted out of SPIxSR, and the transmit is complete
#else
	SPICON1Value =
	    ENABLE_SDO_PIN & SPI_MODE16_ON & ENABLE_SCK_PIN &
	    SPI_SMP_ON & SPI_CKE_OFF &
	    SLAVE_ENABLE_OFF &
	    CLK_POL_ACTIVE_LOW &
	    MASTER_ENABLE_ON &
	    secPre & priPre;
	SPICON2Value = FRAME_ENABLE_OFF & FRAME_SYNC_OUTPUT;
	SPISTATValue = SPI_ENABLE & SPI_IDLE_CON & SPI_RX_OVFLOW_CLR;
#endif

#ifdef __PIC32MX__
//	 * Example: OpenSPI1(SPI_MODE32_ON|SPI_SMP_ON|MASTER_ENABLE_ON|SEC_PRESCAL_1_1|PRI_PRESCAL_1_1, SPI_ENABLE);
	OpenSPI(SPICON1Value, SPISTATValue);
#else
	OpenSPI(SPICON1Value, SPICON2Value, SPISTATValue);
//	printf("SPI1STAT %04X, SPI1CON1 %04X, SPI1CON2 %04X\r\n", SPI1STAT, SPI1CON1, SPI1CON2);
#endif

	_SPIROV = 0;                // clear SPI receive overflow
	_SPIIF  = 0;                // clear any pending interrupts
	_SPIIP  = INT_PRI_MPUSPI;   // set interrupt priority
//	_SPIIE  = 1;                // turn on SPI interrupts
}
Exemplo n.º 8
0
// *------------------------------------------------------*
void vSST25Init(void){

	SST25_CS_TRIS=0;
	SST25_CS=1;
	OpenSPI(SPI_START_CFG_1, SPI_START_CFG_2);
	SPIBRG=0; // a 80 MHz -> 40MHz SPI
    vSST25ResetWriteProtection();
}
Exemplo n.º 9
0
// The init procedure is executed once when the REXLANG function block initializes.
long init(void)
{
    spi_bus_handle = OpenSPI(spi_dev); // open SPI device
    
		// SPI data modes:
		//	SPI_MODE0 = 0,  // CPOL = 0, CPHA = 0, Clock idle low, data is clocked in on rising edge, output data (change) on falling edge
		//	SPI_MODE1 = 1,  // CPOL = 0, CPHA = 1, Clock idle low, data is clocked in on falling edge, output data (change) on rising edge
		//	SPI_MODE2 = 2,  // CPOL = 1, CPHA = 0, Clock idle high, data is clocked in on falling edge, output data (change) on rising edge
		//	SPI_MODE3 = 3,  // CPOL = 1, CPHA = 1, Clock idle high, data is clocked in on rising, edge output data (change) on falling edge

    spi_bufTx[0] = 0; //SPI data mode (0-3 mode, | 4=CS_HIGH | 8=LSB_FIRST | 16=3WIRE | 32=LOOP | 64=NO_CS | 128=READY)
		spi_bufTx[1] = 8; //bits per word
		spi_bufTx[2] = 1000000; //clock frequency [Hz]
		SetOptions(spi_bus_handle, spi_bufTx);

    // Verification of SPI bus settings
		GetOptions(spi_bus_handle, spi_bufRx);
		Trace(0, spi_bufRx[0]);  //	SPI mode
		Trace(1, spi_bufRx[1]);  //	bits per word
		Trace(2, spi_bufRx[2]);  //	clock frequency
	
    // Addressing the device
    spi_opcode_write = 0x40; // ( 0 | 1 | 0 | 0 | A2 | A1 | A0 | R/W ), write=0
    spi_opcode_read  = 0x41; // ( 0 | 1 | 0 | 0 | A2 | A1 | A0 | R/W ), read=1

    // !!!!!!!!!!!!!
    // By default, IOCON.BANK=0, therefore see Table 1-6 in the datasheet for register mapping
    //
    // Table 1-5, which confusingly appears sooner in the datasheet, displays register addresses 
    // for IOCON.BANK=1, which are significantly different 
    // !!!!!!!!!!!!!
    
    //Setting PORTA to output
    spi_bufTx[0] = spi_opcode_write;
    spi_bufTx[1] = 0x00; //register no. (IODIRA) 
    spi_bufTx[2] = 0x00; //IODIRA data, bitmask, 0=output, 1=input
    spi_write_count = 3;
    spi_read_count = 0;
    spi_ret_fun = SPI(spi_bus_handle, 0, spi_bufTx, spi_write_count, spi_bufRx, spi_read_count);

    //Setting PORTB to input
    spi_bufTx[0] = spi_opcode_write;
    spi_bufTx[1] = 0x01; //register no. (IODIRB) 
    spi_bufTx[2] = 0xFF; //IODIRB data, bitmask, 0=output, 1=input
    spi_write_count = 3;
    spi_read_count = 0;
    spi_ret_fun = SPI(spi_bus_handle, 0, spi_bufTx, spi_write_count, spi_bufRx, spi_read_count);

    //Enabling pull-up resistors on PORTB
    spi_bufTx[0] = spi_opcode_write;
    spi_bufTx[1] = 0x0D; //register no. (GPPUB) 
    spi_bufTx[2] = 0xFF; //GPPUB data, bitmask, 0=no pull-up, 1=pull-up enabled
    spi_write_count = 3;
    spi_read_count = 0;
    spi_ret_fun = SPI(spi_bus_handle, 0, spi_bufTx, spi_write_count, spi_bufRx, spi_read_count);

    return 0;
}
Exemplo n.º 10
0
//There are two memory banks in the LCD, data/RAM and commands. This 
//function sets the DC pin high or low depending, and then sends
//the data byte
void LCDWrite(char data_or_command, char data) 
{
	_LCDData = data_or_command; //Tell the LCD that we are writing either to data or a command (data has this line high, command: low)
	//Send the data
	OpenSPI(SLV_SSOFF & SPI_FOSC_4, MODE_00, SMPEND);  //Ensure the SPI port is open
	_LCDSelect=0;
	WriteSPI(data);    //shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
	_LCDSelect=1;
	CloseSPI();
}
Exemplo n.º 11
0
/******************************************************************************
 * Function:        void InitTempSensor(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Initializes SPI interface & chip select line
 *
 * Note:            None
 *****************************************************************************/
void InitTempSensor(void)
{
    cs_temp_sensor = 1;
    tris_cs_temp_sensor = OUTPUT_PIN;
	OpenSPI(SPI_FOSC_64, MODE_11, SMPMID);
    
    // Initialize readable values - default to room temperature
    temperature._word = 0x0C87;       // 25 degree celsius
    UpdateCelsiusASCII();
    
}//end InitTempSensor
Exemplo n.º 12
0
/*--------------------------------------------------------\
| SPIInitM                                                 |
|     													   |
| Initializes the SPI module and it's required ports;      |
\---------------------------------------------------------*/
void SPIInitM(void)
{
    OpenSPI(SPI_FOSC_16, MODE_00, SMPMID);
    ADCON1 = 0x0F; //Switch all pins related to the ADC to digital I/O's
    TRISBbits.RB1 = 1; //Set the SlaveReady pins as an input;
    TRISBbits.RB2 = 1;
    TRISBbits.RB3 = 0; //Set the SlaveSelect pins as an output;
    TRISBbits.RB4 = 0;
    INTCON2bits.RBPU = 1;

}
Exemplo n.º 13
0
Arquivo: main.c Projeto: btcub/pic18f
void main()
{
  unsigned char c;
  unsigned char column;
  TRISA=0;
  TRISC=0;

LATCbits.LATC4=1;

//    PORTA=1;
//  PORTB=0xFF;
//  PORTC=0xFF;

    OSCCON=0b01100000; //Internal 4MHZ Oscillator
		ADCON1=0x7F;//Make all ports Digital 
		OpenUSART(USART_TX_INT_OFF &// Initialize USART, Transmit interrupt off
		                              USART_RX_INT_ON &// Receive interrupt ON
		                              USART_ASYNCH_MODE & // Use USART in asynchronous mode
		                              USART_EIGHT_BIT &// Eight bit data
		                              USART_CONT_RX &// Enable continous receiving
		                              USART_BRGH_LOW,// Do not use baud rate multiplication
		                              12);// For a baud rate of 9600 value of SPBRGH:SPBRG register pair
		INTCONbits.PEIE=1;// Enable peripheral interrupts
		INTCONbits.GIEH=1;// Enable all interrupts
//		putrsUSART ("\nPlease type a S to Start");
OpenSPI(SPI_FOSC_4,MODE_01,SMPMID);
  //      SSPCON |= SPI_FOSC_64;
     
  
 while(1) {
putrsUSART(0x1);
//      WriteSPI(0x01);
//UARTIntPutChar(0xa);
//    __delay_ms(500);
 
 //   __delay_ms(50);
 }
  
  

}
Exemplo n.º 14
0
void main()
{

  int test;
  unsigned char del;
  stCanFrame sample;
  unsigned char mpptDevice = 0x01;
  unsigned char deviceMC = 0x02;
  unsigned char mpptCanConfig[4];
  unsigned char mcCanConfig[4];

  unsigned short filterID = mcBaseAddress | motorTempMes  ;



  OpenUSART( USART_TX_INT_OFF &
  USART_RX_INT_OFF &
  USART_ASYNCH_MODE &
  USART_EIGHT_BIT &
  USART_CONT_RX &
  USART_BRGH_HIGH, 71);
  
   printf("\n\r Serial Open \n");

  OpenSPI( SPI_FOSC_16,   //Master clock 16mhz
  		MODE_00,                 
  		SMPEND);                  //Output data a end of buff

  



    selectNoDevice();

    setmppt(mpptCanConfig);

    test = mcp_init(mpptDevice, mpptCanConfig);		
	while ( test != 0)
	{
		printf("\rMPPT. Failer to init MCP 2515, reseting \n");
		test = mcp_init(mpptDevice, mpptCanConfig);
	}
	mcp2515_normal(mpptDevice);
	printf("\rMPPT. Pass init MCP 2515\n");

    delay();
       
    setmc(mcCanConfig);
    test = mcp_init(deviceMC,mcCanConfig);
    while(test !=0)
    {
		printf("\r MOTOR CONTROLLER.  Failer to init MCP 2515, reseting \n");
	    test = mcp_init(deviceMC,mcCanConfig);
    }
	mcp2515_normal(deviceMC);
	printf("\rMOTOR CONTROLLER. Pass init MCP 2515\n");
    delay();

	if (bit_is_set(0b10111111,6))
		printf("\r Error -simple bit shift fails \n");
	else	
		printf("\r simple bit operations work right \n");
		




		
    //Ending set up

    //starting main loop
	//------------------
    getMessagesThatLookLike(&(filterID), deviceMC);
	while(1)
	{	
    	mpptData myMpptData[4];
		mcData myMCData;
		stCanFrame sample;
		stCanFrame result;
		unsigned char counter = 0, temp;
		int pollCount = 10;
            
		
		//MPPT
        //---------------------
		//build the message prompts the MPPT data
		//The mppt address we want are. 
		// 0x711 , 0x713, 0x715, 0x717
		sample.id =   MPPTRequestID;
		sample.length = 0;
		sample.rtr =0;
		while(counter < 4)
		{
			sample.id =   MPPTRequestID + 1 + (counter * 2);
			if(g_debug) printf("\r the id is %x\n",MPPTRequestID + 1 + (counter * 2));
			mcp2515_send_message(&sample, 0x02,mpptDevice);		
			Delay10TCYx(0x30);
			result.id = 0;
			mcp2515_get_message(&result ,mpptDevice);			
	
			while(!(result.id == MPPTAnswerID + 1 + (counter * 2)) && pollCount ) //while we do not have the matching id, and the time has not expired keep waiting for the message
			{
		 		mcp2515_get_message(&result, mpptDevice);
		    	Delay10TCYx(0x30);
		 		pollCount--;
	
		 	}
			if(pollCount) 
			{
				parsMppt((result.data),myMpptData[counter]);
			    if(g_messageDebug) 
			    {
				    printf("\rMessage from the MPPT \n");
				    printCanMessage(result);
		 	    }

			}
			else
			{
				if(g_debug) printf("\r mppt TimeOUT \n");
			}
	
			

			counter++;
		}
		

		pollCount = 10;
        //MOTOR Controller
        //-------------------------------
        

   		Delay10TCYx(0x30);
		result.id = 0;
	   	mcp2515_get_message(&result ,deviceMC);
		while( !(result.id == 0x040b) && pollCount)
	   	{
			mcp2515_get_message(&result ,deviceMC)	;
		}
		if (result.id = 0x040b)
	 	{
		    int cool = convertToInt(result.data + 4 , 100 );
		    printf("\rThe temp is %i\n",cool);
		    printCanMessage(result);
			parsMC((result.data), result.id, myMCData);
		}
		else
		{
			printf("\r MC TimeOUT \n");
		}
				
		
	}
} 
Exemplo n.º 15
0
void InitSPI(void){
    OpenSPI(SPI_FOSC_64, MODE_00, SMPMID);
}
Exemplo n.º 16
0
void initSpi(void){
     CloseSPI();	//close if was on
    OpenSPI(SPI_FOSC_64,MODE_01,SMPMID);
   // WriteSPI()

}
Exemplo n.º 17
0
/**
 * Configure SPI in PIC18 as master
 *
 * clock = FOSC_64
 * Mode (0,1)
 * Input data sampled at middle of data out
 */
void spiConfigureMaster(void)
{
    CloseSPI();
    OpenSPI(SPI_FOSC_64,MODE_01,SMPMID);
}
Exemplo n.º 18
0
void main (void)
{
 unsigned int pll_startup_counter = 1600;
	//Init ports
	//1=in, 0=output
	unsigned char adc_nr=0;	

     OSCTUNEbits.PLLEN = 1;  //Enable the PLL and wait 2+ms until the PLL locks before enabling USB module
      while(pll_startup_counter--);

	TRISA	= 0b0;	// all out
	TRISB	= 0b00100000;	// 
	TRISC	= 0b0;   // 
	
//	RPINR6 = 0;

	OpenTimer0  (TIMER_INT_ON & T0_SOURCE_INT & T0_16BIT & T0_PS_1_1);
	WriteTimer0 (TIMER_START_SEC);
	INTCONbits.GIE = 1;

	LED = 1;

	CS_1 = 1;
	CS_2 = 1;
	CS_3 = 1;
	CS_4 = 1;
	CS_5 = 1;
	CS_6 = 1;
	CS_7 = 1;
	CS_8 = 1;
	CS_9 = 1;

	CS_1 = 0;
	CS_2 = 0;
	CS_3 = 0;
	CS_4 = 0;
	CS_5 = 0;
	CS_6 = 0;
	CS_7 = 0;
	CS_8 = 0;
	CS_9 = 0;


	OpenSPI(SPI_FOSC_16, MODE_00, SMPMID);

	while(adc_nr < 4){

		spi_transfer(adc_nr, 0xFFFF);
		spi_transfer(adc_nr, ( WRITE_REG | (0<<10) ));
//		spi_transfer(adc_nr, AUTOMATIC_SEQUENCE);
//		spi_transfer(adc_nr, AUTOMATIC_SEQUENCE);

		adc_nr++;
	}
	adc_nr=0;

	USB_Out_Buffer[0]=59;
	USB_Out_Buffer[1]=1;
	USB_Out_Buffer[2]=0;
	USB_Out_Buffer[3]=0;
	USB_Out_Buffer[4]=0;
	USB_Out_Buffer[5]=0;

	 USBDeviceInit();	


	while(1){
	//mainloop
		   USBDeviceTasks(); 
			if(transmit){

				ProcessIO();

				transmit =1;
			}		
	}

}
Exemplo n.º 19
0
void QfSpi_Init(void) {
    /*
//  Sanity check SPI0 state.
Assert( Spi0State == Uninitialized );


SetBit( UCTL0, SWRST );          //  Hold the USART in Reset while configuring

ClearBit( IE1, URXIE0 );         //  Disable SPI0 Receive Interrupts

U0ME  |= UTXE0 + URXE0;          //  Enable USART0 transmit and receive modules

P3SEL |= 0x0E;                   //  Select the SPI option for USART0 pins (P3.1-3)

UCTL0 |= CHAR +                  //  Character length is 8 bits
         SYNC +                  //  Synchronous Mode (as opposed to UART)
         MM;                     //  8-bit SPI Master **SWRST**

UTCTL0 |= CKPH  +                //  UCLK delayed by 1/2 cycle
          SSEL1 + SSEL0 +        //  Clock source is SMCLK (implies Master mode)
                                 //         00 UCLKI               10 SMCLK
                                 //         01 ACLK  (fastest)     11 SMCLK
          STC;                   //  3-pin SPI mode (STE disabled)

URCTL0 = 0;                      //  Receive control register

UMCTL0 = SPI0_MODULATION_CONTROL;  //  No modulation
UBR10  = GetHiByte( SPI0_BAUD_DIVISOR );   //  Set baud rate
UBR00  = GetLoByte( SPI0_BAUD_DIVISOR );


URCTL0 = 0;                      //  Init receiver contol register


ME1  |= UTXE0 + URXE0;           //  Enable USART0 SPI transmit and receive.   (note that
                                 //  URXE0 and USPIE0 are one in the same on the '449)

ClearBit( UCTL0, SWRST );        //  Release USART state machine (begin operation).
                                 //  Doesn't do anything in SPI mode until a write
                                 //  to TXBUF0 occurs.
     */
    PIE1bits.SSPIE = 0;
    IPR1bits.SSPIP = 0; //spi interrupt low priority

    set_LIV_function(&Spi0ReadIsr);

    TRISCbits.TRISC3 = 0; //sck output
    TRISCbits.TRISC5 = 0; //sdo output
    //TRISAbits.TRISA5 = 1;	//ss input

    QfPlat_DeactivateQF4A512ChipSelect();
    OpenSPI(SPI_FOSC_16, MODE_00, SMPEND);

    Spi0State = Idle;

    //YEB
#ifndef __YEB_INTERRUPT__
#ifndef __YEB_IMMEDIATE__
    rememberHandle = registerTask(&rememberCallback, 0, (unsigned short) 0, -1);
    pauseTask(rememberHandle);
#endif
#endif
}
Exemplo n.º 20
0
/*--------------------------------------------------------\
| RestartSPI                                               |
|     													   |
| Restarts, and effectively resets, the SPI module.        |
\---------------------------------------------------------*/
void RestartSPI(void)
{
    CloseSPI();
    OpenSPI(SPI_FOSC_16, MODE_00, SMPMID);
}
Exemplo n.º 21
0
Arquivo: BusMon.c Projeto: GBert/misc
void UserInit(void) {
    byte i;

#if defined(USE_USB_BUS_SENSE_IO)
    tris_usb_bus_sense = INPUT_PIN; // See io_cfg.h
#endif

#if defined(USE_SELF_POWER_SENSE_IO)
    tris_self_power = INPUT_PIN;
#endif


    CS_2515_HIGH(); //Drive high
    tris_CS = 0; //Output
    OpenSPI(SPI_FOSC_16, MODE_00, SMPMID);

    TRISBbits.TRISB0 = 1; //SDI
    TRISBbits.TRISB1 = 0; //SCK

    //-------------------------
    // initialize variables
    //-------------------------
    for (i = 0; i < BUF_SIZE; i++) // initialize input and output buffer to 0
    {
        inbuffer[i] = 0;
        outbuffer[i] = 0;
    }

    //Timer 0
    TMR0H = 0; //clear timer
    TMR0L = 0; //clear timer
    T0CONbits.PSA = 0; //Assign prescaler to Timer 0
    T0CONbits.T0PS2 = 1; //Setup prescaler
    T0CONbits.T0PS1 = 1; //Will time out every 51 us based on
    T0CONbits.T0PS0 = 1; //20 MHz Fosc
    T0CONbits.T0CS = 0; //Increment on instuction cycle

    INTCON2 = 0xFF; //INT2 on rising edge
    INTCON3bits.INT2IP = 0; //Low priority
    INTCON3bits.INT2IF = 0; //Clear flag
    INTCON3bits.INT2IE = 1; //Enable INT2 interrupt

    //Outputs for the LEDs
    ADCON1 = 0x0F; //Digital pins
    CMCON = 0x07; //Digital pins

    LED_25PCT_OFF();
    LED_50PCT_OFF();
    LED_75PCT_OFF();
    LED_100PCT_OFF();

    TRISBbits.TRISB6 = INPUT_PIN;
    TRISBbits.TRISB7 = INPUT_PIN;

    tris_LED_25PCT = OUTPUT_PIN;
    tris_LED_50PCT = OUTPUT_PIN;
    tris_LED_75PCT = OUTPUT_PIN;
    tris_LED_100PCT = OUTPUT_PIN;

    UserFlag.CANLoading = OFF;

    LED_RX_OFF();
    LED_TX_OFF();

    tris_LED_TX = OUTPUT_PIN;
    tris_LED_RX = OUTPUT_PIN;

    tris_SW_LOAD = INPUT_PIN;

    //RTS Pin Outputs
    RTS0_2515_HIGH();
    tris_RTS0_pin = OUTPUT_PIN;

    RTS1_2515_HIGH();
    tris_RTS1_pin = OUTPUT_PIN;

    RTS2_2515_HIGH();
    tris_RTS2_pin = OUTPUT_PIN;

    tris_CAN_RES = OUTPUT_PIN;
    CAN_RES_ON(); //JM
    //  CAN_RES_OFF();  //Disconnect the termination resistor by default

    UserFlag.MCP_RXBn = 0; //clear flag
    UserFlag.USBsend = 0; //clear flag
    UserFlag.USBQueue = 0; //Clear message queue

    //Need to set up MCP2515 before enabling interrupts
    CANInit(); // See BusMon.c & .h

    RCONbits.IPEN = 1;
    INTCONbits.PEIE = 1;
    INTCONbits.GIE = 1;
}//end UserInit
Exemplo n.º 22
0
void init7SegmentHardware(void) {
  OpenSPI(SPI_FOSC_4, MODE_11, SMPEND);
  _7SEG_CONTROL_TRIS = 0;
  _7SEG_CONTROL = 1;
}
Exemplo n.º 23
0
BYTE MDD_SDSPI_MediaInitialize(void)
{
    WORD timeout;
    BYTE       status = TRUE;
    MMC_RESPONSE    response; 
#if defined __C30__ || defined __C32__
    WORD spiconvalue = 0x0003;
#endif
    
    SD_CS = 1;               //Initialize Chip Select line
    
    //Media powers up in the open-drain mode and cannot handle a clock faster
    //than 400kHz. Initialize SPI port to slower than 400kHz
#if defined __C30__ || defined __C32__
#ifdef __PIC32MX__
	OpenSPI(SPI_START_CFG_1, SPI_START_CFG_2);
    SPIBRG = SPICalutateBRG(GetPeripheralClock(), 400000);
#else
    // Calculate the prescaler needed for the clock
    timeout = GetSystemClock() / 400000;
    // if timeout is less than 400k and greater than 100k use a 1:1 prescaler
    if (timeout == 0)
    {
        OpenSPIM (MASTER_ENABLE_ON | PRI_PRESCAL_1_1 | SEC_PRESCAL_1_1);
    }
    else
    {
        while (timeout != 0)
        {
            if (timeout > 8)
            {
                spiconvalue--;
                // round up
                if ((timeout % 4) != 0)
                    timeout += 4;
                timeout /= 4;
            }
            else
            {
                break;
            }
        }
        
        timeout--;
    
        OpenSPIM (MASTER_ENABLE_ON | spiconvalue | ((~(timeout << 2)) & 0x1C));
    }
#endif    


    // let the card power on and initialize
    Delayms(1);
    
    //Media requires 80 clock cycles to startup [8 clocks/BYTE * 10 us]
    for(timeout=0; timeout<10; timeout++)
        mSend8ClkCycles();

    SD_CS = 0;
    
    Delayms(1);
    
    // Send CMD0 to reset the media
    response = SendMMCCmd(GO_IDLE_STATE,0x0);
    
    if((response.r1._byte == MMC_BAD_RESPONSE) || ((response.r1._byte & 0xF7) != 0x01))
    {
        status = FALSE;      // we have not got anything back from the card
        SD_CS = 1;                               // deselect the devices

        return status;
    }

    // According to spec cmd1 must be repeated until the card is fully initialized
    timeout = 0xFFF;
    
    do
    {
        response = SendMMCCmd(SEND_OP_COND,0x0);
        timeout--;
    }while(response.r1._byte != 0x00 && timeout != 0);

    // see if it failed
    if(timeout == 0)
    {
        status = FALSE;      // we have not got anything back from the card
        
        SD_CS = 1;                               // deselect the devices
    }
    else      
    {

#else
    
    // let the card power on and initialize
    Delayms(1);
    
    #if (GetSystemClock() < 25600000)

        #if (GetSystemClock() < 1600000)
            OpenSPIM (SYNC_MODE_FAST, BUS_MODE, SMP_PHASE);
        #elif (GetSystemClock() < 6400000)
            OpenSPIM (SYNC_MODE_MED, BUS_MODE, SMP_PHASE);
        #else
            OpenSPIM (SYNC_MODE_SLOW, BUS_MODE, SMP_PHASE);
        #endif
        
        // let the card power on and initialize
        Delayms(1);
        
        //Media requires 80 clock cycles to startup [8 clocks/BYTE * 10 us]
        for(timeout=0; timeout<10; timeout++)
            mSend8ClkCycles();
    
        SD_CS = 0;
        
        Delayms(1);
        
        // Send CMD0 to reset the media
        response = SendMMCCmd(GO_IDLE_STATE,0x0);
        
        if((response.r1._byte == MMC_BAD_RESPONSE) || ((response.r1._byte & 0xF7) != 0x01))
        {
            status = FALSE;      // we have not got anything back from the card
            SD_CS = 1;                               // deselect the devices

            return status;
        }
    
        // According to spec cmd1 must be repeated until the card is fully initialized
        timeout = 0xFFF;
        
        do
        {
            response = SendMMCCmd(SEND_OP_COND,0x0);
            timeout--;
        }while(response.r1._byte != 0x00 && timeout != 0);

    #else

        // Make sure the SPI module doesn't control the bus
        SPICON1 = 0x00;

        //Media requires 80 clock cycles to startup [8 clocks/BYTE * 10 us]
        for(timeout=0; timeout<10; timeout++)
            WriteSPIManual(0xFF);
    
        SD_CS = 0;
        
        Delayms(1);
    
        // Send CMD0 to reset the media
        response = SendMMCCmdManual (GO_IDLE_STATE, 0x0);

        if ((response.r1._byte == MMC_BAD_RESPONSE) || ((response.r1._byte & 0xF7) != 0x01))
        {
            status = FALSE;     // we have not got anything back from the card
            SD_CS = 1;                              // deselect the devices

            return status;
        }

        // According to the spec cmd1 must be repeated until the card is fully initialized
        timeout = 0xFFF;
    
        do
        {
            response = SendMMCCmdManual (SEND_OP_COND, 0x0);
            timeout--;
        }while(response.r1._byte != 0x00 && timeout != 0);
    #endif    

    // see if it failed
    if (timeout == 0)
    {
        status = FALSE;     // we have not got anything back from the card
        SD_CS = 1;                              // deselect the devices
    }
    else
    {
#endif

        Delayms (2);

        #ifdef __PIC32MX__
            #if (GetSystemClock() <= 20000000)
                SPIBRG = SPICalutateBRG(GetPeripheralClock(), 10000);
            #else
                SPIBRG = SPICalutateBRG(GetPeripheralClock(), SPI_FREQUENCY);
            #endif
        #else
            OpenSPIM(SYNC_MODE_FAST);
        #endif

        // Turn off CRC7 if we can, might be an invalid cmd on some cards (CMD59)
        response = SendMMCCmd(CRC_ON_OFF,0x0);

        // Now set the block length to media sector size. It should be already
        response = SendMMCCmd(SET_BLOCKLEN,MEDIA_SECTOR_SIZE);
        
        for(timeout = 0xFF; timeout > 0 && MDD_SDSPI_SectorRead(0x0,NULL) != TRUE; timeout--)
        {;}

        // see if we had an issue
        if(timeout == 0)
        {
            status = FALSE;
            SD_CS = 1;                               // deselect the devices
        }
    }

    return(status);
}//end MediaInitialize