summaryrefslogtreecommitdiff
path: root/src/arch/lora32u4ii/driver/spi.cc
blob: c2cad08200f780980971ce4097266122531f9416 (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
/*
 * Copyright 2021 Daniel Friesel
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */
#include "driver/spi.h"
#include "driver/gpio.h"
#include "arch.h"
#include <avr/io.h>

signed char SPI::setup()
{
	// configure SS as output to avoid unintened switches to slave mode
	gpio.output(GPIO::pb0, 0);
	// MISO is automatically configured as input
	// Configure SCK and MOSI as output
	DDRB |= _BV(PB2) | _BV(PB1);
	// up to 2 MHz SPI clock
	SPCR = _BV(SPE) | _BV(MSTR);
}

signed char SPI::xmit(
		unsigned char tx_len, unsigned char *tx_buf,
		unsigned char rx_len, unsigned char *rx_buf)
{
	unsigned char i = 0;

	while ((i < tx_len) || (i < rx_len)) {
		if (i < tx_len) {
			SPDR = tx_buf[i];
		} else {
			SPDR = 0;
		}
		while (!(SPSR & _BV(SPIF))) ;
		if (i < rx_len) {
			rx_buf[i] = SPDR;
		}
		i++;
	}
	return 0;
}

SPI spi;