i'm currently trying to set up a SPI via an Arduino Uno (for a prototype that will use an Atmel MCU). For starters, i just want so send out one byte and clear the Flag (activating an LED to indicate). But the programm never gets past waiting for the flag. Any idea what the problem might be?
Here is the code:
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <avr/io.h>
#define SET_REG_BIT(a,b) a = a | (1<<b)
#define DEL_REG_BIT(a,b) a = a & ~(1<<b)
#define FLIP_REG_BIT(a,b) a = a ^ (1<<b)
#define CHECK_REG_BIT(a,b) a = ((a & (1<<b))>>b)
void setup()
{
//LED_PORT PB5 -> Output
SET_REG_BIT(DDRB, DDB0);
//SS PB2 -> Output
SET_REG_BIT(DDRB, DDB2);
//SS PB2 LOW
SET_REG_BIT(PORTB, PORTB2);
//MOSI PB3 -> Output
SET_REG_BIT(DDRB, DDB3);
//SCK PB5 -> Output
SET_REG_BIT(DDRB, DDB5);
//SPI Enable
SET_REG_BIT(SPCR, SPE);
//SPI Interrupt Disable
DEL_REG_BIT(SPCR, SPIE);
//SPI Master Mode
SET_REG_BIT(SPCR, MSTR);
//Write to SPI Data Register, start transmission
SPDR = 0x01;
//Wait for SPI Flag
while ((SPSR & (1<<SPIF)) == 0);
//Activate LED
SET_REG_BIT(PORTB, PORTB0);
}
void loop()
{
}
Thank you, this does work. But i still don't understand why it won't work with my code. Besides enabling SPI, setting MOSI, SCK and SS as Outputs and driving SS low, writing into die data register should be enough to get the flag set, even without connecting a slave...
But i still don't understand why it won't work with my code.
Explained in #2. You really need to read the data sheet, look at the power up default values for the registers that must be set correctly, then set them correctly.
Got it solved. The initialization was correct, but MSTR bit must be set before SPI Enable, otherwise SS seems to put it in Slave mode. A bit misleading since the datasheet says:
"If SS is configured as an output, the pin is a general output pin which does not affect the SPI system."