#include <avr/io.h>
#include <util/delay.h>
/* SPI port and pin definitions.*/
#define _BV(bit) (1 << (bit))
#define OUT_REG PORTB //!< port output register.
#define IN_REG PINB //!< port input register.
#define DIR_REG DDRB //!< port direction register.
#define CLOCK_PIN PINB2 //!< clock I/O pin.
#define DATAIN_PIN PINB1 //!< data input pin.
#define DATAOUT_PIN PINB0 //!< data output pin.
unsigned char Transmitt_Receive_Master(unsigned char data);
void SetClock()
{
PORTB |= (1 << PINB2);
}
void ClearClock()
{
PORTB &= ~(1 << PINB2);
}
void SetData()
{
PORTB |= (1 << PINB0);
}
void ClearData()
{
PORTB &= ~(1 << PINB0);
}
void Spi_Master_Init()
{
// set up SCK/MOSI as output Pins
DIR_REG |= (1<<DATAOUT_PIN) | (1<<CLOCK_PIN);
DIR_REG &= ~(1<<DATAIN_PIN); // Data-In (MISO) AS input
}
int main(void)
{
Spi_Master_Init();
while(1)
{
Transmitt_Receive_Master(20);
}
}
unsigned char Transmitt_Receive_Master(unsigned char data)
{
unsigned char i;
unsigned char ReceivedValue=0;
for (i=0;i<8;i++)
{
if (data & _BV(i))
{
SetData();
}
else
{
ClearData();
}
data <<= 1;
// set clock high
_delay_ms(100);
SetClock();
ReceivedValue <<= 1; //shift left one bit
if (IN_REG & DATAIN_PIN )
{
ReceivedValue |= _BV(i);
}
else
{
ReceivedValue &= ~_BV(i);
}
ClearClock();
}
return ReceivedValue;
}