//__________________________________________________________________________________________________
void anibike_dl_master_initialize ( void )
{
	// Set pull-down and wired-or so that there will be no problems
	PORT_ConfigurePins( &DATALINK_PORT,
						DATALINK_CLK_PIN|DATALINK_DATA_PIN,
						false,
						false,
						PORT_OPC_TOTEM_gc,
						PORT_ISC_INPUT_DISABLE_gc );
	PORT_ConfigurePins( &DATALINK_PORT,
						DATALINK_CS_PIN,
						false,
						false,
						PORT_OPC_WIREDANDPULL_gc,
						PORT_ISC_INPUT_DISABLE_gc );
	
	DATALINK_PORT.DIRSET = DATALINK_CLK_PIN|DATALINK_DATA_PIN|DATALINK_CS_PIN;
	DATALINK_PORT.OUTSET = DATALINK_CS_PIN;
							
	/* Initialize SPI master on port DATAFLASH_PORT. */
	SPI_MasterInit(&spiMasterC,
	            &DATALINK_SPI,
	            &DATALINK_PORT,
	            false,
	            SPI_MODE_0_gc,
	            SPI_INTLVL_OFF_gc,
	            false,
	            SPI_PRESCALER_DIV4_gc,1);
					
	// drive cs to high
	DATALINK_PORT.OUTSET = DATALINK_CS_PIN;	
}
Exemplo n.º 2
0
int main(void)
{
	cli();
	CCP = 0xd8;
	CLKPR = 3; // 1/8 clock prescaler
	sei();

	// power saver - uart
	PRR &= ~(1 << PRUSART0);
	init_uart();

	//power saver - spi
	PRR &= ~(1 << PRSPI);
	SPI_MasterInit();

	struct bme280_t s1, s2;
	s1.dev_addr = 1;
	s2.dev_addr = 2;
	init_bme280(&s1);
	init_bme280(&s2);

	while(1)
	{
		measure(&s1);
		measure(&s2);
		transmit_string("----\r\n");
		_delay_ms(1000);
	}
}
Exemplo n.º 3
0
void cc2500_Init(uint8_t power)
{
    prog_uint8_t *init = cc2500InitValue;

    SET_BIT(PORTB, OUT_B_SPI_SCK);
    RES_BIT(PORTB, OUT_B_SPI_MOSI);
    RES_BIT(PORTB, OUT_B_SPI_SS);
    _delay_us(40);                    // warten 40us
    SPI_MasterInit();
    _delay_us(40);                    // warten 40us
    cc2500_Reset();
    cc2500_Off();                         // SS wegnehmen

    SPI_MasterTransmit(CC2500_IOCFG2 | CC2500_WRITE_BURST);
    do
    {
        SPI_MasterTransmit(pgm_read_byte(init++));
    }
    while(init < (cc2500InitValue + sizeof(cc2500InitValue) - 3));
    cc2500_Off();                    // SS wegnehmen wegen Burst
    SPI_MasterTransmit(CC2500_TEST2 | CC2500_WRITE_BURST);
    do
    {
        SPI_MasterTransmit(pgm_read_byte(init++));
    }
    while(init < (cc2500InitValue + sizeof(cc2500InitValue)));
    cc2500_Off();                    // SS wegnehmen wegen Burst
    cc2500setPatableMax(power);
}
int main(void)
{
    SPI_MasterInit();
    btInit();
    interruptINT1_init();
    sei();
    btTransmit(0);
    //moveRobot(ACTIVATE_HIT);
    while(1)
    {
        BT_SensorValues();
        getSensorValues();
        setVariables();

        dataValues[LIFE] = lifeCount;

        //Start of AI program that should keep the robot within the boundaries of the tape track
        moveRobot(LED | lifeCount);

        if(!lifeCount) {
            sensorControlDead();
            if(TapeFlag >= 0x03 && counting == 0) {
                counting = 1;
                timerValue = TIMER_1A_SECOND;
                timer_init();
            } else if(counting == 2) {
                while(1) {
                    moveRobot(STOP);
                }
            }


        } else {

            if(hit == 0) {
                activateHitFlag = 0;
                hitFlag = 1;
            }

            if (hit == 1 && activateHitFlag)
            {
                moveRobot(IR_ON);
                moveRobot(ACTIVATE_HIT);
            }

            else if(hit == 1 && hitFlag == 1) {
                hitFlag = 0;
                lifeCount = lifeCount >> 1;
                timer0_init();
            }

            else if (hit == 1 && !activateHitFlag) {
                moveRobot(IR_OFF);
            }


            if(!sprayPray) {
                idle();
            }
        }
Exemplo n.º 5
0
void NT7534_Init(){
    
    //nastaveni portu
    PIN_A0_DDR = 1;     //data
    PIN_RES_DDR = 1;    //reset
    NT7534_CS_DDR = 1;  //cs
    
    //init values 
    
    //reset
    RES = 0;
    delay_us(50);
    RES = 1;
    
    //CS deactive
    NT7534_CLEAR_CS;
    
    //init SPI
    SPI_MasterInit();  
    
    delay_us(50); 
        
    //init display    
    NT7534_Display_Init();  
    
    delay_us(50); 
    NT7534_clear_screen();
    delay_us(50); 
    knuerr_logo();        
}
Exemplo n.º 6
0
int main (void)
{
	TWI_init();					//TWI Bus Initialisieren
	TWI_59116_reset();
	TWI_59116_setup();
	
	if(CORE==Master){
		DDRA=0xff;				//PORTA als Ausgang
		DDRD|=(1<<2);			// PD2 als Ausgang
		Interrupt_init();
		sei();
		SPI_MasterInit();
		Ebene_ein=0;
		
		while(1)
		{
		
				
			effect_blinky2(1); //ok
			effect_planboing(0,AXIS_Z,20); //ok
			effect_planboing(1,AXIS_X,20); //ok
			effect_planboing(0,AXIS_Y,20); //ok
			effect_planboing(1,AXIS_Z,20); //ok
			for (uint8_t ii=0;ii<8;ii++)
				effect_box_shrink_grow (0,ii%4, ii & 4, 20); //ok
			//sendvoxels_rand_z(100,10,20); // ok
			effect_random_sparkle (1,3,20,10); //ok
			effect_box_woopwoop(1,40,1); //naja
			effect_rain(0,300); //ok
			//effect_wormsqueeze (2, AXIS_Z, 1, 100, 25); //ok
			for(int i=0;i<8;i++){			//	Pixel durchtesten
				for(int j=0;j<64;j++)
				{	LED[0][i][j/8][j%8]=0xff;
					_delay_us(500);
				}
				for(int j=0;j<64;j++)
				{	LED[0][i][j/8][j%8]=0;
					_delay_us(500);
				}
			}
		}
	
	}else{
		DDRA=0x00;				//PORTA als Eingang
		DDRD&=~(1<<2);			// PD2 als Eingang
		SPI_SlaveInit();
		Ebene_ein=0;
		while(1)
		{
			
			I2C_Leds_ein(Ebene_ein%8);		//Säulentreiber einschalten für nächste Ebene
							
		}
	}

	
return 0;
}
Exemplo n.º 7
0
void main(void)
{	
	SPI_MasterInit();
	
	ip_init();

	while (1){
		ip_task();
	}
}
Exemplo n.º 8
0
/** \brief Initializes the ADC.
 *
 * All library functions in this library take the adc given here as their first
 * parameter. This function initializes it for future communication with the
 * ADC.  This library uses the SPI library to communicate with the ADC, set up
 * in interrupt driven packet transfer mode, at 2MHz clock frequency. This
 * library performs bus arbitration through the SPI_driver.c library, however,
 * it is still a good idea to limit the ADC as the only peripheral on the bus
 * for performance reasons.
 *
 * \param[out] adc the adc to initialize
 * \param[in] control_port pointer to the control port for the ADC
 * \param[in] CONVST_bm /CONVST pin bit mask (on control_port)
 * \param[in] EOC_bm /EOC pin bit mask (on control_port)
 * \param[in] SPI_port pointer to the SPI port for the ADC
 * \param[in] SPI_module the SPI module to use
 * \param[in] RFS_bm /RFS pin bit mask (on SPI_port) */
void ADC_init(ADC_ext_t *adc,
              PORT_t *control_port, uint8_t CONVST_bm, uint8_t EOC_bm,
              PORT_t *SPI_port, SPI_t *SPI_module, uint8_t RFS_bm) {

   /* initialize the adc */
   adc->control_port = control_port;
   adc->CONVST_bm = CONVST_bm;
   adc->SPI_port = SPI_port;
   adc->RFS_bm = RFS_bm;
   adc->SPI_master = malloc(sizeof(SPI_Master_t));
   adc->data_packet = malloc(sizeof(SPI_DataPacket_t));
   adc->ready = true;
   adc->continuous = false;
   adc->callback = NULL;

   /* enable /CONVST pin as output */
   control_port->DIRSET = CONVST_bm;
   PORTCFG.MPCMASK = CONVST_bm;
   control_port->PIN0CTRL = PORT_OPC_TOTEM_gc;
   control_port->OUTSET = CONVST_bm;
   control_port->OUTCLR = CONVST_bm;
   control_port->OUTSET = CONVST_bm;

   /* Init /RFS pin as output with push/pull configuration */
   SPI_port->DIRSET = RFS_bm;
   PORTCFG.MPCMASK = RFS_bm;
   SPI_port->PIN0CTRL = PORT_OPC_TOTEM_gc;
   SPI_port->OUTSET = RFS_bm;
   SPI_port->OUTCLR = RFS_bm;
   SPI_port->OUTSET = RFS_bm;


   /* Initialize SPI master on port C, which also sets up SPI interrupt */
   SPI_MasterInit(adc->SPI_master,         // SPI_master_t struct to use
                  SPI_module,              // SPI module to use (see board.h)
                  SPI_port,                // SPI port to use (see board.h)
                  false,                   // lsb_first = false
                  SPI_MODE_2_gc,           // data on leading falling edge
                  SPI_INTLVL_MED_gc,       // SPI interrupt priority
                  false,                   // clock2x = false
                  SPI_PRESCALER_DIV64_gc); // division scaler (2MHz)

   /* enable interrupts on /EOC for falling edge
    * (ADC pulls low to signal conversion ready) */
   control_port->DIRCLR = EOC_bm;                  // EOC pin is input
   PORTCFG.MPCMASK = EOC_bm;
   control_port->PIN0CTRL = PORT_ISC_FALLING_gc; // pulled low when ready
   control_port->INT0MASK |= EOC_bm;             // enable EOC interupt mask
   control_port->INTCTRL = PORT_INT0LVL_LO_gc;   // enable LO level interrupts

   /* enable low and med level interrupts */
   PMIC.CTRL |= PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm;

}
Exemplo n.º 9
0
int main ()
{
	/* Configure port D pin 0 as output
	 * for signaling when tests pass
	 */
	DDR_SIGNAL = (1<<DD_SIGNAL);
	uint8_t i, byte_received;
	SPI_MasterInit();
	for (i=0; i<100; i++)
	{
		SPI_MasterTransmit(0x81);
		_delay_ms(5);
	
		/* is SPI interrupt flag set? */
		if (SPSR == 0x80)
		{
			/* if SPI interrupt flag is set
			 * clear it by reading the data
			 * in SPI data register */
			byte_received = SPI_ReadData();
			set_bit(SIGNAL_PORT, SIGNAL);
			//_delay_ms(25);
			/* did clearing interrupt
			 * flag succeed? */	
			if (SPSR == 0x00)
			{
				/* if yes blink LED */
				clear_bit(SIGNAL_PORT, SIGNAL);
				//_delay_ms(25);
			}
		}
		/* if flag is not set blink slowly
		 * forever */
		else
		{
			while (1)
			{
				set_bit(SIGNAL_PORT, SIGNAL);
				_delay_ms(500);
				clear_bit(SIGNAL_PORT, SIGNAL);
				_delay_ms(500);
			}
		}
	}
	/* if all is well, after completing
	 * the requested transmissions
	 * the LED should go off and the 
	 * processeor should do nothing
	 * happily ever after */
	while (1);
		;	
	return (0);

}
Exemplo n.º 10
0
void matrix_init(void)
{
	SPI_MasterInit();
	
	matrix_transmit(OP_SHUTDOWN,0b00000000);
	matrix_clear();
	matrix_transmit(OP_DISPLAYTEST,0x00);
	matrix_transmit(OP_SCANLIMIT,0x07);
	matrix_transmit(OP_DECODEMODE,0x00);
	matrix_transmit(OP_INTENSITY,0x0F);
	matrix_transmit(OP_SHUTDOWN,0b00000001);
}
Exemplo n.º 11
0
int main( void )
{
	cli();

	setup_clock();

	InitBuffer(&ab);

	//Don't touch any PORTB below 4, those are for printf
//	SetupPrintf();

	USB_ZeroPrescaler();
	USB_Init();

	DDRC = 0x0;

	SPI_MasterInit();

//	_delay_ms(10); //wait for tiny 44 to be ready for data
//	setup_timers();

	setup_channel_interrupt();

	DDRD |= _BV(PD6);

	sei();

//	testAsm();
//	if (testPtr == 'w') PORTD |= _BV(PD6);

	while(1)
	{
		UENUM = 4; //interrupts can change this

		//these if statements can take a bit of time so run them and save the
		//result for future use
		if ( USB_READY(UEINTX) && (BytesFree(&ab) >= 8) )
			dataState=1;
		else if ( BytesUsed(&ab) >= 2)
			dataState=2;
		else
			dataState=0;

		while (needAudioFlag==0);
cli();
		needAudioFlag=0;

		DoAudioState();
sei();
	}

	return 0;
}
Exemplo n.º 12
0
void oled_init()
{

	  SPI_MasterInit();
	  DDRB|=(1<<PB0)|(1<<PB1);
	  PORTB&=~(1<<PB0);
	  _delay_ms(50);
	  PORTB|=(1<<PB0);
	  PORTB&=~(1<<PB1);   //发送命令
	  SPI_MasterTransmit(0xae);//--turn off oled panel
      SPI_MasterTransmit(0x00);//---set low column address
      SPI_MasterTransmit(0x10);//---set high column address
      SPI_MasterTransmit(0x40);//--set start line address  Set Mapping RAM Display Start Line (0x00~0x3F)
      SPI_MasterTransmit(0x81);//--set contrast control register
      SPI_MasterTransmit(0xcf); // Set SEG Output Current Brightness
      SPI_MasterTransmit(0xa1);//--Set SEG/Column Mapping     0xa0左右反置 0xa1正常
      SPI_MasterTransmit(0xc8);//Set COM/Row Scan Direction   0xc0上下反置 0xc8正常
      SPI_MasterTransmit(0xa6);//--set normal display
      SPI_MasterTransmit(0xa8);//--set multiplex ratio(1 to 64)
      SPI_MasterTransmit(0x3f);//--1/64 duty
      SPI_MasterTransmit(0xd3);//-set display offset	Shift Mapping RAM Counter (0x00~0x3F)
      SPI_MasterTransmit(0x00);//-not offset
      SPI_MasterTransmit(0xd5);//--set display clock divide ratio/oscillator frequency
      SPI_MasterTransmit(0x80);//--set divide ratio, Set Clock as 100 Frames/Sec
      SPI_MasterTransmit(0xd9);//--set pre-charge period
      SPI_MasterTransmit(0xf1);//Set Pre-Charge as 15 Clocks & Discharge as 1 Clock
      SPI_MasterTransmit(0xda);//--set com pins hardware configuration
      SPI_MasterTransmit(0x12);
      SPI_MasterTransmit(0xdb);//--set vcomh
      SPI_MasterTransmit(0x40);//Set VCOM Deselect Level
      SPI_MasterTransmit(0x20);//-Set Page Addressing Mode (0x00/0x01/0x02)
      SPI_MasterTransmit(0x02);//
      SPI_MasterTransmit(0x8d);//--set Charge Pump enable/disable
      SPI_MasterTransmit(0x14);//--set(0x10) disable
      SPI_MasterTransmit(0xa4);// Disable Entire Display On (0xa4/0xa5)
      SPI_MasterTransmit(0xa6);// Disable Inverse Display On (0xa6/a7)
      SPI_MasterTransmit(0xaf);//--turn on oled panel
/*	SPI_MasterTransmit(0xAF);
	SPI_MasterTransmit(0x40);
	SPI_MasterTransmit(0xA0);
	SPI_MasterTransmit(0xA6);
	SPI_MasterTransmit(0xA4);
	SPI_MasterTransmit(0xA2);
	SPI_MasterTransmit(0xC8);
	SPI_MasterTransmit(0x2F);
	SPI_MasterTransmit(0x24);
	SPI_MasterTransmit(0x81);
	SPI_MasterTransmit(0x24); */

	oled_clear();
}
Exemplo n.º 13
0
int main()
{
	DDRC=255; //PORTC as output,used for Slave Selections

	while(1)
	{
		PORTC=0;
		_delay_ms(1000);
		SPI_MasterInit();
		SPI_MasterTransmit(255);
		PORTC=255;
		_delay_ms(1000);


		PORTC=0;
		_delay_ms(1000);
		SPI_MasterInit();
		SPI_MasterTransmit(0);
		PORTC=255;
		_delay_ms(1000);
	}
	return 0;
}
Exemplo n.º 14
0
int main(void)
{ 
	//usart_init (UBRR_VAL);//инициализация модуля
	SPI_MasterInit();//инициализация SPI
	nRF24L01_init(0b00000011);//инициализация модуля
	nrf24l01_RX_TX_mode(PRX);//переходим в режим приемника
	while(1)
	{	
		mSend(4);//внешний
		mSend(3);//кухня
		mSend(2);//ванная		
	
	}
}
Exemplo n.º 15
0
int main(void)
{
    PORTB=0xFF;
    DDRB=0xFF;
    SPI_MasterInit();

    while (1)
    {
        SPI_MasterTransmit(0x37);
        _delay_ms(500);
        SPI_MasterTransmit(0x38);
        _delay_ms(500);
        SPI_MasterTransmit(0x39);
        _delay_ms(500);
    }
}
Exemplo n.º 16
0
void init(void) {
    clock_prescale_set(clock_div_2); // we run at 3.3v
    fdev_setup_stream(&mystdout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
    stdout = &mystdout;
    usb_init();
    MRF_RESET_CONFIG;
    MRF_CS_CONFIG;
    SPI_MasterInit();

    // interrupt pin from mrf
    EIMSK |= (1<<INT0);

    while (!usb_configured()) {
    }
    // Advised to wait a bit longer by pjrc.com
    // as not all drivers will be ready even after host is up
    _delay_ms(500);
}
int main(void) {
    char highbyte, lowbyte;
    SPI_MasterInit();
    int i;
    i = MCP_START;  // MCP4921 initial value
    while(1)
    {
        for (i=MCP_START; i<MCP_START+4096; i+=2)
        {
            highbyte = i>>8;
            lowbyte = i;
            PORTB &= ~(1<<2); //SS sets to low
            SPI_MasterTransmit(highbyte);
            SPI_MasterTransmit(lowbyte);
            PORTB |= 1<<2;   //SS sets to high
        }
    }

}
Exemplo n.º 18
0
int main(void)
{
	struct LCD_Geometry *pointCurrent= &Current;
	struct LCD_Properties *pointProperties= &Properties;
	FILE lcd_str = FDEV_SETUP_STREAM(TerminalChar, NULL, _FDEV_SETUP_RW);
	//FILE lcd_str = FDEV_SETUP_STREAM(USART_send, NULL, _FDEV_SETUP_RW);
	char *hellow = "hello";
	stdout = &lcd_str;

	USART_init();
	SPI_MasterInit();
	SSD1289_Initalize();
	

	
	testLibrary(); 

		
	//ReadBMP_ARRAY(40,40,BMP_IMAGE);
}
void Radio_RxInit() {
	SPI_MasterInit();
	DDRB|=(1<<CSN)|(1<<CE);
	PORTB|=(1<<IRQ)|(1<<CSN);
	delay_ms(5);
	unsigned char oneByte[1]={0x33};
	unsigned char threeByte[3]={0x18, 0x04, 0x96};
	writeRegister(0x00, oneByte, 1); //set config reg to power up into rx mode
	oneByte[0]=0x01;
	writeRegister(0x03, oneByte, 1); //set address length to 3 bytes
	writeRegister(0x0A, threeByte, 3); //set address of pipe 0 to random number, in this case my birthday
	oneByte[0]=76;
	writeRegister(0x05, oneByte, 1); //set channel to 76
	oneByte[0]=0x00;
	writeRegister(0x01, oneByte, 1); //turn off auto acknowledge
	oneByte[0]=5;
	writeRegister(0x11, oneByte, 1); //set packet length for pipe 0
	flushRx();
	PORTB|=(1<<CE);
}
void Radio_TxInit() {
	SPI_MasterInit();
	DDRB|=(1<<CSN)|(1<<CE);
	PORTB|=(1<<IRQ)|(1<<CSN);
	delay_ms(5); //settling time specified in the data sheet
	unsigned char oneByte[1]={0x72};
	unsigned char threeByte[3]={0x18, 0x04, 0x96};
	writeRegister(0x00, oneByte, 1); //set config reg to power up into tx mode
	oneByte[0]=0x01;
	writeRegister(0x03, oneByte, 1); //set address length to 3 bytes
	writeRegister(0x10, threeByte, 3); //set address of transmit to random number, in this case my birthday
	oneByte[0]=76;
	writeRegister(0x05, oneByte, 1); //set to channel 76
	oneByte[0]=0x00;
	writeRegister(0x01, oneByte, 1); //turn off Auto Acknowledge, one way communication okay if a few packets get dropped
	writeRegister(0x04, oneByte, 1); //turn off retransmit, not ideal for remote control
	oneByte[0]=0x01;
	writeRegister(0x1D, oneByte, 1); //enable W_TX_PAYLOAD_NOACK
	flushTx();
	PORTB|=(1<<CE);
}
void SPI_Init(u08 mode,u08 prescale)
{ //variable

        unsigned char temp;

//set these pins H

        SPI_PORT |= (1<<MOSI_PIN)|(1<<MISO_PIN)|(1<<SCK_PIN);

//setup SPI

        SPI_SCKspeed(prescale);

        SPI_Modeselect(mode);

        SPI_MasterInit();

//clear SPI interrupt flag

        temp = SPSR;

        temp = SPDR;
}
Exemplo n.º 22
0
int main(void)
{
	/* desabilita os pinos de RX e TX */
	UCSR0B=0x00;
				
	/* Para uso do botão */
	DDRB &= (~(1 << PB0));
	PORTB |= (1 << PB0);
	
	LCD_inicia_4bits();
	
	SPI_MasterInit();
		
    while(1)
    {
		if(!tst_bit(PINB, PB0)) {
			SPI_HABILITA_SLAVE();	
			_delay_ms(20);
			SPI_Transmit('A');
			SPI_DESABILITA_SLAVE();
			while(!tst_bit(PINB, PB0));
		}		
    }
}
Exemplo n.º 23
0
int main(void)
{
	unsigned int XXL,YXL,ZXL;
	//unsigned int ADC1,ADC2,ADC3;
//	int16_t ZGY;
	unsigned int XGY,YGY,ZGY;
//	unsigned char XYZ_buffer[100];
	unsigned int timer=0;
	unsigned int timer_old=0;
	unsigned int diff_counter=0;
	unsigned int m_IMU_count=0;
    double m_XXL_sum=0;
    double m_YXL_sum=0;
    double m_ZXL_sum=0;
    double m_XGY_sum=0;
    double m_YGY_sum=0;
    double m_ZGY_sum=0;


	clk_init();
	port_init();
 	USART_INIT();
	
	timer_Init();
	int_init();
//	sei();
	

//	spi_init();


	/* Init SS pin as output with wired AND and pull-up. */
	//120813 portC를 D로 바꿈 SPI인거 같아서  
	PORTD.DIRSET = PIN0_bm;
	PORTD.PIN0CTRL = PORT_OPC_WIREDANDPULL_gc;
	PORTD.DIRSET = PIN1_bm;
	PORTD.PIN1CTRL = PORT_OPC_WIREDANDPULL_gc;

	/* Set SS output to high. (No slave addressed). */
	PORTD.OUTSET = PIN0_bm;
	PORTD.OUTSET = PIN1_bm;

	/* Instantiate pointer to ssPort. */
	PORT_t *ssPort = &PORTD;

	/* Initialize SPI master on port D. */
	SPI_MasterInit(&spiMasterD,
	               &SPID,
	               &PORTD,
	               false,
	               SPI_MODE_3_gc,
	               SPI_INTLVL_OFF_gc,
	               false,
	               SPI_PRESCALER_DIV16_gc);


	/* Use USARTD0 and initialize buffers. */
	USART_InterruptDriver_Initialize(&USARTD0_data, &USARTD0, USART_DREINTLVL_HI_gc);

	/* Enable RXC interrupt. */
	USART_RxdInterruptLevel_Set(USARTD0_data.usart, USART_RXCINTLVL_HI_gc);

	/* Enable PMIC interrupt level low. */
	PMIC.CTRL |= PMIC_HILVLEX_bm;

	/* Enable global interrupts.*/
	sei();

	/* Initialize ACC & Gyro */
//	Init_L3G4200DH();
	Init_LIS3DH();
	
	SPI_MasterCreateDataPacket(&dataPacket,
		                           masterSendData_gyro_init,
		                           GYRO_DATA,
		                           NUM_BYTES,
		                           &PORTD,
		                           PIN1_bm);

		SPI_MasterSSLow(ssPort, PIN1_bm);

		/* Transceive packet. */
		SPI_MasterTransceivePacket(&spiMasterD, &dataPacket);
		/* MASTER: Release SS to slave. */

		SPI_MasterSSHigh(ssPort, PIN1_bm);



//	USART_Rx_Enable(&USARTD0);
//	USART_Tx_Enable(&USARTD0);


	

	double z_deg=0;


	unsigned int oldT=0;
	unsigned int newT=0;	
	unsigned int dT=0;	
	int i;

	
	double x1m=0;
	double x1p=0;
	
	double P1p=1.0;

	double x2m[4]={0,0,0,0};
	double x2p[4]={0,0,0,0};
	
	double P2p[4][4]={{0.1,0,0,0},
				 	  {0,0.1,0,0},
					  {0,0,0.1,0},
			 		  {0,0,0,0.1}};


	double enc_time_cnt=0;

	for(i=0;i<DELAY_COMP_G;i++)
	{
		m_XGY_buf[i]=0.0;
		m_YGY_buf[i]=0.0;
		m_ZGY_buf[i]=0.0;

		m_XXL_buf[i]=0.0;
		m_YXL_buf[i]=0.0;
		m_ZXL_buf[i]=0.0;

		m_enc_buf[i]=0.0;
		m_enc_timebuf[i]=0.0;
		m_T_buf[i]=0.0;

	}

	//char XYZ_buffer_debug[20];
	//sprintf((char*)XYZ_buffer_debug,"Hello W");
	//uartSendTX((unsigned char*)XYZ_buffer_debug);
	while(1) 
	{
		
		
		//if(1)
		if(samplingFlag)
		{
				
		
			
//				adc_start_conversion(&ADCA, ADC_CH0);			
				samplingFlag=0;
				timer=TCC0.CNT;
				diff_counter=timer-timer_old;
				
				
				/* Create data packet (SS to slave by PC0). */
				SPI_MasterCreateDataPacket(&dataPacket,
				                           masterSendData,
				                           ACC_DATA,
				                           NUM_BYTES,
				                           &PORTD,
				                           PIN0_bm);


				/* MASTER: Pull SS line low. This has to be done since
				 *         SPI_MasterTransceiveByte() does not control the SS line(s). */
				SPI_MasterSSLow(ssPort, PIN0_bm);
				_delay_us(5);
				/* Transceive packet. */
				SPI_MasterTransceivePacket(&spiMasterD, &dataPacket);
				/* MASTER: Release SS to slave. */
				_delay_us(5);
				SPI_MasterSSHigh(ssPort, PIN0_bm);
				
				
				/* Create data packet (SS to slave by PC1). */
				SPI_MasterCreateDataPacket(&dataPacket,
				                           masterSendData_gyro,
				                           GYRO_DATA,
				                           NUM_BYTES,
				                           &PORTD,
				                           PIN1_bm);

				/* MASTER: Pull SS line low. This has to be done since
				 *         SPI_MasterTransceiveByte() does not control the SS line(s). */
				SPI_MasterSSLow(ssPort, PIN1_bm);
				/* Transceive packet. */
				_delay_us(5);
				SPI_MasterTransceivePacket(&spiMasterD, &dataPacket);
				/* MASTER: Release SS to slave. */
				_delay_us(5);
				SPI_MasterSSHigh(ssPort, PIN1_bm);







				timer_old=timer;

				T=(double)diff_counter/2000000.0*32.0;

				ACC_DATA[2]=ACC_DATA[2]+0x80;
				ACC_DATA[4]=ACC_DATA[4]+0x80;
				ACC_DATA[6]=ACC_DATA[6]+0x80;
				YXL= (unsigned int)ACC_DATA[2]*256+ACC_DATA[1];
				XXL= (unsigned int)ACC_DATA[4]*256+ACC_DATA[3];
				ZXL= (unsigned int)ACC_DATA[6]*256+ACC_DATA[5];

				GYRO_DATA[2]=GYRO_DATA[2]+0x80;
				GYRO_DATA[4]=GYRO_DATA[4]+0x80;
				GYRO_DATA[6]=GYRO_DATA[6]+0x80;
				XGY= (unsigned int)GYRO_DATA[4]*256+GYRO_DATA[3];
				YGY= (unsigned int)GYRO_DATA[2]*256+GYRO_DATA[1];
				ZGY= (unsigned int)GYRO_DATA[6]*256+GYRO_DATA[5];	
			
			if(m_IMU_count<Tsample)
			{
				m_IMU_count++;
			}
			else if(m_IMU_count<Tsample+Bsample)
			{
				m_XXL_sum+=XXL;
				m_YXL_sum+=YXL;
				m_ZXL_sum+=ZXL;
				//m_XGY_sum+=XGY;
				//m_YGY_sum+=YGY;
				m_ZGY_sum+=ZGY;
				m_IMU_count++;
			}
			else if(m_IMU_count==Tsample+Bsample)
			{
				//SetTimer(25,1,NULL);
				m_biasXXL=(double)m_XXL_sum/(double)Bsample;
				m_biasYXL=(double)m_YXL_sum/(double)Bsample;
				m_biasZXL=(double)m_ZXL_sum/(double)Bsample-GRAVITY_COUNT;
				//m_biasXGY=(double)m_XGY_sum/(double)Bsample;
				//m_biasYGY=(double)m_YGY_sum/(double)Bsample;
				m_biasZGY=(double)m_ZGY_sum/(double)Bsample;

				
				gravityVect[0]=0;
				gravityVect[1]=0;
				gravityVect[2]=SCALE_ZXL*GRAVITY_COUNT;

				m_IMU_count++;

		    }
		    else
			{
				
			
				//encoder_interface(0);
				//encoder_interface(1);
				
				//host_interface();
				


				//unsigned int a=TCC0.CNT;

				//position_estimator(XXL,YXL,ZXL,XGY,YGY,ZGY);
				
				//unsigned int b=TCC0.CNT;

				//TJX=(double)(b-a)/2000000.0*32.0;

				//FF_controller();

				newT=TCC0.CNT;
				dT=newT-oldT;

				
				////////////////////////////////////////////////
				///////////////////////////////////////////////////////
				///////////////////////////////////////////////////////
				///////////////////////////////////////////////////////
				///////////////////////////////////////////////////////
				///////////////////////////////////////////////////////
				///////////////////////////////////////////////////////	    	
				int i,j,k;	

				m_XXL=-SCALE_XXL*((double)XXL-(double)m_biasXXL);
				m_YXL=-SCALE_YXL*((double)YXL-(double)m_biasYXL);
				m_ZXL=SCALE_ZXL*((double)ZXL-(double)m_biasZXL);
				m_XGY=-SCALE_XGY*((double)XGY-(double)m_biasXGY);//-0.001212142/0.00015711
				m_YGY=SCALE_YGY*((double)YGY-(double)m_biasYGY);//+
				//if(ZGY<3000)	m_ZGY=SCALE_ZGY*((double)ZGY-(double)m_biasZGY+65536.0);
				//else 			m_ZGY=SCALE_ZGY*((double)ZGY-(double)m_biasZGY);//+
				m_ZGY=SCALE_ZGY*((double)ZGY-(double)m_biasZGY);
				
				sprintf(XYZ_buffer,"%u %u %u %u %u %u \n",XXL, YXL, ZXL, XGY, YGY, ZGY);
				uartC0SendTX((unsigned char*)XYZ_buffer);
		
			}
		}
	}

	while(true) {
		nop();
	}
}
Exemplo n.º 24
0
int main( void )
{
    uint8_t delay;
    uint8_t counter;
    uint8_t doStatus = 1;

    InitTimer();
    InitUART();

    SetDirectionOut( LED );

    SetDirectionOut( MOSI );
    SetDirectionIn(  MISO );
    SetDirectionOut( SCK );
    SetDirectionOut( SS );
    SetDirectionIn(  INT );
    SetDirectionOut( TRIGGER );

    TRIGGER_PORT &= ~TRIGGER_MASK;

    SPI_MasterInit();

    Log( "*****\n" );
    Log( "***** WLN CLI program\n" );
    Log( "*****\n" );

    sei();

    counter = 0;
    while ( 1 )
    {
        LED_PORT ^= LED_MASK;

        if ( doStatus )
        {
            if ( counter == 0 )
            {
                uint8_t status = WLN_ReadStatus();
                WLN_PrintStatus( status );
            }
            counter = ( counter + 1 ) & 0x03;
        }

        // Tick rate is 100/sec so waiting for 50 waits for 1/2 sec

        for ( delay = 0; delay < 50; delay++ ) 
        {
            tick_t prevCount = gTickCount;
            while ( gTickCount == prevCount )
            {
                LogBufDump();
            }

            if ( UART0_IsCharAvailable() )
            {
                char    ch = UART0_GetChar();

                switch ( ch )
                {
                    case '!':
                    {
                        doStatus = !doStatus;
                        Log( "Turning status %s\n", doStatus ? "on" : "off" );
                        break;
                    }

                    case '*':
                    {
                        Log( "Reset\n" );

                        SetDirectionOut( RESET );
                        RESET_PORT &= ~RESET_MASK;
                        break;
                    }

                    case ' ':
                    {
                        WLN_ReadData();
                        break;
                    }

                    default:
                    {
                        Log( "Read: '%c'\n", ch );
                        WLN_WriteByte( ch );
                        break;
                    }
                }

            }
        }
    }

} // main
Exemplo n.º 25
0
//-----------------------------------------------------------------------------
// functions
//-----------------------------------------------------------------------------
void spi_init(void) {
    // Initialize SPI master on port C.
	SPI_MasterInit(&spiMasterC, &SPIC, &PORTC, false, SPI_MODE_0_gc, \
	               SPI_INTLVL_HI_gc, false, SPI_PRESCALER_DIV4_gc);
}
Exemplo n.º 26
0
Arquivo: spi_api.c Projeto: pan-/mbed
void spi_format(spi_t *obj, int bits, int mode, int slave)
{
    spi_master_config_t master_config;
    spi_slave_config_t slave_config;

    /* Bits: values between 4 and 16 are valid */
    MBED_ASSERT(bits >= 4 && bits <= 16);
    obj->bits = bits;

    if (slave) {
        /* Slave config */
        SPI_SlaveGetDefaultConfig(&slave_config);
        slave_config.dataWidth = (spi_data_width_t)(bits - 1);
        slave_config.polarity = (mode & 0x2) ? kSPI_ClockPolarityActiveLow : kSPI_ClockPolarityActiveHigh;
        slave_config.phase = (mode & 0x1) ? kSPI_ClockPhaseSecondEdge : kSPI_ClockPhaseFirstEdge;

        SPI_SlaveInit(spi_address[obj->instance], &slave_config);
    } else {
        /* Master config */
        SPI_MasterGetDefaultConfig(&master_config);
        master_config.dataWidth = (spi_data_width_t)(bits - 1);
        master_config.polarity = (mode & 0x2) ? kSPI_ClockPolarityActiveLow : kSPI_ClockPolarityActiveHigh;
        master_config.phase = (mode & 0x1) ? kSPI_ClockPhaseSecondEdge : kSPI_ClockPhaseFirstEdge;
        master_config.direction = kSPI_MsbFirst;

        switch (obj->instance) {
            case 0:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM0);
                RESET_PeripheralReset(kFC0_RST_SHIFT_RSTn);
                break;
            case 1:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM1);
                RESET_PeripheralReset(kFC1_RST_SHIFT_RSTn);
                break;
            case 2:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM2);
                RESET_PeripheralReset(kFC2_RST_SHIFT_RSTn);
                break;
            case 3:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM3);
                RESET_PeripheralReset(kFC3_RST_SHIFT_RSTn);
                break;
            case 4:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM4);
                RESET_PeripheralReset(kFC4_RST_SHIFT_RSTn);
                break;
            case 5:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM5);
                RESET_PeripheralReset(kFC5_RST_SHIFT_RSTn);
                break;
            case 6:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM6);
                RESET_PeripheralReset(kFC6_RST_SHIFT_RSTn);
                break;
            case 7:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM7);
                RESET_PeripheralReset(kFC7_RST_SHIFT_RSTn);
                break;
