Imported Upstream version 3.2.2
[debian/gnuradio] / usrp2 / firmware / lib / spi.c
1 /*
2  * Copyright 2007,2008 Free Software Foundation, Inc.
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include "spi.h"
19 #include "memory_map.h"
20
21 void
22 spi_init(void) 
23 {
24   /*
25    * f_sclk = f_wb / ((div + 1) * 2)
26    */
27   spi_regs->div = 1;  // 0 = Div by 2 (25 MHz); 1 = Div-by-4 (12.5 MHz)
28 }
29
30 void
31 spi_wait(void) 
32 {
33   while (spi_regs->ctrl & SPI_CTRL_GO_BSY)
34     ;
35 }
36
37 uint32_t
38 spi_transact(bool readback, int slave, uint32_t data, int length, uint32_t flags) 
39 {
40   flags &= (SPI_CTRL_TXNEG | SPI_CTRL_RXNEG);
41   int ctrl = SPI_CTRL_ASS | (SPI_CTRL_CHAR_LEN_MASK & length) | flags;
42
43   spi_wait();
44
45   // Tell it which SPI slave device to access
46   spi_regs->ss = slave & 0xff;
47
48   // Data we will send
49   spi_regs->txrx0 = data;
50
51   // Run it -- write once and rewrite with GO set
52   spi_regs->ctrl = ctrl;
53   spi_regs->ctrl = ctrl | SPI_CTRL_GO_BSY;
54
55   if(readback) {
56     spi_wait();
57     return spi_regs->txrx0;
58   }
59   else
60     return 0;
61 }