Micropython Classes #10775
Unanswered
jimcraig47
asked this question in
Using MicroPython
Micropython Classes
#10775
Replies: 2 comments 3 replies
-
# style tips: Class names are PascalCase, constants are UPPER_SNAKE_CASE,
# everything else lower_snake_case. Leading underscore means "private" within
# module or class.
_MAX_DUTY = const(65536)
class MotorControl:
def __init__(self, in1, in2, in3, in4):
self.in1 = in1
self.in2 = in2
self.in3 = in3
self.in4 = in4
def forward(self, speed):
duty_cycle = self._speed_to_duty_cycle(speed)
self.in1.duty_u16(duty_cycle)
self.in2.duty_u16(0)
self.in3.duty_u16(duty_cycle)
self.in4.duty_u16(0)
def coast(self):
self.in1.duty_u16(0)
self.in2.duty_u16(0)
self.in3.duty_u16(0)
self.in4.duty_u16(0)
def _speed_to_duty_cycle(self, speed):
if speed < 0:
speed = 0
if speed > 100:
speed = 100
return speed * _MAX_DUTY // 100
# assuming the parameters here (IN*) are defined as PWM objects elsewhere
# have to create an instance of the class in order to use it (fixes TypeError)
motor = MotorControl(IN1, IN2, IN3, IN4)
try:
motor.forward(100)
# need something like time.sleep(1) here so that the program does not end right away
finally:
# ensure that motor stops even if program crashes/is interrupted
motor.coast() |
Beta Was this translation helpful? Give feedback.
3 replies
-
Just some minor comments:
if self.speed <=0 or self.speed > 100:
duty_cycle = 0
else:
duty_cycle = int((speed*65536)/100) The Pythonic way to write this is: if 0 < self.speed <= 100:
duty_cycle = int((speed * 65536) / 100)
else:
duty_cycle = 0
if speed < 0:
speed = 0
elif speed > 100:
speed = 100 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Have watched numerous YouTubes trying to teach myself functions and classes. Trying to apply what I've learned to creating a class to run a dcmotor for a robot car but can't get past the following error or figure out what other parameter it's looking for.
TypeError: function takes 2 positional arguments but 1 were given
class motorcontrol:
motorcontrol.forward(100)
Beta Was this translation helpful? Give feedback.
All reactions