add toggleButton example
This commit is contained in:
@@ -24,3 +24,42 @@ The usual `gpio_init` and `gpio_set_dir` are used to initialize and set the dire
|
||||
The same code can be used for controlling the fan from earlier experiment. LED connected to the `ledPin` is replaced with connection to the gate pin of the mosfet.
|
||||
|
||||
- insert gif of controlling fan with button
|
||||
|
||||
## ToggleButton
|
||||
|
||||
Instead of setting the fan status to be the same as the the button status, this example toggles everytime the button is pressed.
|
||||
|
||||
Below code demonstrates using a button to toggle the state of the fan between on and off.
|
||||
|
||||
```c
|
||||
int buttonStatus = gpio_get(buttonPin);
|
||||
bool outputStatus = false;
|
||||
int state = buttonStatus * 2 + gpio_get(buttonPin);
|
||||
while (true)
|
||||
{
|
||||
state = buttonStatus * 2 + gpio_get(buttonPin);
|
||||
switch (state)
|
||||
{
|
||||
case 1:
|
||||
outputStatus = !outputStatus;
|
||||
gpio_put(ledPin, outputStatus);
|
||||
buttonStatus = 1;
|
||||
sleep_ms(10);
|
||||
break;
|
||||
case 2:
|
||||
buttonStatus = 0;
|
||||
sleep_ms(10);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To toggle the state on button state changes, change in button press is recorded using `buttonStatus` variable.
|
||||
|
||||
If the button is pressed, `buttonState` will be `0` and new state will be `1`. Hence, the value in the `status` variable will be `1`. When this happens, the fan state is toggled. Output doesn't change when the button is released.
|
||||
|
||||
|
||||
Small delay is added to mitigate switch bouncing, as explained in [Circuit Basics blog on switch de-bouncing](https://www.circuitbasics.com/how-to-use-switch-debouncing-on-the-arduino/).
|
||||
|
||||
- insert gif of fan toggling.
|
||||
|
||||
Reference in New Issue
Block a user