libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
esp_dac.hpp
1#pragma once
2
3#include "esp_def.hpp"
4
5#include <cstdint>
6
7#include "dac.hpp"
8#include "soc/soc_caps.h"
9
10#if SOC_DAC_SUPPORTED
11#include "driver/gpio.h"
12#include "esp_private/gpio.h"
13#include "hal/dac_ll.h"
14#include "soc/dac_periph.h"
15#endif
16
17namespace LibXR
18{
19
20class ESP32DAC : public DAC
21{
22 public:
23 explicit ESP32DAC(uint8_t channel_id = 0, float init_voltage = 0.0f,
24 float reference_voltage = 3.3f)
25 : channel_id_(channel_id), reference_voltage_(reference_voltage)
26 {
27#if SOC_DAC_SUPPORTED
28 if ((channel_id_ >= SOC_DAC_CHAN_NUM) || (reference_voltage_ <= 0.0f))
29 {
30 return;
31 }
32
33 ready_ = true;
34 dac_ll_power_on(ToChannel(channel_id_));
35 dac_ll_rtc_sync_by_adc(false);
36 (void)gpio_config_as_analog(
37 static_cast<gpio_num_t>(dac_periph_signal.dac_channel_io_num[channel_id_]));
38 (void)Write(init_voltage);
39#else
40 (void)init_voltage;
41#endif
42 }
43
44
45 ErrorCode Write(float voltage) override
46 {
47#if SOC_DAC_SUPPORTED
48 if (!ready_)
49 {
51 }
52
53 if (voltage < 0.0f)
54 {
55 voltage = 0.0f;
56 }
57 else if (voltage > reference_voltage_)
58 {
59 voltage = reference_voltage_;
60 }
61
62 constexpr uint32_t kMaxCode = (1U << SOC_DAC_RESOLUTION) - 1U;
63 const float scale = static_cast<float>(kMaxCode) / reference_voltage_;
64 uint32_t code = static_cast<uint32_t>((voltage * scale) + 0.5f);
65 if (code > kMaxCode)
66 {
67 code = kMaxCode;
68 }
69
70 dac_ll_update_output_value(ToChannel(channel_id_), static_cast<uint8_t>(code));
71 return ErrorCode::OK;
72#else
73 (void)voltage;
75#endif
76 }
77
78 private:
79#if SOC_DAC_SUPPORTED
80 static dac_channel_t ToChannel(uint8_t channel_id)
81 {
82 return channel_id == 0 ? DAC_CHAN_0 : DAC_CHAN_1;
83 }
84#endif
85
86 uint8_t channel_id_;
87 float reference_voltage_;
88 bool ready_ = false;
89};
90
91} // namespace LibXR
数字模拟转换器(DAC)基类
Definition dac.hpp:18
ErrorCode Write(float voltage) override
输出 DAC 电压
Definition esp_dac.hpp:45
LibXR 命名空间
Definition ch32_can.hpp:14
ErrorCode
定义错误码枚举
Definition libxr_def.hpp:64
@ NOT_SUPPORT
不支持 | Not supported
@ OK
操作成功 | Operation successful