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.
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:
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.
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.