3 * Copyright 2007 Free Software Foundation, Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "memory_map.h"
23 #define MAX_WB_DIV 4 // maximum wishbone divisor (from 100 MHz MASTER_CLK)
25 // prescaler divisor values for 100 kHz I2C [uses 5 * SCLK internally]
27 #define PRESCALER(wb_div) (((MASTER_CLK_RATE/(wb_div)) / (5 * 100000)) - 1)
29 static uint16_t prescaler_values[MAX_WB_DIV+1] = {
30 0xffff, // 0: can't happen
31 PRESCALER(1), // 1: 100 MHz
32 PRESCALER(2), // 2: 50 MHz
33 PRESCALER(3), // 3: 33.333 MHz
34 PRESCALER(4), // 4: 25 MHz
40 i2c_regs->ctrl = 0; // disable core
42 // setup prescaler depending on wishbone divisor
43 int wb_div = hwconfig_wishbone_divisor();
44 if (wb_div > MAX_WB_DIV)
47 i2c_regs->prescaler_lo = prescaler_values[wb_div] & 0xff;
48 i2c_regs->prescaler_hi = (prescaler_values[wb_div] >> 8) & 0xff;
50 i2c_regs->ctrl = I2C_CTRL_EN; // enable core
52 // FIXME interrupt driven?
58 while (i2c_regs->cmd_status & I2C_ST_TIP) // wait for xfer to complete
67 if ((i2c_regs->cmd_status & I2C_ST_RXACK) != 0){ // target NAK'd
74 i2c_read (unsigned char i2c_addr, unsigned char *buf, unsigned int len)
76 if (len == 0) // reading zero bytes always works
79 while (i2c_regs->cmd_status & I2C_ST_BUSY)
82 i2c_regs->data = (i2c_addr << 1) | 1; // 7 bit address and read bit (1)
83 // generate START and write addr
84 i2c_regs->cmd_status = I2C_CMD_WR | I2C_CMD_START;
88 for (; len > 0; buf++, len--){
89 i2c_regs->cmd_status = I2C_CMD_RD | (len == 1 ? (I2C_CMD_NACK | I2C_CMD_STOP) : 0);
91 *buf = i2c_regs->data;
96 i2c_regs->cmd_status = I2C_CMD_STOP; // generate STOP
102 i2c_write(unsigned char i2c_addr, const unsigned char *buf, unsigned int len)
104 while (i2c_regs->cmd_status & I2C_ST_BUSY)
107 i2c_regs->data = (i2c_addr << 1) | 0; // 7 bit address and write bit (0)
109 // generate START and write addr (and maybe STOP)
110 i2c_regs->cmd_status = I2C_CMD_WR | I2C_CMD_START | (len == 0 ? I2C_CMD_STOP : 0);
114 for (; len > 0; buf++, len--){
115 i2c_regs->data = *buf;
116 i2c_regs->cmd_status = I2C_CMD_WR | (len == 1 ? I2C_CMD_STOP : 0);
123 i2c_regs->cmd_status = I2C_CMD_STOP; // generate STOP