2 Copyright 2016 Luiz Ribeiro <luizribeiro@gmail.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,
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, see <http://www.gnu.org/licenses/>.
23 void i2c_set_bitrate(uint16_t bitrate_khz) {
24 uint8_t bitrate_div = ((F_CPU / 1000l) / bitrate_khz);
25 if (bitrate_div >= 16) {
26 bitrate_div = (bitrate_div - 16) / 2;
32 // set pull-up resistors on I2C bus pins
37 // enable TWI (two-wire interface)
40 // enable TWI interrupt and slave address ACK
45 uint8_t i2c_start(uint8_t address) {
46 // reset TWI control register
49 // begin transmission and wait for it to end
50 TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
51 while (!(TWCR & (1<<TWINT)));
53 // check if the start condition was successfully transmitted
54 if ((TWSR & 0xF8) != TW_START) {
58 // transmit address and wait
60 TWCR = (1<<TWINT) | (1<<TWEN);
61 while (!(TWCR & (1<<TWINT)));
63 // check if the device has acknowledged the READ / WRITE mode
64 uint8_t twst = TW_STATUS & 0xF8;
65 if ((twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK)) {
73 TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
76 uint8_t i2c_write(uint8_t data) {
79 // transmit data and wait
80 TWCR = (1<<TWINT) | (1<<TWEN);
81 while (!(TWCR & (1<<TWINT)));
83 if ((TWSR & 0xF8) != TW_MT_DATA_ACK) {
90 uint8_t i2c_send(uint8_t address, uint8_t *data, uint16_t length) {
91 if (i2c_start(address)) {
95 for (uint16_t i = 0; i < length; i++) {
96 if (i2c_write(data[i])) {