]> git.donarmstrong.com Git - qmk_firmware.git/blob - keyboards/winkeyless/bface/i2c.c
c27f3e3d17e1c2393d8a56269b05f7a025245240
[qmk_firmware.git] / keyboards / winkeyless / bface / i2c.c
1 /*
2 Copyright 2016 Luiz Ribeiro <luizribeiro@gmail.com>
3
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.
8
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.
13
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/>.
16 */
17
18 #include <avr/io.h>
19 #include <util/twi.h>
20
21 #include "i2c.h"
22
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;
27     }
28     TWBR = bitrate_div;
29 }
30
31 void i2c_init(void) {
32     // set pull-up resistors on I2C bus pins
33     PORTC |= 0b11;
34
35     i2c_set_bitrate(400);
36
37     // enable TWI (two-wire interface)
38     TWCR |= (1 << TWEN);
39
40     // enable TWI interrupt and slave address ACK
41     TWCR |= (1 << TWIE);
42     TWCR |= (1 << TWEA);
43 }
44
45 uint8_t i2c_start(uint8_t address) {
46     // reset TWI control register
47     TWCR = 0;
48
49     // begin transmission and wait for it to end
50     TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
51     while (!(TWCR & (1<<TWINT)));
52
53     // check if the start condition was successfully transmitted
54     if ((TWSR & 0xF8) != TW_START) {
55         return 1;
56     }
57
58     // transmit address and wait
59     TWDR = address;
60     TWCR = (1<<TWINT) | (1<<TWEN);
61     while (!(TWCR & (1<<TWINT)));
62
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)) {
66         return 1;
67     }
68
69     return 0;
70 }
71
72 void i2c_stop(void) {
73     TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
74 }
75
76 uint8_t i2c_write(uint8_t data) {
77     TWDR = data;
78
79     // transmit data and wait
80     TWCR = (1<<TWINT) | (1<<TWEN);
81     while (!(TWCR & (1<<TWINT)));
82
83     if ((TWSR & 0xF8) != TW_MT_DATA_ACK) {
84         return 1;
85     }
86
87     return 0;
88 }
89
90 uint8_t i2c_send(uint8_t address, uint8_t *data, uint16_t length) {
91     if (i2c_start(address)) {
92         return 1;
93     }
94
95     for (uint16_t i = 0; i < length; i++) {
96         if (i2c_write(data[i])) {
97             return 1;
98         }
99     }
100
101     i2c_stop();
102
103     return 0;
104 }