libyggdrasil  v1.0.0
i2c.hpp
Go to the documentation of this file.
1  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  * _____.___. .___ .__.__ *
3  * \__ | | ____ ____ __| _/___________ _____|__| | *
4  * / | |/ ___\ / ___\ / __ |\_ __ \__ \ / ___/ | | *
5  * \____ / /_/ > /_/ > /_/ | | | \// __ \_\___ \| | |__ *
6  * / ______\___ /\___ /\____ | |__| (____ /____ >__|____/ *
7  * \/ /_____//_____/ \/ \/ \/ *
8  * - Asgard - *
9  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
10  * This software can be used by students and other personal of the *
11  * Bern University of Applied Sciences under the terms of the MIT *
12  * license. *
13  * For other persons this software is under the terms of the GNU *
14  * General Public License version 2. *
15  * *
16  * Copyright © 2021, Bern University of Applied Sciences. *
17  * All rights reserved. *
18  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
26 #pragma once
27 
29 
30 #include <string>
31 #include <array>
32 
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <sys/ioctl.h>
36 #include <sys/stat.h>
37 #include <linux/i2c-dev.h>
38 
39 namespace bsp::asg::drv {
40 
47  template<u16 InterfaceNumber>
48  struct I2C {
49 
55  static bool init() {
56  I2C::s_fileHandle = open(("/dev/i2c-" + std::to_string(InterfaceNumber)).c_str(), O_RDWR);
57  return I2C::s_fileHandle != -1;
58  }
59 
65  static bool deinit() {
66  close(I2C::s_fileHandle);
67  return true;
68  }
69 
77  template<size_t N>
78  static void read(u8 address, std::array<u8, N> &data) {
79  ::ioctl(I2C::s_fileHandle, I2C_SLAVE, address >> 1);
80  ::read(I2C::s_fileHandle, data.data(), N);
81  }
82 
90  template<size_t N>
91  static void write(u8 address, const std::array<u8, N> &data) {
92  ::ioctl(I2C::s_fileHandle, I2C_SLAVE, address >> 1);
93  ::write(I2C::s_fileHandle, data.data(), N);
94  }
95 
96  private:
97  static inline int s_fileHandle = -1;
98  };
99 
100 }
bsp::asg::drv::I2C::write
static void write(u8 address, const std::array< u8, N > &data)
I2C write.
Definition: i2c.hpp:91
bsp::asg::drv
Definition: display.hpp:60
u8
uint8_t u8
Unsigned integer definitions.
Definition: types.h:36
i2c.hpp
Frontend for the I2C abstraction.
bsp::asg::drv::I2C::deinit
static bool deinit()
Deinit function.
Definition: i2c.hpp:65
bsp::asg::drv::I2C
I2C implementation for Asgard.
Definition: i2c.hpp:48
bsp::asg::drv::I2C::init
static bool init()
Init function.
Definition: i2c.hpp:55
bsp::asg::drv::I2C::read
static void read(u8 address, std::array< u8, N > &data)
I2C receive.
Definition: i2c.hpp:78