ext-store · Recipe
Factory reset
Erase every stored key when a button is held at power-on, then restart into a clean device.
A device that saves settings needs a way back to a clean state. Here, holding a button while the board powers up erases the store and restarts.
Goal
At boot, if the button is held for two seconds, call store_clear() and restart. Otherwise start normally.
What you need
- A push button between a GPIO and GND, with a pull-up resistor to 3V3 (10 kOhm) so the pin reads
1when the button is released and0while it is pressed. The script uses GPIO 4; use a free pin of your board. ext-storefor the store,ext-gpioto read the button andext-sysfor the delay and the restart. Conductor adds the HAL of each.
composer require php-baremetal/ext-store php-baremetal/ext-gpio php-baremetal/ext-sys
The code
<?php
const RESET_BUTTON = 4;
function held_for(int $pin, int $ms): bool
{
for ($t = 0; $t < $ms; $t += 50) {
if (gpio_read($pin) !== 0) {
return false; // released early
}
sys_delay(50);
}
return true;
}
function setup(): void
{
gpio_mode(RESET_BUTTON, GPIO_INPUT);
if (gpio_read(RESET_BUTTON) === 0 && held_for(RESET_BUTTON, 2000)) {
echo "factory reset: erasing ", count(store_keys()), " keys\n";
if (store_clear()) {
sys_restart(); // stops the program and restarts the board
}
echo "factory reset failed: the store is not available\n";
}
// normal start-up from here
echo "booted with ", count(store_keys()), " stored keys\n";
}
function loop(int $tick): void
{
delay(1000);
}
What you will see
Hold the button, press reset, and keep holding for two seconds:
factory reset: erasing 3 keys
booted with 0 stored keysThe second line comes from the boot after the restart. Release the button first, or it erases again, which is harmless.
Related
- Save settings Recipe
- PHP API PHP API
- ext-gpio Extension
- ext-sys Extension