K210——PWM control servo

K210


insert image description here

1. What is PWM?

PWM (Pulse Width Modulation) is a specific signal output, which is mainly used to output square waves with different frequencies and duty ratios (the proportion of high level occurrence time in a cycle to the total time).
insert image description here
Example of output PWM waveform to achieve fixed frequency or average voltage , the right side is the equivalent voltage

2. Correlation function

1.machine.PWM(tim, freq, duty, pin, enable=True)

machine.PWM(tim, freq, duty, pin, enable=True)

The PWM object is under the machine module.
[tim] K210's PWM relies on timer to generate waveform
[freq] PWM frequency
[duty] PWM duty cycle
[pin] PWM output pin
[enable] Whether to generate waveform immediately after constructing the object, the default is True.

PWM.freq(freq)
设置频率。不传参数返回当前频率值。
PWM.duty(duty)
设置占空比。不传参数返回当前占空比值。[0-100]表示占空比百分比
PWM.enable()
使能 PWM 输出。
PWM.disable()
暂停 PWM 输出。 PWM.deinit()
注销 PWM。

insert image description here

2. Complete code

from machine import Timer,PWM
import time

#PWM通过定时器配置,接到IO17引脚
tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
S1 = PWM(tim, freq=50, duty=0, pin=17)

'''
说明:舵机控制函数
功能:180度舵机:angle:-9090 表示相应的角度
     360连续旋转度舵机:angle:-9090 旋转方向和速度值。
    【duty】占空比值:0-100
'''

def Servo(servo,angle):
    S1.duty((angle+90)/180*10+2.5)


while True:
    #-90Servo(S1,-90)
    time.sleep(1)

    #-45Servo(S1,-45)
    time.sleep(1)

    #0Servo(S1,0)
    time.sleep(1)

    #45Servo(S1,45)
    time.sleep(1)

    #90Servo(S1,90)
    time.sleep(1)

insert image description here
When connecting, do not directly connect the 5v on the board, it may break down the chip

Guess you like

Origin blog.csdn.net/qq_51963216/article/details/123945993