/* * Copyright (c) 2010, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /** * \file * i2c core functions * \author * Robert Olsson */ #include #include #include #include #include "dev/watchdog.h" #include "contiki.h" #include "i2c.h" #include #include #include #include "dev/co2_sa_kxx-sensor.h" void i2c_init(uint32_t speed) { /* initialize TWI clock: 100 kHz clock, TWPS = 0 => prescaler = 1 */ TWSR = 0; /* no prescaler */ TWBR = ((F_CPU / speed) - 16) / 2; /* must be > 10 for stable operation */ } uint8_t i2c_start(uint8_t addr) { uint8_t twst; uint32_t n; /* Send START condition */ TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); /* Wait until transmission completed */ for(n = 0; n < 100000 && !(TWCR & (1 << TWINT)); n++) { } if(n >= 100000) { return 1; } /* check value of TWI Status Register. Mask prescaler bits. */ twst = TW_STATUS & 0xF8; if((twst != TW_START) && (twst != TW_REP_START)) { return 1; } /* send device address */ TWDR = addr; TWCR = (1 << TWINT) | (1 << TWEN); /* wail until transmission completed and ACK/NACK has been received */ for(n = 0; n < 100000 && !(TWCR & (1 << TWINT)); n++) { } if(n >= 100000) { return 1; } /* check value of TWI Status Register. Mask prescaler bits. */ twst = TW_STATUS & 0xF8; if((twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK)) { return 1; } return 0; } void i2c_start_wait(uint8_t addr) { uint8_t twst; while ( 1 ) { // send START condition TWCR = (1<