2 * Copyright Droids Corporation (2008)
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 2 of the License, or
7 * (at your option) any later version.
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.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * Host wrapper for SPI
25 #include <aversive/parts.h>
26 #include <aversive/error.h>
32 #include <spi_config.h>
35 static volatile uint8_t g_ss_number;
36 static volatile spi_mode_t g_spi_mode;
37 static volatile uint8_t g_slave_selected;
38 static volatile uint8_t g_spi_order;
39 static volatile spi_format_t g_spi_format;
40 static volatile spi_mode_t g_spi_mode;
41 static volatile spi_clk_rate_t g_spi_clk_rate;
44 * Register a pin as SS line
45 * Returns a unique identifier, or -1 on error
46 * There is always the physical SS line registered as 0
48 int8_t spi_register_ss_line(volatile uint8_t *port, uint8_t bitnum)
50 DEBUG(E_SPI, "Trying to register new SS line: port 0x%x, bitnum %d", port, bitnum);
51 /* too much SS lines (try to change SPI_MAX_SLAVES) */
52 if (g_ss_number >= SPI_MAX_SLAVES+1)
55 NOTICE(E_SPI, "New Slave Line registered: %d", g_ss_number);
61 * Set data order (default: MSB first)
63 void spi_set_data_order(uint8_t order)
71 uint8_t spi_get_data_order(void)
80 void spi_init(spi_mode_t mode, spi_format_t format, spi_clk_rate_t clk_rate)
82 NOTICE(E_SPI, "Init SPI: mode %d, format %d, clk_rate %d",
83 mode, format, clk_rate);
85 /* SS pin is not driven by SPI hardware
86 * This is taken care of by spi_register_ss_line()
87 * EVEN for the "default" SS line */
89 g_spi_format = format;
90 g_spi_clk_rate = clk_rate;
91 g_slave_selected = FALSE;
92 g_spi_mode = SPI_MODE_MASTER;
93 NOTICE(E_SPI, "Init done");
97 * Returns the state of SPI
99 inline spi_mode_t spi_get_mode(void)
105 * Send a byte (and receive one)
106 * Returns the received byte
108 uint8_t spi_send_and_receive_byte(uint8_t byte)
115 * Send a byte, discard the result
117 inline void spi_send_byte(uint8_t byte)
119 spi_send_and_receive_byte(byte);
123 * Receives a byte (sends a NULL)
125 uint8_t spi_receive_byte(void)
127 return spi_send_and_receive_byte(0x00);
131 * Activates the selected SS line
133 uint8_t spi_slave_select(uint8_t slave)
135 if (g_slave_selected) {
136 ERROR(E_SPI, "A slave is already selected !");
141 g_slave_selected = TRUE;
146 * Desactivates the selected SS line
148 void spi_slave_deselect(uint8_t slave)
151 g_slave_selected = FALSE;
157 void spi_display_ss_lines(void)