Open 4.5Gearshift mode.py and click .
'''
* Filename : Gearshift mode
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import Pin,PWM,ADC
import time
key = ADC(26)
# set INA and INB to PWM pins
pwm_INA = PWM(Pin(14))
pwm_INB = PWM(Pin(15))
# set PWM frequency. The frequency depends on the motor application.
pwm_INA.freq(500)
pwm_INB.freq(500)
# Set the maximum and minimum rotation speed
max_duty = 65535
min_duty = 0
# Linear interpolation is used to calculate duty values for different speeds
def calc_duty(speed):
speed = int(speed * (max_duty - min_duty) / 100 + min_duty)
return speed
# change the rotation speed
def set_speed_INA(speed):
duty = calc_duty(speed)
pwm_INA.duty_u16(duty)
# change the rotation speed
def set_speed_INB(speed):
duty = calc_duty(speed)
pwm_INB.duty_u16(duty)
while True:
key_value = key.read_u16()
if key_value < 10000: # no key is pressed
pass
elif key_value < 14000: # SW5 is pressed
set_speed_INA(0)
set_speed_INB(40)
elif key_value < 27000: # SW4 is pressed
set_speed_INA(0)
set_speed_INB(60)
elif key_value < 40000: # SW3 is pressed
set_speed_INA(0)
set_speed_INB(80)
elif key_value < 53000: # SW2 is pressed
set_speed_INA(0)
set_speed_INB(100)
else: # SW1 is pressed
set_speed_INA(0)
set_speed_INB(0)
time.sleep(0.1)
Conceive:
The code structure of program is similar to that of Chapter 3.8, so please refer to that section for detailed explanations.
Initialization: Set pins of AD button and 130 motor.
Loop:
① Press button 5 to adjust the speed to 40.
② Press button 4 to adjust the speed to 60.
③ Press button 3 to adjust the speed to 80.
④ Press button 2 to adjust the speed to 100.
⑤ Press button 1 to stop the fan.