]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/mbed/common/I2C.cpp
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / mbed / common / I2C.cpp
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2013 ARM Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "I2C.h"
17
18 #if DEVICE_I2C
19
20 namespace mbed {
21
22 I2C *I2C::_owner = NULL;
23
24 I2C::I2C(PinName sda, PinName scl) : _i2c(), _hz(100000) {
25     // The init function also set the frequency to 100000
26     i2c_init(&_i2c, sda, scl);
27
28     // Used to avoid unnecessary frequency updates
29     _owner = this;
30 }
31
32 void I2C::frequency(int hz) {
33     _hz = hz;
34
35     // We want to update the frequency even if we are already the bus owners
36     i2c_frequency(&_i2c, _hz);
37
38     // Updating the frequency of the bus we become the owners of it
39     _owner = this;
40 }
41
42 void I2C::aquire() {
43     if (_owner != this) {
44         i2c_frequency(&_i2c, _hz);
45         _owner = this;
46     }
47 }
48
49 // write - Master Transmitter Mode
50 int I2C::write(int address, const char* data, int length, bool repeated) {
51     aquire();
52
53     int stop = (repeated) ? 0 : 1;
54     int written = i2c_write(&_i2c, address, data, length, stop);
55
56     return length != written;
57 }
58
59 int I2C::write(int data) {
60     return i2c_byte_write(&_i2c, data);
61 }
62
63 // read - Master Reciever Mode
64 int I2C::read(int address, char* data, int length, bool repeated) {
65     aquire();
66
67     int stop = (repeated) ? 0 : 1;
68     int read = i2c_read(&_i2c, address, data, length, stop);
69
70     return length != read;
71 }
72
73 int I2C::read(int ack) {
74     if (ack) {
75         return i2c_byte_read(&_i2c, 0);
76     } else {
77         return i2c_byte_read(&_i2c, 1);
78     }
79 }
80
81 void I2C::start(void) {
82     i2c_start(&_i2c);
83 }
84
85 void I2C::stop(void) {
86     i2c_stop(&_i2c);
87 }
88
89 } // namespace mbed
90
91 #endif