#if (FSL_FEATURE_SOC_FLEXCOMM_COUNT > 8U)
            case 8:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM8);
                RESET_PeripheralReset(kFC8_RST_SHIFT_RSTn);
                break;
#endif
#if (FSL_FEATURE_SOC_FLEXCOMM_COUNT > 9U)
            case 9:
                CLOCK_AttachClk(kFRO12M_to_FLEXCOMM9);
                RESET_PeripheralReset(kFC9_RST_SHIFT_RSTn);
                break;
#endif

        }

        SPI_MasterInit(spi_address[obj->instance], &master_config, 12000000);
    }
}
Exemplo n.º 27
0
int main(void)
{
	unsigned int XXL,YXL,ZXL,XGL,YGL,ZGL;
	unsigned char XYZ_buffer[100];
	clk_init();
	port_init();
 	USART_INIT();
//	spi_init();


	/* Init SS pin as output with wired AND and pull-up. */
	PORTC.DIRSET = PIN0_bm;
	PORTC.PIN0CTRL = PORT_OPC_WIREDANDPULL_gc;
	PORTC.DIRSET = PIN1_bm;
	PORTC.PIN1CTRL = PORT_OPC_WIREDANDPULL_gc;

	/* Set SS output to high. (No slave addressed). */
	PORTC.OUTSET = PIN0_bm;
	PORTC.OUTSET = PIN1_bm;

	/* Instantiate pointer to ssPort. */
	PORT_t *ssPort = &PORTC;

	/* Initialize SPI master on port C. */
	SPI_MasterInit(&spiMasterC,
	               &SPIC,
	               &PORTC,
	               false,
	               SPI_MODE_3_gc,
	               SPI_INTLVL_OFF_gc,
	               false,
	               SPI_PRESCALER_DIV16_gc);

	/* Initialize ACC & Gyro */
	Init_L3G4200DH();
	Init_LIS331DLH();

	/* Read Sensor data */

	while(true) {
	/* Create data packet (SS to slave by PC0). */
	SPI_MasterCreateDataPacket(&dataPacket,
	                           masterSendData,
	                           ACC_DATA,
	                           NUM_BYTES,
	                           &PORTC,
	                           PIN0_bm);


	/* MASTER: Pull SS line low. This has to be done since
	 *         SPI_MasterTransceiveByte() does not control the SS line(s). */
	SPI_MasterSSLow(ssPort, PIN0_bm);
	/* Transceive packet. */
	SPI_MasterTransceivePacket(&spiMasterC, &dataPacket);
	/* MASTER: Release SS to slave. */
	SPI_MasterSSHigh(ssPort, PIN0_bm);


	/* Create data packet (SS to slave by PC1). */
	SPI_MasterCreateDataPacket(&dataPacket,
	                           masterSendData,
	                           GYRO_DATA,
	                           NUM_BYTES,
	                           &PORTC,
	                           PIN1_bm);

	/* MASTER: Pull SS line low. This has to be done since
	 *         SPI_MasterTransceiveByte() does not control the SS line(s). */
	SPI_MasterSSLow(ssPort, PIN1_bm);
	/* Transceive packet. */
	SPI_MasterTransceivePacket(&spiMasterC, &dataPacket);
	/* MASTER: Release SS to slave. */
	SPI_MasterSSHigh(ssPort, PIN1_bm);

	  ACC_DATA[2]=ACC_DATA[2]+0x80;
	  ACC_DATA[4]=ACC_DATA[4]+0x80;
	  ACC_DATA[6]=ACC_DATA[6]+0x80;
	  XXL= (unsigned int)ACC_DATA[2]*256+ACC_DATA[1];
	  YXL= (unsigned int)ACC_DATA[4]*256+ACC_DATA[3];
	  ZXL= (unsigned int)ACC_DATA[6]*256+ACC_DATA[5];

	  GYRO_DATA[2]=GYRO_DATA[2]+0x80;
	  GYRO_DATA[4]=GYRO_DATA[4]+0x80;
	  GYRO_DATA[6]=GYRO_DATA[6]+0x80;
	  XGL= (unsigned int)GYRO_DATA[2]*256+GYRO_DATA[1];
	  YGL= (unsigned int)GYRO_DATA[4]*256+GYRO_DATA[3];
	  ZGL= (unsigned int)GYRO_DATA[6]*256+GYRO_DATA[5];

		sprintf((char*)XYZ_buffer,"[XXL%6u][YXL%6u][ZXL%6u][XGY%6u][YGY%6u][ZGY%6u]\r\n",XXL,YXL,ZXL,XGL,YGL,ZGL);
		//uartSendTXbit('3');
		//sprintf((char*)XYZ_buffer,"abcdefgefgh12341\n\r");	
		uartSendTX(XYZ_buffer);
	}
	while(true) {
		nop();
	}
}
Exemplo n.º 28
0
int main() {
   bitSet(DDRJ, DDJ1);  /* red - output pin */
   bitSet(DDRJ, DDJ0);  /* yellow - output pin */
   bitSet(DDRH, DDH1);  /* green - output pin */

   bitSet(PORTJ, PJ1);  /* red off */
   bitSet(PORTJ, PJ0);  /* yellow off */
   bitSet(PORTH, PH1);  /* green off */

   DDRL =  0b00000000;  /* PL0 .. PL7 input */
   PORTL = 0b11111111;  /* PL0 .. PL7 pullup enable */

   // initialize timer.
   OCR1A = 2;                /* Compare match after 2 increments (976 Hz) */
   TCCR1A = _BV(COM1A0);      /* Toggle OC1A on compare match */
   TCCR1B = _BV(WGM12) | _BV(CS12) | _BV(CS10);   /* Mode=Clear on Compare Match; clk = Clk_IO/1024 = 1953 Hz */
   TCCR1C = 0;
   TIMSK1 = _BV(OCIE1A);

   //TCCR0A = 0;
   //TCCR0B = _BV(CS02) | _BV(CS00);      // start timer with clk/1024 (15,625 kHz)
   //TIMSK0 = _BV(TOIE0);                 // enable timer0 overflow interrupt

SPI_MasterInit();
   int value = 0;
   int prevValue = 0;
   lcdInit();
   sei();
   lcdPrint(0, "Hello Arduino!");
   while(1) {
      set_sleep_mode(0); // IDLE mode
      sleep_mode();

      if (prevEncoder == 2 && encoderVal == 0) {
         value+=10;
         if (value > 1000) {
            value = 1000;
         }
         bitClear(PORTJ, PJ1);  /* red on */
      } else {
         bitSet(PORTJ, PJ1);  /* red off */
      }

      if (prevEncoder == 1 && encoderVal == 0) {
         value-=10;
         if (value < 0) {
            value = 0;
         }
         bitClear(PORTJ, PJ0);  /*yellow on */
      } else {
         bitSet(PORTJ, PJ0);  /* yellow off */
      }

      if (prevValue != value) {
         itoa(value, line, 10);
         lcdPrint(0, line);
         MCP48xx_SetValue(value);
      }
      prevValue = value;
   
#if 0
      if ( (prevEncoder == 3 && encoderVal == 2) ||
           (prevEncoder == 2 && encoderVal == 0) ||
           (prevEncoder == 0 && encoderVal == 1) ||
           (prevEncoder == 1 && encoderVal == 3)) {
         bitClear(PORTJ, PJ1);  /* red on */
      } else {
         bitSet(PORTJ, PJ1);  /* red off */
      }

      if ( (prevEncoder == 3 && encoderVal == 1) ||
           (prevEncoder == 1 && encoderVal == 0) ||
           (prevEncoder == 0 && encoderVal == 2) ||
           (prevEncoder == 2 && encoderVal == 3)) {
         bitClear(PORTJ, PJ0);  /*yellow on */
      } else {
         bitSet(PORTJ, PJ0);  /* yellow off */
      }
#endif 
      prevEncoder = encoderVal;
   }
}
Exemplo n.º 29
0
/*! \brief Test function.
 *
 *  This function tests the SPI master and slave drivers in interrupt-driven
 *  operation, with a master (on port C) communicating with a slave (on port D).
 *
 *  Hardware setup:
 *
 *    - Connect PC4 to PD4 (SS)
 *    - Connect PC5 to PD5 (MOSI)
 *    - Connect PC6 to PD6 (MISO)
 *    - Connect PC7 to PD7 (SCK)
 *
 *  The driver is tested by transmitting data from the master to the slave.
 *  The slave increments the received data and sends it back. The master reads
 *  the data from the slave and verifies that it equals the data sent + 1.
 *
 *  The first data transaction is initiated by the main routine. When a
 *  transaction has finished, an interrupt will be triggered which will start
 *  new transactions until all bytes have been transceived.
 *
 *  The variable, 'success', will be non-zero when the function reaches the
 *  infinite for-loop if the test was successful.
 *
 *  \note This example uses multilevel interrupts. For more information on how
 *        to use the interrupt controller, refer to application note AVR1305.
 */
