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.
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.
The completed library file is as follows:
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!