Skip to content

Commit bf9df4b

Browse files
committed
Add PWM class as wrapper.
1 parent a6c55e2 commit bf9df4b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

mrbgem.rake

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ MRuby::Gem::Specification.new('mruby-esp32-ledc') do |spec|
33
spec.authors = 'vickash'
44

55
spec.cc.include_paths << "#{build.root}/src"
6+
spec.add_dependency('mruby-rational', :core => 'mruby-rational')
67
end

mrblib/pwm.rb

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class PWM
2+
attr_accessor :group, :channel, :timer, :resolution, :f, :d
3+
4+
def initialize(pin = nil, **kwargs)
5+
self.group = kwargs[:group] || ESP32::LEDC_LOW_SPEED_MODE
6+
self.channel = kwargs[:channel] || ESP32::LEDC_CHANNEL_0
7+
self.timer = kwargs[:timer] || ESP32::LEDC_TIMER_0
8+
self.resolution = kwargs[resolution] || ESP32::LEDC_TIMER_14_BIT
9+
10+
f = kwargs[:freq] || kwargs[:frequency] || 1000
11+
d = kwargs[:duty] || 0
12+
13+
puts("group=#{group}, channel=#{channel}, timer=#{timer}, resolution=#{resolution}, f=#{f}, d=#{d}")
14+
15+
ESP32::LEDC.timer_config(group, timer, resolution, f)
16+
ESP32::LEDC.channel_config(pin, group, timer, channel)
17+
18+
self.frequency(f)
19+
self.duty(d)
20+
end
21+
22+
def frequency(freq)
23+
self.f = freq
24+
print(self.f)
25+
ESP32::LEDC.set_freq(self.group, self.timer, self.f)
26+
end
27+
28+
def period_us(micro_sec)
29+
frequency(Rational(1, Rational(micro_sec, 1_000_000)))
30+
end
31+
32+
def duty(percent)
33+
self.d = Rational(percent, 100).to_i
34+
ESP32::LEDC.set_duty(self.group, self.channel, self.d)
35+
end
36+
37+
def pulse_width_us(micro_sec)
38+
us_per_bit = Rational(1_000_000, self.f) / (2 ** self.resolution)
39+
duty((Rational(micro_sec, us_per_bit) * 100).to_i)
40+
end
41+
end

0 commit comments

Comments
 (0)