Raspberry Constructors
Next, we use “def __init__()" to add a constructor to the Servo class. It can contain multiple parameters. When we need to refer to a variable in the function, we need to pass in the value of the parameter through the function body itself. Therefore, we need to set the parameter in the function body first. For example, the function of our constructor below is to set a pin as the pin of the output PWM signal, so the parameter we need to introduce in the function body is the pin number. In addition to “pin", we also introduce a parameter called “self". Self represents the instance of a class, not the class itself. This is also the difference between a class function and an ordinary function.
1 def __init__(self, pin):
2 self.pin = pin
3 self.pwm = PWM ( self.pin)
Next, we define the “turn" function to calculate the rotation angle “val" of the Servo. In this function, we output the PWM signal to the Servo through freq(), and output the analog value to the Servo by using the duty_u16() function to control its rotation. Note that the analog value is calculated by the formula: val/180*13000+4000. We need to convert the string or number calculated by the formula into the integer through the int() function.
1 def turn(self, val):
2 self.pwm.freq(100)
3 self.pwm.duty_u16(int(val/180*13000+4000))
The completed library file is as follows:
1 from machine import Pin, PWM #call machine library
2 #define a servo object below:
3 class SERVO:
#add a constructor to the created class: def __init__(self, pin):
#define two instance variables, pin and PWM: self.pin = pin
self.pwm = PWM(self.pin) #define example method of turn to calculate the rotation angle of Servo:
10 def turn(self, val):
self.pwm. freq(100)
self.pwm.duty_u16(int(val/180*13000+4000))
After completing the library file, we name it “servo.py" and store it in Pico. Then we can call the functions in the library directly. Modifying the program of Project 1 as follows, we can input the rotation angle of Servo, run the program, and watch the magic happen!
1 from machine import Pin
2 from utime import sleep
3 from servo import SERVO
4 servo = SERVO(Pin(20))
5
6 for i in range(10):
servo.turn(20)
sleep(1)
servo. turn(160)
sleep(1)