mbed library with additional peripherals for ST F401 board

Fork of mbed-src by mbed official

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers I2C.cpp Source File

I2C.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2013 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 #include "I2C.h"
00017 
00018 #if DEVICE_I2C
00019 
00020 namespace mbed {
00021 
00022 I2C *I2C::_owner = NULL;
00023 
00024 I2C::I2C(PinName sda, PinName scl) {
00025     // The init function also set the frequency to 100000
00026     i2c_init(&_i2c, sda, scl);
00027     _hz = 100000;
00028 
00029     // Used to avoid unnecessary frequency updates
00030     _owner = this;
00031 }
00032 
00033 void I2C::frequency(int hz) {
00034     _hz = hz;
00035 
00036     // We want to update the frequency even if we are already the bus owners
00037     i2c_frequency(&_i2c, _hz);
00038 
00039     // Updating the frequency of the bus we become the owners of it
00040     _owner = this;
00041 }
00042 
00043 void I2C::aquire() {
00044     if (_owner != this) {
00045         i2c_frequency(&_i2c, _hz);
00046         _owner = this;
00047     }
00048 }
00049 
00050 // write - Master Transmitter Mode
00051 int I2C::write(int address, const char* data, int length, bool repeated) {
00052     aquire();
00053 
00054     int stop = (repeated) ? 0 : 1;
00055     int written = i2c_write(&_i2c, address, data, length, stop);
00056 
00057     return length != written;
00058 }
00059 
00060 int I2C::write(int data) {
00061     return i2c_byte_write(&_i2c, data);
00062 }
00063 
00064 // read - Master Reciever Mode
00065 int I2C::read(int address, char* data, int length, bool repeated) {
00066     aquire();
00067 
00068     int stop = (repeated) ? 0 : 1;
00069     int read = i2c_read(&_i2c, address, data, length, stop);
00070 
00071     return length != read;
00072 }
00073 
00074 int I2C::read(int ack) {
00075     if (ack) {
00076         return i2c_byte_read(&_i2c, 0);
00077     } else {
00078         return i2c_byte_read(&_i2c, 1);
00079     }
00080 }
00081 
00082 void I2C::start(void) {
00083     i2c_start(&_i2c);
00084 }
00085 
00086 void I2C::stop(void) {
00087     i2c_stop(&_i2c);
00088 }
00089 
00090 } // namespace mbed
00091 
00092 #endif