aboutsummaryrefslogtreecommitdiff
path: root/src/inc/spi/spi.c
blob: b04fe7eab45f38ecd93ce83e87c2bfde0237d1c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "spi.h"

void spi_init()
{
  // setup SPI-Port
  DDR_SPI   = (1<<DD_MOSI) | (1<<DD_SS) | (1<<DD_SCK);
  PORT_SPI |=  (1<<DD_SS);

  // SPI Control Register (SPCR)
  // SPI Enable=1 | Data Order=LSB | SPI_Master=1 (!make SS stay HIGH!)
  // SPCR |= (1<<SPE) | (1<<DORD) | (1<<MSTR) | (1<<CPOL) | (1<<CPHA) | (1<<SPR1) | (1<<SPR0);
  // (1<<DORD) - would be LSB-mode (, but we need MSB-mode!)
  SPCR  = (1<<SPE) | (1<<MSTR); //  (1<<SPR1) | (1<<SPR0)
  spi_setspeed(SPICLK_DEFAULT);
  // setup SPI options
  /// SPSR &= ~(1<<SPI2X); // do not use SPI speed-doubler
}

void spi_setspeed(SPICLK speed)
{
  if(speed < 4) // nominal clock speeds
  {
    SPSR &= ~(1<<SPI2X); // do not use SPI speed-doubler
    SPCR |= speed;
  }
  else // use SPI2X
  {
    SPSR |= (1<<SPI2X);  // use SPI speed-doubler
    SPCR |= (speed - 0x4);
  }
  _delay_ms(2);
}

void spi_putc(unsigned char c)
{
  /// uart_putc('>');
  /// uart_putc(c);
  /// uart_putc('\n');
  SPDR = c;
  loop_until_bit_is_set(SPSR, SPIF);
  /// stdout_put_string(uart_putc, "- [done]\n");
}

unsigned char spi_getc()
{
  SPDR = 0xFF; // init receive register with value
  /* Wait for reception complete */
  while(!(SPSR & (1<<SPIF)));
  /* Return data register */
  return SPDR;
  /// unsigned char c = SPDR;
  /// uart_putc('<');
  /// uart_putc(c);
  /// uart_putc('\n');
  /// return c;
}
..