2 * Copyright © 2011 Keith Packard <keithp@keithp.com>
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, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
22 * Atmega32u4 TWI master mode (I2C)
27 /* Send bytes over I2C.
29 * This just polls; the I2C is set to go as fast as possible,
30 * so using interrupts would take way too long
33 ao_i2c_send(void *block, uint16_t len)
37 ao_mutex_get(&ao_i2c_mutex);
39 while (!(UCSR1A & (1 << UDRE1)));
41 while (!(UCSR1A & (1 << RXC1)));
44 ao_mutex_put(&ao_i2c_mutex);
47 /* Receive bytes over I2C.
49 * This sets up tow DMA engines, one reading the data and another
50 * writing constant values to the I2C transmitter as that is what
51 * clocks the data coming in.
54 ao_i2c_recv(void *block, uint16_t len)
58 ao_mutex_get(&ao_i2c_mutex);
60 while (!(UCSR1A & (1 << UDRE1)));
62 while (!(UCSR1A & (1 << RXC1)));
65 ao_mutex_put(&ao_i2c_mutex);
69 #define XCK1_PORT PORTD
72 #define XMS1_PORT PORTE
78 /* Ensure the TWI is powered */
83 XCK1_DDR |= (1 << XCK1);
85 /* Clear chip select (which is negated) */
86 XMS1_PORT |= (1 < XMS1);
87 XMS1_DDR |= (1 << XMS1);
89 /* Set baud register to zero (required before turning transmitter on) */
92 UCSR1C = ((0x3 << UMSEL10) | /* Master I2C mode */
93 (0 << UCSZ10) | /* I2C mode 0 */
94 (0 << UCPOL1)); /* I2C mode 0 */
96 /* Enable transmitter and receiver */
97 UCSR1B = ((1 << RXEN1) |
100 /* It says that 0 is a legal value; we'll see... */