1/*
2 * esp32 / esp-idf pwm
3 *
4 * Copyright (C) 2019 - 2020 Andy Green <andy@warmcat.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 * IN THE SOFTWARE.
23 */
24
25#include "private-lib-core.h"
26#include "soc/ledc_reg.h"
27#include "driver/ledc.h"
28
29#define _LEDC_HIGH_SPEED_MODE 0
30
31static const ledc_timer_config_t tc = {
32	.speed_mode             	= _LEDC_HIGH_SPEED_MODE,
33	.duty_resolution        	= LEDC_TIMER_13_BIT,
34	.timer_num              	= LEDC_TIMER_0,
35	.freq_hz                	= 5000,
36	.clk_cfg                	= LEDC_AUTO_CLK
37};
38
39int
40lws_pwm_plat_init(const struct lws_pwm_ops *lo)
41{
42	ledc_channel_config_t lc = {
43		.duty			= 8191,
44		.intr_type		= LEDC_INTR_FADE_END,
45		.speed_mode		= _LEDC_HIGH_SPEED_MODE,
46		.timer_sel		= LEDC_TIMER_0,
47	};
48	size_t n;
49
50        ledc_timer_config(&tc);
51
52        for (n = 0; n < lo->count_pwm_map; n++) {
53        	lc.channel = LEDC_CHANNEL_0 + lo->pwm_map[n].index;
54        	lc.gpio_num = lo->pwm_map[n].gpio;
55        	ledc_channel_config(&lc);
56                ledc_set_duty(_LEDC_HIGH_SPEED_MODE, lc.channel, 0);
57                ledc_update_duty(_LEDC_HIGH_SPEED_MODE, lc.channel);
58        }
59
60	return 0;
61}
62
63void
64lws_pwm_plat_intensity(const struct lws_pwm_ops *lo, _lws_plat_gpio_t gpio,
65		       lws_led_intensity_t inten)
66{
67	size_t n;
68
69	for (n = 0; n < lo->count_pwm_map; n++) {
70		if (lo->pwm_map[n].gpio == gpio) {
71			if (!lo->pwm_map[n].active_level)
72				inten = 65535 - inten;
73			ledc_set_duty(_LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0 +
74					lo->pwm_map[n].index, inten >> 3);
75			ledc_update_duty(_LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0 +
76					lo->pwm_map[n].index);
77			return;
78		}
79	}
80
81	lwsl_err("%s: unknown gpio for pwm\n", __func__);
82}
83