MycilaJSY 13.0.0
Arduino / ESP32 library for the JSY1031, JSY-MK-163, JSY-MK-193, JSY-MK-194, JSY-MK-227, JSY-MK-229, JSY-MK-333 families single-phase and three-phase AC bidirectional meters from Shenzhen Jiansiyan Technologies Co, Ltd.
Loading...
Searching...
No Matches
MycilaDimmerPWM.h
1// SPDX-License-Identifier: MIT
2/*
3 * Copyright (C) 2023-2025 Mathieu Carbou
4 */
5#pragma once
6
7#include "MycilaDimmer.h"
8
9#define MYCILA_DIMMER_PWM_RESOLUTION 12 // 12 bits resolution => 0-4095 watts
10#define MYCILA_DIMMER_PWM_FREQUENCY 1000 // 1 kHz
11
12namespace Mycila {
16 class PWMDimmer : public Dimmer {
17 public:
18 virtual ~PWMDimmer() { end(); }
19
23 void setPin(gpio_num_t pin) { _pin = pin; }
24
28 gpio_num_t getPin() const { return _pin; }
29
33 void setFrequency(uint32_t frequency) { this->_frequency = frequency; }
34
38 uint32_t getFrequency() const { return _frequency; }
39
43 void setResolution(uint8_t resolution) { this->_resolution = resolution; }
44
48 uint8_t getResolution() const { return _resolution; }
49
56 void begin() override;
57
63 void end() override;
64
65 const char* type() const override { return "pwm"; }
66
67 bool calculateMetrics(Metrics& metrics, float gridVoltage, float loadResistance) const override {
68 return isEnabled() && _calculatePhaseControlMetrics(metrics, _dutyCycleFire, gridVoltage, loadResistance);
69 }
70
71#ifdef MYCILA_JSON_SUPPORT
77 void toJson(const JsonObject& root) const override {
78 Dimmer::toJson(root);
79 root["pwm_pin"] = static_cast<int>(_pin);
80 root["pwm_frequency"] = _frequency;
81 root["pwm_resolution"] = _resolution;
82 }
83#endif
84
85 protected:
86 bool _apply() override {
87 if (!_online) {
88 return ledcWrite(_pin, 0);
89 }
90 uint32_t duty = _dutyCycleFire * ((1 << _resolution) - 1);
91 return ledcWrite(_pin, duty);
92 }
93
94 bool _calculateHarmonics(float* array, size_t n) const override {
95 return _calculatePhaseControlHarmonics(_dutyCycleFire, array, n);
96 }
97
98 private:
99 gpio_num_t _pin = GPIO_NUM_NC;
100 uint32_t _frequency = MYCILA_DIMMER_PWM_FREQUENCY;
101 uint8_t _resolution = MYCILA_DIMMER_PWM_RESOLUTION;
102 };
103} // namespace Mycila
bool isEnabled() const
Check if the dimmer is enabled (if it was able to initialize correctly)
PWM based dimmer implementation for voltage regulators controlled by a PWM signal to 0-10V analog con...
void setPin(gpio_num_t pin)
Set the GPIO pin to use for the dimmer.
void setResolution(uint8_t resolution)
Set the PWM resolution in bits.
void setFrequency(uint32_t frequency)
Set the PWM frequency in Hz.
uint8_t getResolution() const
Get the PWM resolution in bits.
void end() override
Disable the dimmer.
gpio_num_t getPin() const
Get the GPIO pin used for the dimmer.
void begin() override
Enable a dimmer on a specific GPIO pin.
uint32_t getFrequency() const
Get the PWM frequency in Hz.