Skip to content

Commit d66a614

Browse files
committed
Feature: Add the pwm percentage function
1 parent fb64fb9 commit d66a614

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

m5stack/libs/unit/hbridge.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,19 @@ def set_16bit_pwm(self, duty=0):
7575
"""
7676
self.write_mem_list(PWM16BIT_REG, [(duty & 0xFF), ((duty >> 8) & 0xFF)])
7777

78+
def set_percentage_pwm(self, duty=0, res=8):
79+
"""
80+
set 8bit or 16bit pwm dutycycle
81+
duty : 0 to 100%
82+
resolution: 8 or 16 bit
83+
"""
84+
duty = max(min(duty, 100), 0)
85+
if res == 8:
86+
duty = self.map(duty, 0, 100, 0, 255)
87+
else:
88+
duty = self.map(duty, 0, 100, 0, 65535)
89+
self.write_mem_list(PWM8BIT_REG, [duty])
90+
7891
def set_pwm_freq(self, freq=0):
7992
"""
8093
set direction
@@ -127,6 +140,9 @@ def write_mem_list(self, reg, data):
127140
def read_reg(self, reg, num):
128141
return self.hbridge_i2c.readfrom_mem(self.i2c_addr, reg, num)
129142

143+
def map(self, x, in_min, in_max, out_min, out_max):
144+
return round((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
145+
130146
def deinit(self):
131147
pass
132148

0 commit comments

Comments
 (0)