int main( void )
{
	/* Init SS pin as output with wired AND and pull-up. */
	PORTC.DIRSET = PIN4_bm;
	PORTC.PIN4CTRL = PORT_OPC_WIREDANDPULL_gc;

	/* Set SS output to high. (No slave addressed). */
	PORTC.OUTSET = PIN4_bm;

	/* Initialize SPI master on port C. */
	SPI_MasterInit(&spiMasterC,
	               &SPIC,
	               &PORTC,
				   false,
	               SPI_MODE_0_gc,
	               SPI_INTLVL_LO_gc,
	               false,
	               SPI_PRESCALER_DIV4_gc);

	/* Initialize SPI slave on port D. */
	SPI_SlaveInit(&spiSlaveD,
	              &SPID,
	              &PORTD,
	              false,
	              SPI_MODE_0_gc,
	              SPI_INTLVL_MED_gc);

	/* Enable low and medium level interrupts in the interrupt controller. */
	PMIC.CTRL |= PMIC_MEDLVLEN_bm | PMIC_LOLVLEN_bm;
	sei();

	/* Create data packet (SS to slave by PC4) */
	SPI_MasterCreateDataPacket(&dataPacket,
	                           sendData,
	                           receivedData,
	                           NUM_BYTES + 1,
	                           &PORTC,
	                           PIN4_bm);

	/* Transmit and receive first data byte. */
	uint8_t status;
	do {
		status = SPI_MasterInterruptTransceivePacket(&spiMasterC, &dataPacket);
	} while (status != SPI_OK);

	/* Wait for transmission to complete. */
	while (dataPacket.complete == false) {

	}

	/* Check that correct data was received. Assume success at first. */
	success = true;
	for (uint8_t i = 0; i < NUM_BYTES; i++) {
		if (receivedData[i + 1] != (uint8_t)(sendData[i] + 1)) {
			success = false;
		}
	}
	while(true) {
		nop();
	}
}
Exemplo n.º 30
0
/*! \brief Test function.
 *
 *  This function tests the SPI master and slave drivers in polled operation,
 *  with a master (on port C) communicating with a slave (on port D).
 *
 *  Hardware setup:
 *
 *    - Connect PC4 to PD4 (SS)
 *    - Connect PC5 to PD5 (MOSI)
 *    - Connect PC6 to PD6 (MISO)
 *    - Connect PC7 to PD7 (SCK)
 *
 *  The drivers are tested in two phases:
 *
 *  1: Data is transmitted on byte at a time from the master to the slave.
 *     The slave increments the received data and sends it back. The master reads
 *     the data from the slave and verifies that it equals the data sent + 1.
 *
 *  2: Data is transmitted 4 bytes at a time to the slave. As the master sends
 *     a byte to the slave, the preceding byte is sent back to the master.
 *     When all bytes have been sent, it is verified that the last 3 bytes
 *     received at the master, equal the first 3 bytes sent.
 *
 *  The variable, 'success', will be non-zero when the function reaches the
 *  infinite for-loop if the test was successful.
 */
