# 2-Axis PWM Motor Controls in Python

a guest
Oct 2nd, 2016
455
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # stick is a tuple of the form (x, y), that comes from the 2-axis controller (wii nunchuk)
2. # Both x and y are values from 0 - 255
3. # x=0 means "all the way left"
4. # y=0 means "all the way down"
5.
6. # motors are controlled by PWM
7. # The only thing we change is the duty cycle,
8. # which is a value from 0 - 100
9.
10. # Even though the duty cycle can only be 0 - 100, my move_motors() function
11. # takes values from -100 - 100. This is because if the value you pass
12. # for a motor is below 0 (a negative number), it will flip the pin that
13. # controls direction, and always pass the PWM pin a positive value
14. # Eg:
15. #   passing move_motors() the argument -58 for left_motor means:
16. #       flip the direction pin so motor spins backwards, and set duty cycle to 58
17.
18. # Turn the 0-255 value of joystick into -128 - 127 value
19. left_right = stick[0] - 128
20. front_back = stick[1] - 128
21.
22. left_motor = front_back + left_right
23. right_motor = front_back - left_right
24.
25. # Scale factor defaults to 1
26. scale_factor = 1
27.
28. # Calculate scale factor
29. if abs(left_motor) > 100 or abs(right_motor) > 100:
30.     # Find highest of the 2 values, since both could be above 100
31.     x = max(abs(left_motor), abs(right_motor))
32.
33.     # Calculate scale factor
34.     scale_factor = 100.0 / x
35.
36. # Use scale factor, and turn values back into integers
37. left_motor = int(left_motor * scale_factor)
38. right_motor = int(right_motor * scale_factor)
39.
40. # Actually move the motors
41. move_motors(left_motor, right_motor)
RAW Paste Data