Raspberry Control Fan On and Off with Button
First, we will try to control the fan rotation with the press of a button and achieve manual control of the fan. At this point, you can try to recall the program that we worked on to control an LED on and off with the button, as they have the same logic.
Hardware Connection
In this project, the electronic hardware we need to use is as follows:
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - Mini Fan
• Grove - Button
Use a Grove data cable to connect the Button to D16 on the Grove Shield, and connect the Mini Fan to D18.
Write a Program
Similarly, we have to first import the required libraries to set the pins for the button and the fan. When the button is pressed, the return value is 1 and the fan turns on; otherwise, the fan is turned off. The complete code is as follows:
from machine import Pin
BUTTON = machine.Pin(16, machine.Pin.IN)
minifan = machine. Pin(18, machine. Pin.OUT)
while True:
val = BUTTON.value()
if val == 1:
minifan.value(1)
else:
miniFan.value (0)
You might realise that when the fan turns on when the button is pressed, and off when the button is released. However, this is not in line with our usage habits. Generally, after we turn on the fan, we don't expect to have to continue pressing the button all the time. In the previous lessons, we also learned how to create variables to solve the similar problem encountered in achieving control of the LED with a button. In this lesson, we will instead introduce another method, using the toggle() function to switch the fan between the high and low levels. When you press the button, the fan will be switched to high; when you press the button again, it will be switched to the low level, so as to “toggle” the fan on and off.
import machine
import utime
button = machine.Pin(18, machine.Pin.IN)
minifan = machine.Pin(16, machine.Pin.OUT)
val = 0
while True:
val = button.value()
if val == 1:
miniFan.toggle()
utime. sleep_ms(100)
Use a USB cable to connect Pico to the computer, click the “run" button to save the program to any location, and then test the running effect by pressing the button.