Abdullah
Abdullah

Reputation: 21

How to control speed for a water pump plugged in a BBC microbit using micropython

How to control speed for a water pump plugged in a BBC micro:bit using micropython?

So far to control the water pump I can turn it on/off, here is my code:

from microbit import *
pin2.write_digital(1)
sleep(1000)
pin2.write_digital(0)

How it is connected:

Upvotes: 1

Views: 728

Answers (2)

nekomatic
nekomatic

Reputation: 6284

If you're controlling a DC motor with a transistor switch, which is what it looks like from your diagram, you should be able to vary the speed using pulse-width modulation (PWM) - in other words by repeatedly turning the output on for a short time then off for a short time, with the ratio of on time to off time (the duty factor) determining how fast the motor runs.

You can do that in code as Bob's answer suggests, but in MicroPython on the micro:bit you can also generate PWM using the write_analog method of the Pin class. That way you can set a motor speed and it will continue to run while your program continues to do something else. You may need to experiment to find the period setting that gives you the best control.

If you're updating the speed in a loop, don't fall into the trap described here.

Off topic, it looks as if your transistor is configured as an emitter follower. Since the micro:bit uses 3.3 V logic, this will only drive the motor with a maximum of about 2.7 volts even though you have 6 V available from your battery pack (assuming your diagram is accurate). For better results you might want to look up other methods of switching a high current load from a logic output, e.g. a low side switch. If you need to ask questions about that try Electronics

Upvotes: 1

Turn it on an off in quick succession:

for loopcount in range(1, 1000):
    pin2.write_digital(1)
    sleep(2)
    pin2.write_digital(0)
    sleep(2)

Adjust the sleep calls to get the flow you want.

Upvotes: 1

Related Questions