X-Git-Url: http://cloudbase.mooo.com/gitweb/z180-stamp.git/blobdiff_plain/61b0cfe9df810db4fbca78e5f880d61c5063f324..7f552300815ccadd45ebb3e7f0ae72a3b2e0c4e5:/avr/i2c.c diff --git a/avr/i2c.c b/avr/i2c.c index df97fea..d181ff6 100644 --- a/avr/i2c.c +++ b/avr/i2c.c @@ -1,11 +1,10 @@ -/* - * I2C (TWI) master interface. +/* + * I2C (TWI) master interface. */ #include "common.h" #include -#include #include #include "config.h" @@ -13,9 +12,11 @@ #include "debug.h" #include "i2c.h" -#ifdef DEBUG -//# define DEBUG_I2C -#endif +#define DEBUG_I2C 0 + +#define debug_i2c(fmt, args...) \ + debug_cond(DEBUG_I2C, fmt, ##args) + /* General TWI Master status codes */ #define TWI_START 0x08 /* START has been transmitted */ @@ -46,33 +47,33 @@ * TWSTO: TWI STOP Condition Bit * TWEN: TWI Enable Bit * TWIE: TWI Interrupt Enable - * + * * (1< 255) { - tmptwbr >>= 4; + uint32_t tmp_twbr = F_CPU /2 / speed - 8; + + while (tmp_twbr > 255) { + tmp_twbr >>= 4; twps += 1; } - debug_cond((twps > 3), "TWCLK too low: %lu Hz\n", speed); + debug_cond((twps > 3), "*** TWCLK too low: %lu Hz\n", speed); - twbr = (uint8_t) tmptwbr; + twbr = (uint8_t) tmp_twbr; + + PRR0 &= ~_BV(PRTWI); _init(); } @@ -251,7 +240,7 @@ int_fast8_t i2c_waitready(void) { uint32_t timer = get_timer(0); uint8_t timeout = 0; - + do { if (get_timer(timer) >= 30) { timeout = TIMEOUT; @@ -261,14 +250,14 @@ int_fast8_t i2c_waitready(void) xmit.stat |= timeout; -#ifdef DEBUG_I2C +#if DEBUG_I2C dump_ram((uint8_t *) &xmit, 4, "=== i2c_wait ready: (done)"); _delay_ms(30); -#endif +#endif return xmit.stat; } -//static +static int i2c_send(uint8_t chip, uint16_t addr, uint8_t alen, uint8_t *buffer, int8_t len) { uint8_t i, n; @@ -287,11 +276,11 @@ int i2c_send(uint8_t chip, uint16_t addr, uint8_t alen, uint8_t *buffer, int8_t for (n = len + i; i < n; i++) xmit.buf[i] = *buffer++; xmit.len = i; - -#ifdef DEBUG_I2C + +#if DEBUG_I2C dump_ram((uint8_t *) &xmit, 0x20, "=== i2c_send"); _delay_ms(30); -#endif +#endif /* Enable TWI, TWI int and initiate start condition */ TWCR = (1< 2) || (1 + alen + len > CONFIG_SYS_I2C_BUFSIZE)) { debug("** i2c_write: buffer overflow, alen: %u, len: %u\n", alen, len); return -1; } - + i2c_send(chip, addr, alen, buffer, len); rc = i2c_waitready(); - debug("** i2c_write: result=0x%02x\n",rc); return (rc & XMIT_DONE) != 0; } @@ -375,12 +363,11 @@ int i2c_read(uint8_t chip, unsigned int addr, uint_fast8_t alen, alen, len); return -1; } - + if (alen != 0) { i2c_send(chip, addr, alen, NULL, 0); - } + } rc = i2c_recv(chip, buffer, len); - debug("** i2c_read: result=0x%02x\n",rc); return !((rc & (XMIT_DONE|DATA_ACK)) == (XMIT_DONE|DATA_ACK)); }