int main(void)
{
	/* Init SS pin as output with wired AND and pull-up. */
	PORTC.DIRSET = PIN4_bm;
	PORTC.PIN4CTRL = PORT_OPC_WIREDANDPULL_gc;

	/* Set SS output to high. (No slave addressed). */
	PORTC.OUTSET = PIN4_bm;

	/* Instantiate pointer to ssPort. */
	PORT_t *ssPort = &PORTC;

	/* Initialize SPI master on port C. */
	SPI_MasterInit(&spiMasterC,
	               &SPIC,
	               &PORTC,
	               false,
	               SPI_MODE_0_gc,
	               SPI_INTLVL_LO_gc,
	               false,
	               SPI_PRESCALER_DIV4_gc);

	/* Initialize SPI slave on port D. */
	SPI_SlaveInit(&spiSlaveD,
	              &SPID,
	              &PORTD,
	              false,
				  SPI_MODE_0_gc,
				  SPI_INTLVL_LO_gc);

	/* PHASE 1: Transceive individual bytes. */

	/* MASTER: Pull SS line low. This has to be done since
	 *         SPI_MasterTransceiveByte() does not control the SS line(s). */
	SPI_MasterSSLow(ssPort, PIN4_bm);

	for(uint8_t i = 0; i < NUM_BYTES; i++) {
		/* MASTER: Transmit data from master to slave. */
		SPI_MasterTransceiveByte(&spiMasterC, masterSendData[i]);

		/* SLAVE: Wait for data to be available. */
		while (SPI_SlaveDataAvailable(&spiSlaveD) == false) {

		}

		/* SLAVE: Get the byte received. */
		uint8_t slaveByte = SPI_SlaveReadByte(&spiSlaveD);

		/* SLAVE: Increment received byte and send back. */
		slaveByte++;
		SPI_SlaveWriteByte(&spiSlaveD, slaveByte);

		/* MASTER: Transmit dummy data to shift data from slave to master. */
		uint8_t masterReceivedByte = SPI_MasterTransceiveByte(&spiMasterC, 0x00);

		/* MASTER: Check if the correct value was received. */
		if (masterReceivedByte != (masterSendData[i] + 1) ) {
			success = false;
		}
	}

	/* MASTER: Release SS to slave. */
	SPI_MasterSSHigh(ssPort, PIN4_bm);

	/* PHASE 2: Transceive data packet. */

	/* Create data packet (SS to slave by PC4). */
	SPI_MasterCreateDataPacket(&dataPacket,
	                           masterSendData,
	                           masterReceivedData,
	                           NUM_BYTES,
	                           &PORTC,
	                           PIN4_bm);

	/* Transceive packet. */
	SPI_MasterTransceivePacket(&spiMasterC, &dataPacket);

	/* Check that correct data was received. Assume success at first. */
	for (uint8_t i = 0; i < NUM_BYTES - 1; i++) {
		if (masterReceivedData[i + 1] != masterSendData[i]) {
			success = false;
		}
	}

	while(true) {
		nop();
	}
}