raspikeyer/src/settings.cpp

71 lines
1.7 KiB
C++
Raw Normal View History

2024-02-07 09:32:11 +01:00
#include <cstring>
2024-02-07 11:15:41 +01:00
#include <pico/stdlib.h>
2024-02-06 22:11:58 +01:00
#include "settings.h"
namespace
{
2024-02-07 09:32:11 +01:00
constexpr const uint32_t FLASH_TARGET_OFFSET = PICO_FLASH_SIZE_BYTES - FLASH_SECTOR_SIZE;
2024-02-07 11:15:41 +01:00
const uint8_t *flash_target_contents = (const uint8_t *)(XIP_BASE + FLASH_TARGET_OFFSET);
const uint LED_PIN = PICO_DEFAULT_LED_PIN;
2024-02-06 22:11:58 +01:00
}
void flash_store_callback(void *settings)
{
2024-02-07 09:32:11 +01:00
int writeSize = (sizeof(struct Settings) / FLASH_PAGE_SIZE) + 1;
flash_range_erase(FLASH_TARGET_OFFSET, FLASH_SECTOR_SIZE);
2024-02-07 11:15:41 +01:00
flash_range_program(FLASH_TARGET_OFFSET, (uint8_t *)settings, FLASH_PAGE_SIZE);
2024-02-06 22:11:58 +01:00
}
void store_settings(Settings &settings)
{
2024-02-07 11:15:41 +01:00
uint8_t *settingsAsBytes = (uint8_t *)&settings;
2024-02-07 09:32:11 +01:00
2024-02-07 11:15:41 +01:00
int result = flash_safe_execute(flash_store_callback, settingsAsBytes, 1000);
if (result == PICO_OK)
{
gpio_put(LED_PIN, 1);
sleep_ms(250);
gpio_put(LED_PIN, 0);
sleep_ms(250);
gpio_put(LED_PIN, 1);
sleep_ms(250);
gpio_put(LED_PIN, 0);
sleep_ms(250);
2024-02-07 11:25:38 +01:00
gpio_put(LED_PIN, 1);
sleep_ms(250);
gpio_put(LED_PIN, 0);
sleep_ms(250);
2024-02-07 11:15:41 +01:00
}
2024-02-07 09:32:11 +01:00
}
2024-02-07 11:15:41 +01:00
Settings read_settings()
{
2024-02-07 09:32:11 +01:00
Settings settings;
2024-02-07 11:35:30 +01:00
2024-02-07 09:32:11 +01:00
memcpy(&settings, flash_target_contents, sizeof(struct Settings));
2024-02-07 11:25:38 +01:00
2024-02-07 11:35:30 +01:00
if (settings.magic_number != MAGIC_NUMBER)
{
2024-02-07 11:25:38 +01:00
settings = Settings();
gpio_put(LED_PIN, 1);
sleep_ms(1000);
gpio_put(LED_PIN, 0);
sleep_ms(250);
gpio_put(LED_PIN, 1);
sleep_ms(1000);
gpio_put(LED_PIN, 0);
sleep_ms(250);
gpio_put(LED_PIN, 1);
sleep_ms(1000);
gpio_put(LED_PIN, 0);
sleep_ms(250);
2024-02-07 11:35:30 +01:00
store_settings(settings);
}
2024-02-07 11:25:38 +01:00
2024-02-07 09:32:11 +01:00
return settings;
2024-02-06 22:11:58 +01:00
}