← Back to Course
PWM for LED Dimming and Motor Speed
🎛️ PWM - Analog Output with MicroPython
📖 PWM LED Dimming:
from machine import Pin, PWM
import time
# Create PWM object on GP0 at 1kHz frequency
led = PWM(Pin(0))
led.freq(1000)
# Fade LED up and down
while True:
# Fade up
for duty in range(0, 65535, 1000):
led.duty_u16(duty)
time.sleep(0.01)
time.sleep(0.5)
# Fade down
for duty in range(65535, 0, -1000):
led.duty_u16(duty)
time.sleep(0.01)
time.sleep(0.5)
💧 Variable Speed Water Pump:
from machine import Pin, PWM, ADC
import time
# Setup
pump = PWM(Pin(0)) # PWM pin for pump control
pump.freq(1000)
moisture_sensor = ADC(Pin(26)) # ADC pin
def read_moisture():
raw = moisture_sensor.read_u16() # 0-65535
percent = 100 - (raw / 65535 * 100)
return max(0, min(100, percent))
while True:
moisture = read_moisture()
print(f"Soil moisture: {moisture:.1f}%")
if moisture < 20:
pump.duty_u16(65535) # Full speed
print("Pump: FULL SPEED")
elif moisture < 40:
# Map moisture to pump speed
speed = int(32768 + (moisture - 20) * 1000)
pump.duty_u16(speed)
print(f"Pump: MEDIUM SPEED")
else:
pump.duty_u16(0) # Pump OFF
print("Pump: OFF")
time.sleep(60) # Update every minute
⚠️ Important:
For water pumps, use a MOSFET (like IRLZ44N) with PWM. Do not connect pumps directly to Pico W pins - they can't handle the current!
💡 Key Takeaways:
- Apply these concepts directly to your farm or project.
- Take notes on important details for the quiz.
- Use the button below to track your progress.
×