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/>.
18 // Please do not modify this file
25 void i2c_set_bitrate(uint16_t bitrate_khz) {
26 uint8_t bitrate_div = ((F_CPU / 1000l) / bitrate_khz);
27 if (bitrate_div >= 16) {
28 bitrate_div = (bitrate_div - 16) / 2;
34 // set pull-up resistors on I2C bus pins
39 // enable TWI (two-wire interface)
42 // enable TWI interrupt and slave address ACK
47 uint8_t i2c_start(uint8_t address) {
48 // reset TWI control register
51 // begin transmission and wait for it to end
52 TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
53 while (!(TWCR & (1<<TWINT)));
55 // check if the start condition was successfully transmitted
56 if ((TWSR & 0xF8) != TW_START) {
60 // transmit address and wait
62 TWCR = (1<<TWINT) | (1<<TWEN);
63 while (!(TWCR & (1<<TWINT)));
65 // check if the device has acknowledged the READ / WRITE mode
66 uint8_t twst = TW_STATUS & 0xF8;
67 if ((twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK)) {
75 TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
78 uint8_t i2c_write(uint8_t data) {
81 // transmit data and wait
82 TWCR = (1<<TWINT) | (1<<TWEN);
83 while (!(TWCR & (1<<TWINT)));
85 if ((TWSR & 0xF8) != TW_MT_DATA_ACK) {
92 uint8_t i2c_send(uint8_t address, uint8_t *data, uint16_t length) {
93 if (i2c_start(address)) {
97 for (uint16_t i = 0; i < length; i++) {
98 if (i2c_write(data[i])) {