summaryrefslogtreecommitdiffstats
path: root/firmware/zpu/lib/spi.c
blob: de3645fe3cac37bda02701ddf7c83011c4b80925 (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
57
58
/*
 * Copyright 2012 Ettus Research LLC
 * Copyright 2007,2008 Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "spi.h"
#include "memory_map.h"
#include "nonstdio.h"
#include "mdelay.h"

void spi_init(void)
{
  spi_core->divider = 100;
}

void spi_wait(void)
{
  //assumption that divider is reasonably small
  mdelay(1);
}

uint32_t spi_transact(bool readback, int slave, uint32_t data, int length, uint32_t flags)
{
    uint32_t control_word = 0;
    control_word |= (slave << SPI_CORE_SLAVE_SELECT_SHIFT);
    control_word |= (length << SPI_CORE_NUM_BITS_SHIFT);
    if ((flags & SPI_PUSH_RISE)  != 0) control_word |= (1 << SPI_CORE_DATA_IN_EDGE_SHIFT);
    if ((flags & SPI_PUSH_FALL)  != 0) control_word |= (0 << SPI_CORE_DATA_IN_EDGE_SHIFT);
    if ((flags & SPI_LATCH_RISE) != 0) control_word |= (1 << SPI_CORE_DATA_OUT_EDGE_SHIFT);
    if ((flags & SPI_LATCH_FALL) != 0) control_word |= (0 << SPI_CORE_DATA_OUT_EDGE_SHIFT);

    uint32_t data_out_rev = 0;
    for (size_t i = 0; i < length; i++){
        const int bit = ((data >> i) & 0x1);
        data_out_rev |= (bit << (length - i - 1));
    }

    spi_wait();
    spi_core->control = control_word;
    spi_core->data = data_out_rev;

    if (readback) spi_wait();

    return readback_mux->spi;
}