tutrcos
読み取り中…
検索中…
一致する文字列を見つけられません
i2c_master.hpp
[詳解]
1#pragma once
2
3#include "main.h"
4
5#include <cstddef>
6#include <cstdint>
7#include <mutex>
8
9#include "tutrcos/core.hpp"
10
11namespace tutrcos {
12namespace peripheral {
13
14class I2CMaster {
15public:
16 I2CMaster(I2C_HandleTypeDef *hi2c) : hi2c_{hi2c} {}
17
18 bool transmit(uint16_t address, uint8_t *data, size_t size,
19 uint32_t timeout) {
20 std::lock_guard lock{mtx_};
21 if (HAL_I2C_Master_Transmit_IT(hi2c_, address << 1, data, size) != HAL_OK) {
22 return false;
23 }
24 uint32_t start = core::Kernel::get_ticks();
25 while (hi2c_->State != HAL_I2C_STATE_READY) {
26 uint32_t elapsed = core::Kernel::get_ticks() - start;
27 if (elapsed >= timeout) {
28 return false;
29 }
31 }
32 return true;
33 }
34
35 bool receive(uint16_t address, uint8_t *data, size_t size, uint32_t timeout) {
36 std::lock_guard lock{mtx_};
37 uint32_t start = core::Kernel::get_ticks();
38 if (HAL_I2C_Master_Receive_IT(hi2c_, address << 1, data, size) != HAL_OK) {
39 return false;
40 }
41 while (hi2c_->State != HAL_I2C_STATE_READY) {
42 uint32_t elapsed = core::Kernel::get_ticks() - start;
43 if (elapsed >= timeout) {
44 return false;
45 }
47 }
48 return true;
49 }
50
51 I2C_HandleTypeDef *get_hal_handle() { return hi2c_; }
52
53private:
54 I2C_HandleTypeDef *hi2c_;
55 core::Mutex mtx_;
56};
57
58} // namespace peripheral
59} // namespace tutrcos
static uint32_t get_ticks()
Definition kernel.hpp:14
Definition mutex.hpp:12
static void delay(uint32_t ticks)
Definition thread.hpp:32
Definition i2c_master.hpp:14
I2CMaster(I2C_HandleTypeDef *hi2c)
Definition i2c_master.hpp:16
I2C_HandleTypeDef * get_hal_handle()
Definition i2c_master.hpp:51
bool receive(uint16_t address, uint8_t *data, size_t size, uint32_t timeout)
Definition i2c_master.hpp:35
bool transmit(uint16_t address, uint8_t *data, size_t size, uint32_t timeout)
Definition i2c_master.hpp:18
Definition kernel.hpp:7