diff --git a/exercises/00_usb_radio_check/README.md b/exercises/00_usb_radio_check/README.md index e69de29..0a51157 100644 --- a/exercises/00_usb_radio_check/README.md +++ b/exercises/00_usb_radio_check/README.md @@ -0,0 +1,116 @@ +Command: + + pio run -e node_a -t upload --upload-port /dev/ttyACM0 +Here's a sample compile & upload session: + + (rnsenv) jlpoole@jp /usr/local/src/microreticulum/microReticulumTbeam/exercises/00_usb_radio_check $ pio run -e node_a -t upload --upload-port /dev/ttyACM0 + Processing node_a (platform: espressif32; framework: arduino; board: esp32-s3-devkitc-1) + ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Verbose mode can be enabled via `-v, --verbose` option + CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32-s3-devkitc-1.html + PLATFORM: Espressif 32 (6.12.0) > Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM) + HARDWARE: ESP32S3 240MHz, 320KB RAM, 8MB Flash + DEBUG: Current (esp-builtin) On-board (esp-builtin) External (cmsis-dap, esp-bridge, esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa) + PACKAGES: + - framework-arduinoespressif32 @ 3.20017.241212+sha.dcc1105b + - tool-esptoolpy @ 2.40900.250804 (4.9.0) + - tool-mkfatfs @ 2.0.1 + - tool-mklittlefs @ 1.203.210628 (2.3) + - tool-mkspiffs @ 2.230.0 (2.30) + - toolchain-riscv32-esp @ 8.4.0+2021r2-patch5 + - toolchain-xtensa-esp32s3 @ 8.4.0+2021r2-patch5 + LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf + LDF Modes: Finder ~ chain, Compatibility ~ soft + Found 34 compatible libraries + Scanning dependencies... + Dependency Graph + |-- RadioLib @ 6.6.0 + |-- SPI @ 2.0.0 + Building in release mode + Retrieving maximum program size .pio/build/node_a/firmware.elf + Checking size .pio/build/node_a/firmware.elf + Advanced Memory Usage is available via "PlatformIO Home > Project Inspect" + RAM: [= ] 6.0% (used 19768 bytes from 327680 bytes) + Flash: [= ] 8.8% (used 294065 bytes from 3342336 bytes) + Configuring upload protocol... + AVAILABLE: cmsis-dap, esp-bridge, esp-builtin, esp-prog, espota, esptool, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa + CURRENT: upload_protocol = esptool + Looking for upload port... + Using manually specified: /dev/ttyACM0 + Uploading .pio/build/node_a/firmware.bin + esptool.py v4.9.0 + Serial port /dev/ttyACM0 + Connecting... + Chip is ESP32-S3 (QFN56) (revision v0.2) + Features: WiFi, BLE, Embedded Flash 8MB (GD) + Crystal is 40MHz + USB mode: USB-Serial/JTAG + MAC: 48:ca:43:5a:93:a0 + Uploading stub... + Running stub... + Stub running... + Changing baud rate to 460800 + Changed. + Configuring flash size... + Flash will be erased from 0x00000000 to 0x00003fff... + Flash will be erased from 0x00008000 to 0x00008fff... + Flash will be erased from 0x0000e000 to 0x0000ffff... + Flash will be erased from 0x00010000 to 0x00057fff... + SHA digest in image updated + Compressed 15104 bytes to 10430... + Writing at 0x00000000... (100 %) + Wrote 15104 bytes (10430 compressed) at 0x00000000 in 0.2 seconds (effective 519.1 kbit/s)... + Hash of data verified. + Compressed 3072 bytes to 146... + Writing at 0x00008000... (100 %) + Wrote 3072 bytes (146 compressed) at 0x00008000 in 0.0 seconds (effective 584.3 kbit/s)... + Hash of data verified. + Compressed 8192 bytes to 47... + Writing at 0x0000e000... (100 %) + Wrote 8192 bytes (47 compressed) at 0x0000e000 in 0.1 seconds (effective 721.9 kbit/s)... + Hash of data verified. + Compressed 294432 bytes to 164378... + Writing at 0x00010000... (9 %) + Writing at 0x0001bc31... (18 %) + Writing at 0x00024a76... (27 %) + Writing at 0x0002a8b3... (36 %) + Writing at 0x0002fd85... (45 %) + Writing at 0x000350b4... (54 %) + Writing at 0x0003b4b4... (63 %) + Writing at 0x000455f6... (72 %) + Writing at 0x0004c5eb... (81 %) + Writing at 0x00051c54... (90 %) + Writing at 0x00057b42... (100 %) + Wrote 294432 bytes (164378 compressed) at 0x00010000 in 1.9 seconds (effective 1241.1 kbit/s)... + Hash of data verified. + + Leaving... + Hard resetting via RTS pin... + ==================================================================================== [SUCCESS] Took 8.73 seconds ==================================================================================== + + Environment Status Duration + ------------- -------- ------------ + node_a SUCCESS 00:00:08.731 + ==================================================================================== 1 succeeded in 00:00:08.731 ==================================================================================== + (rnsenv) jlpoole@jp /usr/local/src/microreticulum/microReticulumTbeam/exercises/00_usb_radio_check $ + +Here's an example of what displays in the console: + +Booting LoRa test... + +Initializing radio... +Radio chip: SX1262 +Frequency: 915.000 MHz +SF: 7 BW: 125 CR: 5 +radio.begin returned: 0 +alive 0 + Sending test frame... +TX state: 0 +Starting receive... +startReceive returned: 0 +alive 1 + Sending test frame... +TX state: 0 +Starting receive... +startReceive returned: 0 +alive 2 diff --git a/exercises/04_SD_card/README.md b/exercises/04_SD_card/README.md new file mode 100644 index 0000000..4ef7a53 --- /dev/null +++ b/exercises/04_SD_card/README.md @@ -0,0 +1,37 @@ +## Exercise 04: SD Card + +This exercise loops forever. Each cycle: + +1. Prints `Sleeping 10 seconds` and waits 10 seconds. +2. Detects and mounts the SD card. +3. Prints card and filesystem info (type/size/used). +4. Writes `/Exercise_04_test.txt` with: + - `This is a test` +5. Ensures nested directories exist: + - `/test/testsub1/testsubsub1` +6. Writes nested file: + - `/test/testsub1/testsubsub1/Exercise_04_test.txt` +7. If either target file already exists, prints warning, erases it, then recreates it. +8. Demonstrates permission behavior: + - Notes FAT does not provide Unix `chmod/chown`. + - Shows access behavior via `FILE_READ` vs `FILE_WRITE` modes. + +## Build + +```bash +source /home/jlpoole/rnsenv/bin/activate +pio run -e node_a +``` + +## Upload + +```bash +source /home/jlpoole/rnsenv/bin/activate +pio run -e node_a -t upload --upload-port /dev/ttyACM0 +``` + +## Monitor + +```bash +screen /dev/ttyACM0 115200 +``` diff --git a/exercises/04_SD_card/platformio.ini b/exercises/04_SD_card/platformio.ini new file mode 100644 index 0000000..91402fe --- /dev/null +++ b/exercises/04_SD_card/platformio.ini @@ -0,0 +1,36 @@ +; 20260213 ChatGPT +; $Id$ +; $HeadURL$ + +[platformio] +default_envs = node_a + +[env] +platform = espressif32 +framework = arduino +board = esp32-s3-devkitc-1 +monitor_speed = 115200 +lib_deps = + lewisxhe/XPowersLib@0.3.3 + +; SD pins based on T-Beam S3 core pin mapping +build_flags = + -D SD_SCK=36 + -D SD_MISO=37 + -D SD_MOSI=35 + -D SD_CS=47 + -D IMU_CS=34 + -D I2C_SDA1=42 + -D I2C_SCL1=41 + -D ARDUINO_USB_MODE=1 + -D ARDUINO_USB_CDC_ON_BOOT=1 + +[env:node_a] +build_flags = + ${env.build_flags} + -D NODE_LABEL=\"A\" + +[env:node_b] +build_flags = + ${env.build_flags} + -D NODE_LABEL=\"B\" diff --git a/exercises/04_SD_card/src/main.cpp b/exercises/04_SD_card/src/main.cpp new file mode 100644 index 0000000..0ddf800 --- /dev/null +++ b/exercises/04_SD_card/src/main.cpp @@ -0,0 +1,273 @@ +// 20260213 ChatGPT +// $Id$ +// $HeadURL$ + +#include +#include +#include +#include +#include +#include + +#ifndef SD_SCK +#define SD_SCK 36 +#endif +#ifndef SD_MISO +#define SD_MISO 37 +#endif +#ifndef SD_MOSI +#define SD_MOSI 35 +#endif +#ifndef SD_CS +#define SD_CS 47 +#endif +#ifndef IMU_CS +#define IMU_CS 34 +#endif +#ifndef I2C_SDA1 +#define I2C_SDA1 42 +#endif +#ifndef I2C_SCL1 +#define I2C_SCL1 41 +#endif + +static SPIClass sdSpiH(HSPI); +static SPIClass sdSpiF(FSPI); +static SPIClass* g_sdSpi = nullptr; +static const char* g_sdBusName = "none"; +static uint32_t g_sdFreq = 0; +static XPowersLibInterface* g_pmu = nullptr; + +static const char* kRootTestFile = "/Exercise_04_test.txt"; +static const char* kNestedDir = "/test/testsub1/testsubsub1"; +static const char* kNestedTestFile = "/test/testsub1/testsubsub1/Exercise_04_test.txt"; +static const char* kPayload = "This is a test"; + +static bool initPmuForSdPower() { + Wire1.begin(I2C_SDA1, I2C_SCL1); + + if (!g_pmu) { + g_pmu = new XPowersAXP2101(Wire1); + } + + if (!g_pmu->init()) { + Serial.println("PMU: AXP2101 init failed (SD power rail may be off)"); + return false; + } + + // Mirror Meshtastic tbeam-s3-core power setup needed for peripherals. + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO4, 3300); // GNSS + g_pmu->enablePowerOutput(XPOWERS_ALDO4); + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO3, 3300); // LoRa + g_pmu->enablePowerOutput(XPOWERS_ALDO3); + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO2, 3300); // sensor/rtc path + g_pmu->enablePowerOutput(XPOWERS_ALDO2); + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO1, 3300); // IMU/OLED path + g_pmu->enablePowerOutput(XPOWERS_ALDO1); + g_pmu->setPowerChannelVoltage(XPOWERS_BLDO1, 3300); // SD card rail + g_pmu->enablePowerOutput(XPOWERS_BLDO1); + + Serial.printf("PMU: AXP2101 ready, BLDO1(SD)=%s\r\n", + g_pmu->isPowerChannelEnable(XPOWERS_BLDO1) ? "ON" : "OFF"); + return g_pmu->isPowerChannelEnable(XPOWERS_BLDO1); +} + +static const char* cardTypeToString(uint8_t type) { + switch (type) { + case CARD_MMC: return "MMC"; + case CARD_SD: return "SDSC"; + case CARD_SDHC: return "SDHC/SDXC"; + default: return "UNKNOWN"; + } +} + +static bool tryMountWithBus(SPIClass& bus, const char* busName, uint32_t hz) { + SD.end(); + bus.end(); + delay(10); + + // Keep inactive devices deselected on shared bus lines. + pinMode(SD_CS, OUTPUT); + digitalWrite(SD_CS, HIGH); + pinMode(IMU_CS, OUTPUT); + digitalWrite(IMU_CS, HIGH); + + bus.begin(SD_SCK, SD_MISO, SD_MOSI, SD_CS); + delay(2); + + Serial.printf("SD: trying bus=%s freq=%lu Hz\r\n", busName, (unsigned long)hz); + if (!SD.begin(SD_CS, bus, hz)) { + Serial.println("SD: mount failed (possible non-FAT format, power, or bus issue)"); + return false; + } + + uint8_t cardType = SD.cardType(); + if (cardType == CARD_NONE) { + SD.end(); + return false; + } + + g_sdSpi = &bus; + g_sdBusName = busName; + g_sdFreq = hz; + return true; +} + +static bool mountCard() { + const uint32_t freqs[] = {400000, 1000000, 4000000, 10000000}; + + for (uint8_t i = 0; i < (sizeof(freqs) / sizeof(freqs[0])); ++i) { + if (tryMountWithBus(sdSpiH, "HSPI", freqs[i])) { + Serial.println("SD: card detected and mounted"); + return true; + } + } + for (uint8_t i = 0; i < (sizeof(freqs) / sizeof(freqs[0])); ++i) { + if (tryMountWithBus(sdSpiF, "FSPI", freqs[i])) { + Serial.println("SD: card detected and mounted"); + return true; + } + } + + Serial.println("SD: begin() failed on all bus/frequency attempts"); + Serial.println(" likely card absent, bad format, pin mismatch, or hardware issue"); + return false; +} + +static void printCardInfo() { + uint8_t cardType = SD.cardType(); + uint64_t cardSizeMB = SD.cardSize() / (1024ULL * 1024ULL); + uint64_t totalMB = SD.totalBytes() / (1024ULL * 1024ULL); + uint64_t usedMB = SD.usedBytes() / (1024ULL * 1024ULL); + + Serial.printf("SD type: %s\r\n", cardTypeToString(cardType)); + Serial.printf("SD size: %llu MB\r\n", cardSizeMB); + Serial.printf("FS total: %llu MB\r\n", totalMB); + Serial.printf("FS used : %llu MB\r\n", usedMB); + Serial.printf("SPI bus: %s @ %lu Hz\r\n", g_sdBusName, (unsigned long)g_sdFreq); +} + +static bool ensureDirRecursive(const char* path) { + String full(path); + if (!full.startsWith("/")) { + full = "/" + full; + } + + int start = 1; + while (start > 0 && start < (int)full.length()) { + int slash = full.indexOf('/', start); + String partial = (slash < 0) ? full : full.substring(0, slash); + + if (!SD.exists(partial.c_str())) { + Serial.printf("Creating directory: %s\r\n", partial.c_str()); + if (!SD.mkdir(partial.c_str())) { + Serial.printf("ERROR: mkdir failed for %s\r\n", partial.c_str()); + return false; + } + } + + if (slash < 0) { + break; + } + start = slash + 1; + } + + return true; +} + +static bool rewriteFile(const char* path, const char* payload) { + if (SD.exists(path)) { + Serial.printf("WARNING: %s exists ... erasing\r\n", path); + if (!SD.remove(path)) { + Serial.printf("ERROR: failed to erase %s\r\n", path); + return false; + } + } + + File f = SD.open(path, FILE_WRITE); + if (!f) { + Serial.printf("ERROR: failed to create %s\r\n", path); + return false; + } + + size_t wrote = f.println(payload); + f.close(); + + if (wrote == 0) { + Serial.printf("ERROR: write failed for %s\r\n", path); + return false; + } + + Serial.printf("Wrote file: %s\r\n", path); + return true; +} + +static void permissionsDemo(const char* path) { + Serial.println("Permissions demo:"); + Serial.println(" SD/FAT does not support Unix permissions (chmod/chown)."); + Serial.println(" Access control is by open mode (FILE_READ/FILE_WRITE)."); + + File r = SD.open(path, FILE_READ); + if (!r) { + Serial.printf(" Could not open %s as FILE_READ\r\n", path); + return; + } + + Serial.printf(" FILE_READ open succeeded, size=%u bytes\r\n", (unsigned)r.size()); + size_t writeInReadMode = r.print("attempt write while opened read-only"); + if (writeInReadMode == 0) { + Serial.println(" As expected, write via FILE_READ handle was blocked."); + } else { + Serial.printf(" NOTE: write via FILE_READ returned %u (unexpected)\r\n", (unsigned)writeInReadMode); + } + r.close(); +} + +void setup() { + Serial.begin(115200); + Serial.println("Sleeping for 5 seconds to allow Serial Monitor connection..."); + delay(5000); // Time to open Serial Monitor after reset + + Serial.println("\r\n=================================================="); + Serial.println("Exercise 04: SD card test loop"); + Serial.println("=================================================="); + Serial.printf("Pins: CS=%d SCK=%d MISO=%d MOSI=%d\r\n", SD_CS, SD_SCK, SD_MISO, SD_MOSI); + Serial.printf("PMU I2C: SDA1=%d SCL1=%d\r\n", I2C_SDA1, I2C_SCL1); + Serial.println("Note: SD must be FAT16/FAT32 for Arduino SD library.\r\n"); + + initPmuForSdPower(); +} + +void loop() { + Serial.println("Sleeping 10 seconds"); + delay(10000); + + if (!mountCard()) { + Serial.println("SD step skipped this cycle.\r\n"); + return; + } + + printCardInfo(); + + if (!rewriteFile(kRootTestFile, kPayload)) { + SD.end(); + Serial.println("Cycle ended due to root file error.\r\n"); + return; + } + + if (!ensureDirRecursive(kNestedDir)) { + SD.end(); + Serial.println("Cycle ended due to directory creation error.\r\n"); + return; + } + + if (!rewriteFile(kNestedTestFile, kPayload)) { + SD.end(); + Serial.println("Cycle ended due to nested file error.\r\n"); + return; + } + + permissionsDemo(kRootTestFile); + SD.end(); + Serial.println("Cycle complete.\r\n"); +} diff --git a/exercises/05_SD_Card_Watcher/README.md b/exercises/05_SD_Card_Watcher/README.md new file mode 100644 index 0000000..d993448 --- /dev/null +++ b/exercises/05_SD_Card_Watcher/README.md @@ -0,0 +1,39 @@ +## Exercise 05: SD Card Watcher + +This exercise continuously watches SD card presence and prints state-change events. + +Watcher behavior: + +1. Initializes PMU and enables SD power rail (AXP2101 BLDO1). +2. Polls for card changes with debounced state transitions. +3. Emits events only on change: + - `EVENT: card inserted/mounted` + - `EVENT: card removed/unavailable` + - `EVENT: no card detected` +4. On mount event, prints card info and runs SD write workflow. +5. Every 15 seconds while mounted, runs a periodic write/permission check. +6. Uses fast preferred probe (`HSPI @ 400k`) and occasional full fallback scan. + +Files used in this exercise: +- `/Exercise_05_test.txt` +- `/test/testsub1/testsubsub1/Exercise_05_test.txt` + +## Build + +```bash +source /home/jlpoole/rnsenv/bin/activate +pio run -e node_a +``` + +## Upload + +```bash +source /home/jlpoole/rnsenv/bin/activate +pio run -e node_a -t upload --upload-port /dev/ttyACM0 +``` + +## Monitor + +```bash +screen /dev/ttyACM0 115200 +``` diff --git a/exercises/05_SD_Card_Watcher/platformio.ini b/exercises/05_SD_Card_Watcher/platformio.ini new file mode 100644 index 0000000..91402fe --- /dev/null +++ b/exercises/05_SD_Card_Watcher/platformio.ini @@ -0,0 +1,36 @@ +; 20260213 ChatGPT +; $Id$ +; $HeadURL$ + +[platformio] +default_envs = node_a + +[env] +platform = espressif32 +framework = arduino +board = esp32-s3-devkitc-1 +monitor_speed = 115200 +lib_deps = + lewisxhe/XPowersLib@0.3.3 + +; SD pins based on T-Beam S3 core pin mapping +build_flags = + -D SD_SCK=36 + -D SD_MISO=37 + -D SD_MOSI=35 + -D SD_CS=47 + -D IMU_CS=34 + -D I2C_SDA1=42 + -D I2C_SCL1=41 + -D ARDUINO_USB_MODE=1 + -D ARDUINO_USB_CDC_ON_BOOT=1 + +[env:node_a] +build_flags = + ${env.build_flags} + -D NODE_LABEL=\"A\" + +[env:node_b] +build_flags = + ${env.build_flags} + -D NODE_LABEL=\"B\" diff --git a/exercises/05_SD_Card_Watcher/src/main.cpp b/exercises/05_SD_Card_Watcher/src/main.cpp new file mode 100644 index 0000000..fc51cc7 --- /dev/null +++ b/exercises/05_SD_Card_Watcher/src/main.cpp @@ -0,0 +1,411 @@ +// 20260213 ChatGPT +// $Id$ +// $HeadURL$ + +#include +#include +#include +#include +#include +#include +#include + +#ifndef SD_SCK +#define SD_SCK 36 +#endif +#ifndef SD_MISO +#define SD_MISO 37 +#endif +#ifndef SD_MOSI +#define SD_MOSI 35 +#endif +#ifndef SD_CS +#define SD_CS 47 +#endif +#ifndef IMU_CS +#define IMU_CS 34 +#endif +#ifndef I2C_SDA1 +#define I2C_SDA1 42 +#endif +#ifndef I2C_SCL1 +#define I2C_SCL1 41 +#endif + +static SPIClass sdSpiH(HSPI); +static SPIClass sdSpiF(FSPI); +static SPIClass* g_sdSpi = nullptr; +static const char* g_sdBusName = "none"; +static uint32_t g_sdFreq = 0; +static XPowersLibInterface* g_pmu = nullptr; + +static const char* kRootTestFile = "/Exercise_05_test.txt"; +static const char* kNestedDir = "/test/testsub1/testsubsub1"; +static const char* kNestedTestFile = "/test/testsub1/testsubsub1/Exercise_05_test.txt"; +static const char* kPayload = "This is a test"; + +enum class WatchState : uint8_t { + UNKNOWN = 0, + ABSENT, + MOUNTED +}; + +static WatchState g_watchState = WatchState::UNKNOWN; +static uint8_t g_presentVotes = 0; +static uint8_t g_absentVotes = 0; +static uint32_t g_lastPollMs = 0; +static uint32_t g_lastFullScanMs = 0; +static uint32_t g_lastPeriodicActionMs = 0; +static const uint32_t kPollIntervalAbsentMs = 1000; +static const uint32_t kPollIntervalMountedMs = 2000; +static const uint32_t kFullScanIntervalMs = 10000; +static const uint32_t kPeriodicActionMs = 15000; +static const uint8_t kVotesToPresent = 2; +//static const uint8_t kVotesToAbsent = 4; +static const uint8_t kVotesToAbsent = 5; // More votes needed to declare absent to prevent false removes on transient errors. + +//static const uint32_t kStartupWarmupMs = 800; +static const uint32_t kStartupWarmupMs = 1500; // Longer warmup to allow PMU and card stabilization after power-on. +static uint32_t g_logSeq = 0; + +static void logf(const char* fmt, ...) { + char msg[192]; + va_list args; + va_start(args, fmt); + vsnprintf(msg, sizeof(msg), fmt, args); + va_end(args); + Serial.printf("[%10lu][%06lu] %s\r\n", (unsigned long)millis(), (unsigned long)g_logSeq++, msg); +} + +static bool initPmuForSdPower() { + Wire1.begin(I2C_SDA1, I2C_SCL1); + + if (!g_pmu) { + g_pmu = new XPowersAXP2101(Wire1); + } + + if (!g_pmu->init()) { + logf("PMU: AXP2101 init failed (SD power rail may be off)"); + return false; + } + + // Mirror Meshtastic tbeam-s3-core power setup needed for peripherals. + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO4, 3300); // GNSS + g_pmu->enablePowerOutput(XPOWERS_ALDO4); + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO3, 3300); // LoRa + g_pmu->enablePowerOutput(XPOWERS_ALDO3); + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO2, 3300); // sensor/rtc path + g_pmu->enablePowerOutput(XPOWERS_ALDO2); + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO1, 3300); // IMU/OLED path + g_pmu->enablePowerOutput(XPOWERS_ALDO1); + g_pmu->setPowerChannelVoltage(XPOWERS_BLDO1, 3300); // SD card rail + g_pmu->enablePowerOutput(XPOWERS_BLDO1); + + logf("PMU: AXP2101 ready, BLDO1(SD)=%s", + g_pmu->isPowerChannelEnable(XPOWERS_BLDO1) ? "ON" : "OFF"); + return g_pmu->isPowerChannelEnable(XPOWERS_BLDO1); +} + +static const char* cardTypeToString(uint8_t type) { + switch (type) { + case CARD_MMC: return "MMC"; + case CARD_SD: return "SDSC"; + case CARD_SDHC: return "SDHC/SDXC"; + default: return "UNKNOWN"; + } +} + +static bool tryMountWithBus(SPIClass& bus, const char* busName, uint32_t hz, bool verbose) { + SD.end(); + bus.end(); + delay(10); + + // Keep inactive devices deselected on shared bus lines. + pinMode(SD_CS, OUTPUT); + digitalWrite(SD_CS, HIGH); + pinMode(IMU_CS, OUTPUT); + digitalWrite(IMU_CS, HIGH); + + bus.begin(SD_SCK, SD_MISO, SD_MOSI, SD_CS); + delay(2); + + if (verbose) { + logf("SD: trying bus=%s freq=%lu Hz", busName, (unsigned long)hz); + } + if (!SD.begin(SD_CS, bus, hz)) { + if (verbose) { + logf("SD: mount failed (possible non-FAT format, power, or bus issue)"); + } + return false; + } + + uint8_t cardType = SD.cardType(); + if (cardType == CARD_NONE) { + SD.end(); + return false; + } + + g_sdSpi = &bus; + g_sdBusName = busName; + g_sdFreq = hz; + return true; +} + +static bool mountPreferred(bool verbose) { + return tryMountWithBus(sdSpiH, "HSPI", 400000, verbose); +} + +static bool mountCard() { + const uint32_t freqs[] = {400000, 1000000, 4000000, 10000000}; + + for (uint8_t i = 0; i < (sizeof(freqs) / sizeof(freqs[0])); ++i) { + if (tryMountWithBus(sdSpiH, "HSPI", freqs[i], true)) { + logf("SD: card detected and mounted"); + return true; + } + } + for (uint8_t i = 0; i < (sizeof(freqs) / sizeof(freqs[0])); ++i) { + if (tryMountWithBus(sdSpiF, "FSPI", freqs[i], true)) { + logf("SD: card detected and mounted"); + return true; + } + } + + logf("SD: begin() failed on all bus/frequency attempts"); + logf(" likely card absent, bad format, pin mismatch, or hardware issue"); + return false; +} + +static void printCardInfo() { + uint8_t cardType = SD.cardType(); + uint64_t cardSizeMB = SD.cardSize() / (1024ULL * 1024ULL); + uint64_t totalMB = SD.totalBytes() / (1024ULL * 1024ULL); + uint64_t usedMB = SD.usedBytes() / (1024ULL * 1024ULL); + + logf("SD type: %s", cardTypeToString(cardType)); + logf("SD size: %llu MB", cardSizeMB); + logf("FS total: %llu MB", totalMB); + logf("FS used : %llu MB", usedMB); + logf("SPI bus: %s @ %lu Hz", g_sdBusName, (unsigned long)g_sdFreq); +} + +static bool ensureDirRecursive(const char* path) { + String full(path); + if (!full.startsWith("/")) { + full = "/" + full; + } + + int start = 1; + while (start > 0 && start < (int)full.length()) { + int slash = full.indexOf('/', start); + String partial = (slash < 0) ? full : full.substring(0, slash); + + if (!SD.exists(partial.c_str())) { + logf("Creating directory: %s", partial.c_str()); + if (!SD.mkdir(partial.c_str())) { + logf("ERROR: mkdir failed for %s", partial.c_str()); + return false; + } + } + + if (slash < 0) { + break; + } + start = slash + 1; + } + + return true; +} + +static bool rewriteFile(const char* path, const char* payload) { + if (SD.exists(path)) { + logf("WARNING: %s exists ... erasing", path); + if (!SD.remove(path)) { + logf("ERROR: failed to erase %s", path); + return false; + } + } + + File f = SD.open(path, FILE_WRITE); + if (!f) { + logf("ERROR: failed to create %s", path); + return false; + } + + size_t wrote = f.println(payload); + f.close(); + + if (wrote == 0) { + logf("ERROR: write failed for %s", path); + return false; + } + + logf("Wrote file: %s", path); + return true; +} + +static void permissionsDemo(const char* path) { + logf("Permissions demo:"); + logf(" SD/FAT does not support Unix permissions (chmod/chown)."); + logf(" Access control is by open mode (FILE_READ/FILE_WRITE)."); + + File r = SD.open(path, FILE_READ); + if (!r) { + logf(" Could not open %s as FILE_READ", path); + return; + } + + logf(" FILE_READ open succeeded, size=%u bytes", (unsigned)r.size()); + size_t writeInReadMode = r.print("attempt write while opened read-only"); + if (writeInReadMode == 0) { + logf(" As expected, write via FILE_READ handle was blocked."); + } else { + logf(" NOTE: write via FILE_READ returned %u (unexpected)", (unsigned)writeInReadMode); + } + r.close(); +} + +static bool verifyMountedCard() { + File root = SD.open("/", FILE_READ); + if (!root) { + return false; + } + root.close(); + return true; +} + +static void runCardWorkflow() { + printCardInfo(); + + if (!rewriteFile(kRootTestFile, kPayload)) { + logf("Watcher action: root file write failed"); + return; + } + if (!ensureDirRecursive(kNestedDir)) { + logf("Watcher action: directory creation failed"); + return; + } + if (!rewriteFile(kNestedTestFile, kPayload)) { + logf("Watcher action: nested file write failed"); + return; + } + + permissionsDemo(kRootTestFile); +} + +static void setStateMounted() { + if (g_watchState != WatchState::MOUNTED) { + logf("EVENT: card inserted/mounted"); + runCardWorkflow(); + g_lastPeriodicActionMs = millis(); + } + g_watchState = WatchState::MOUNTED; +} + +static void setStateAbsent() { + if (g_watchState == WatchState::MOUNTED) { + logf("EVENT: card removed/unavailable"); + } else if (g_watchState != WatchState::ABSENT) { + logf("EVENT: no card detected"); + } + SD.end(); + g_watchState = WatchState::ABSENT; +} + +void setup() { + Serial.begin(115200); + Serial.println("[WATCHER: startup]"); + Serial.println("Sleeping for 5 seconds to allow Serial Monitor connection..."); + delay(5000); // Time to open Serial Monitor after reset + + Serial.println("\r\n=================================================="); + Serial.println("Exercise 05: SD Card Watcher"); + Serial.println("=================================================="); + Serial.printf("Pins: CS=%d SCK=%d MISO=%d MOSI=%d\r\n", SD_CS, SD_SCK, SD_MISO, SD_MOSI); + Serial.printf("PMU I2C: SDA1=%d SCL1=%d\r\n", I2C_SDA1, I2C_SCL1); + Serial.println("Note: SD must be FAT16/FAT32 for Arduino SD library.\r\n"); + + initPmuForSdPower(); + logf("Watcher: waiting %lu ms for SD rail/card stabilization", (unsigned long)kStartupWarmupMs); + delay(kStartupWarmupMs); + + // Warm-up attempts before first status decision. + bool warmMounted = false; + for (uint8_t i = 0; i < 3; ++i) { + if (mountPreferred(false)) { + warmMounted = true; + break; + } + delay(200); + } + if (warmMounted) { + logf("Watcher: startup warmup mount succeeded"); + setStateMounted(); + } else { + logf("Watcher: startup warmup did not mount card"); + setStateAbsent(); + } +} + +void loop() { + const uint32_t now = millis(); + const uint32_t pollInterval = (g_watchState == WatchState::MOUNTED) + ? kPollIntervalMountedMs + : kPollIntervalAbsentMs; + if ((uint32_t)(now - g_lastPollMs) < pollInterval) { + delay(10); + return; + } + g_lastPollMs = now; + + if (g_watchState == WatchState::MOUNTED) { + if (verifyMountedCard()) { + if ((uint32_t)(now - g_lastPeriodicActionMs) >= kPeriodicActionMs) { + logf("Watcher: periodic mounted check action"); + runCardWorkflow(); + g_lastPeriodicActionMs = now; + } + g_presentVotes = 0; + g_absentVotes = 0; + return; + } + + // One immediate remount attempt prevents false remove events on transient SPI errors. + if (mountPreferred(false) && verifyMountedCard()) { + g_presentVotes = 0; + g_absentVotes = 0; + return; + } + + g_absentVotes++; + g_presentVotes = 0; + if (g_absentVotes >= kVotesToAbsent) { + setStateAbsent(); + g_absentVotes = 0; + } + return; + } + + bool mounted = mountPreferred(false); + if (!mounted && (uint32_t)(now - g_lastFullScanMs) >= kFullScanIntervalMs) { + g_lastFullScanMs = now; + logf("Watcher: preferred probe failed, running full scan"); + mounted = mountCard(); + } + + if (mounted) { + g_presentVotes++; + g_absentVotes = 0; + if (g_presentVotes >= kVotesToPresent) { + setStateMounted(); + g_presentVotes = 0; + } + } else { + g_absentVotes++; + g_presentVotes = 0; + if (g_absentVotes >= kVotesToAbsent) { + setStateAbsent(); + g_absentVotes = 0; + } + } +} diff --git a/exercises/06_RTC_check/README.md b/exercises/06_RTC_check/README.md new file mode 100644 index 0000000..e783cc9 --- /dev/null +++ b/exercises/06_RTC_check/README.md @@ -0,0 +1,43 @@ +## Exercise 06: RTC Check (PCF8563) + +This exercise validates RTC read/write and power-off persistence on the T-Beam Supreme. + +It: +- Initializes PMU + I2C bus used by RTC. +- Reads RTC at startup. +- Prints RTC every 10 seconds. +- Accepts serial commands: + - `show` + - `set YYYY-MM-DD HH:MM:SS` + - `help` + +## Build + +```bash +source /home/jlpoole/rnsenv/bin/activate +pio run -e node_a +``` + +## Upload + +```bash +source /home/jlpoole/rnsenv/bin/activate +pio run -e node_a -t upload --upload-port /dev/ttyACM0 +``` + +## Monitor + +```bash +screen /dev/ttyACM0 115200 +``` + +## Suggested Persistence Test + +1. Set the RTC: + - `set 2026-02-14 17:30:00` +2. Confirm: + - `show` +3. Power off the unit for a few minutes. +4. Power on and run: + - `show` +5. Compare expected elapsed time vs RTC output. diff --git a/exercises/06_RTC_check/platformio.ini b/exercises/06_RTC_check/platformio.ini new file mode 100644 index 0000000..472385a --- /dev/null +++ b/exercises/06_RTC_check/platformio.ini @@ -0,0 +1,31 @@ +; 20260214 ChatGPT +; $Id$ +; $HeadURL$ + +[platformio] +default_envs = node_a + +[env] +platform = espressif32 +framework = arduino +board = esp32-s3-devkitc-1 +monitor_speed = 115200 +lib_deps = + lewisxhe/XPowersLib@0.3.3 + +build_flags = + -D I2C_SDA1=42 + -D I2C_SCL1=41 + -D RTC_I2C_ADDR=0x51 + -D ARDUINO_USB_MODE=1 + -D ARDUINO_USB_CDC_ON_BOOT=1 + +[env:node_a] +build_flags = + ${env.build_flags} + -D NODE_LABEL=\"A\" + +[env:node_b] +build_flags = + ${env.build_flags} + -D NODE_LABEL=\"B\" diff --git a/exercises/06_RTC_check/src/main.cpp b/exercises/06_RTC_check/src/main.cpp new file mode 100644 index 0000000..fe5f7d3 --- /dev/null +++ b/exercises/06_RTC_check/src/main.cpp @@ -0,0 +1,248 @@ +// 20260214 ChatGPT +// $Id$ +// $HeadURL$ + +#include +#include +#include + +#ifndef I2C_SDA1 +#define I2C_SDA1 42 +#endif +#ifndef I2C_SCL1 +#define I2C_SCL1 41 +#endif +#ifndef RTC_I2C_ADDR +#define RTC_I2C_ADDR 0x51 +#endif + +static XPowersLibInterface* g_pmu = nullptr; +static uint32_t g_logSeq = 0; +static uint32_t g_lastPrintMs = 0; +static String g_cmdBuf; +static bool g_lastWasCR = false; + +struct RtcDateTime { + uint16_t year; + uint8_t month; + uint8_t day; + uint8_t hour; + uint8_t minute; + uint8_t second; + uint8_t weekday; +}; + +static uint8_t toBcd(uint8_t v) { + return ((v / 10U) << 4U) | (v % 10U); +} + +static uint8_t fromBcd(uint8_t b) { + return ((b >> 4U) * 10U) + (b & 0x0FU); +} + +static void logf(const char* fmt, ...) { + char msg[196]; + va_list args; + va_start(args, fmt); + vsnprintf(msg, sizeof(msg), fmt, args); + va_end(args); + Serial.printf("[%10lu][%06lu] %s\r\n", (unsigned long)millis(), (unsigned long)g_logSeq++, msg); +} + +static bool initPmuForRtc() { + Wire1.begin(I2C_SDA1, I2C_SCL1); + + if (!g_pmu) { + g_pmu = new XPowersAXP2101(Wire1); + } + + if (!g_pmu->init()) { + logf("PMU: AXP2101 init failed"); + return false; + } + + // Keep RTC/I2C-related rails on, matching tbeam-s3-core behavior. + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO2, 3300); + g_pmu->enablePowerOutput(XPOWERS_ALDO2); + g_pmu->setPowerChannelVoltage(XPOWERS_ALDO1, 3300); + g_pmu->enablePowerOutput(XPOWERS_ALDO1); + + logf("PMU: AXP2101 ready, ALDO2=%s", + g_pmu->isPowerChannelEnable(XPOWERS_ALDO2) ? "ON" : "OFF"); + return true; +} + +static bool rtcRead(RtcDateTime& out, bool& lowVoltageFlag) { + Wire1.beginTransmission(RTC_I2C_ADDR); + Wire1.write(0x02); // seconds register + if (Wire1.endTransmission(false) != 0) { + return false; + } + + const uint8_t need = 7; + uint8_t got = Wire1.requestFrom((int)RTC_I2C_ADDR, (int)need); + if (got != need) { + return false; + } + + uint8_t sec = Wire1.read(); + uint8_t min = Wire1.read(); + uint8_t hour = Wire1.read(); + uint8_t day = Wire1.read(); + uint8_t weekday = Wire1.read(); + uint8_t month = Wire1.read(); + uint8_t year = Wire1.read(); + + lowVoltageFlag = (sec & 0x80U) != 0; + out.second = fromBcd(sec & 0x7FU); + out.minute = fromBcd(min & 0x7FU); + out.hour = fromBcd(hour & 0x3FU); + out.day = fromBcd(day & 0x3FU); + out.weekday = fromBcd(weekday & 0x07U); + out.month = fromBcd(month & 0x1FU); + uint8_t yy = fromBcd(year); + bool century = (month & 0x80U) != 0; + out.year = century ? (1900U + yy) : (2000U + yy); + + return true; +} + +static bool rtcWrite(const RtcDateTime& in) { + bool century = in.year < 2000; + uint8_t yy = (uint8_t)(in.year % 100); + uint8_t monthReg = toBcd(in.month) & 0x1FU; + if (century) { + monthReg |= 0x80U; + } + + Wire1.beginTransmission(RTC_I2C_ADDR); + Wire1.write(0x02); // seconds register + Wire1.write(toBcd(in.second) & 0x7FU); + Wire1.write(toBcd(in.minute) & 0x7FU); + Wire1.write(toBcd(in.hour) & 0x3FU); + Wire1.write(toBcd(in.day) & 0x3FU); + Wire1.write(toBcd(in.weekday) & 0x07U); + Wire1.write(monthReg); + Wire1.write(toBcd(yy)); + return Wire1.endTransmission() == 0; +} + +static bool parseSetCommand(const String& line, RtcDateTime& dt) { + int y, mo, d, h, mi, s; + if (sscanf(line.c_str(), "set %d-%d-%d %d:%d:%d", &y, &mo, &d, &h, &mi, &s) != 6) { + return false; + } + + if (y < 1900 || y > 2099) return false; + if (mo < 1 || mo > 12) return false; + if (d < 1 || d > 31) return false; + if (h < 0 || h > 23) return false; + if (mi < 0 || mi > 59) return false; + if (s < 0 || s > 59) return false; + + dt.year = (uint16_t)y; + dt.month = (uint8_t)mo; + dt.day = (uint8_t)d; + dt.hour = (uint8_t)h; + dt.minute = (uint8_t)mi; + dt.second = (uint8_t)s; + dt.weekday = 0; // Not critical for this persistence check. + return true; +} + +static void printRtcNow(const char* label) { + RtcDateTime now{}; + bool lowV = false; + if (!rtcRead(now, lowV)) { + logf("%s: RTC read failed", label); + return; + } + logf("%s: %04u-%02u-%02u %02u:%02u:%02u weekday=%u%s", + label, + (unsigned)now.year, (unsigned)now.month, (unsigned)now.day, + (unsigned)now.hour, (unsigned)now.minute, (unsigned)now.second, + (unsigned)now.weekday, + lowV ? " [LOW_VOLTAGE_FLAG]" : ""); +} + +static void handleCommand(const String& raw) { + String line = raw; + line.trim(); + if (line.length() == 0) { + return; + } + + if (line == "help") { + logf("Commands:"); + logf(" show"); + logf(" set YYYY-MM-DD HH:MM:SS"); + logf(" help"); + return; + } + if (line == "show") { + printRtcNow("RTC"); + return; + } + + RtcDateTime dt{}; + if (parseSetCommand(line, dt)) { + if (rtcWrite(dt)) { + logf("RTC set succeeded"); + printRtcNow("RTC"); + } else { + logf("RTC set failed"); + } + return; + } + + logf("Unknown command: %s", line.c_str()); +} + +void setup() { + Serial.begin(115200); + Serial.println("Sleeping for 5 seconds to allow Serial Monitor connection..."); + delay(5000); + + Serial.println("\r\n=================================================="); + Serial.println("Exercise 06: RTC check (PCF8563)"); + Serial.println("=================================================="); + Serial.printf("RTC I2C: SDA1=%d SCL1=%d ADDR=0x%02X\r\n", I2C_SDA1, I2C_SCL1, RTC_I2C_ADDR); + + initPmuForRtc(); + + logf("Type 'help' for commands."); + logf("Power-off persistence test:"); + logf(" 1) set time"); + logf(" 2) power off for a few minutes"); + logf(" 3) power on and run 'show' before any GPS sync"); + printRtcNow("RTC startup"); +} + +void loop() { + while (Serial.available() > 0) { + char c = (char)Serial.read(); + if (c == '\r' || c == '\n') { + // Handle CR, LF, and CRLF/LFCR cleanly as one line ending. + if ((c == '\n' && g_lastWasCR) || (c == '\r' && !g_lastWasCR && g_cmdBuf.length() == 0)) { + g_lastWasCR = (c == '\r'); + continue; + } + handleCommand(g_cmdBuf); + g_cmdBuf = ""; + g_lastWasCR = (c == '\r'); + } else { + g_lastWasCR = false; + g_cmdBuf += c; + if (g_cmdBuf.length() > 120) { + g_cmdBuf = ""; + logf("Input line too long, buffer cleared"); + } + } + } + + uint32_t nowMs = millis(); + if ((uint32_t)(nowMs - g_lastPrintMs) >= 10000) { + g_lastPrintMs = nowMs; + printRtcNow("RTC periodic"); + } +} diff --git a/exercises/README.md b/exercises/README.md index c48c291..900ac7d 100644 --- a/exercises/README.md +++ b/exercises/README.md @@ -4,7 +4,7 @@ There are three buttons ![](../img/20260212_182300_Thu.png) -From Antenna to USB port: +Listed in order from Antenna to USB port: 1) RESET 2) POWER 3) BOOT @@ -16,15 +16,22 @@ The RESET button only needs to be depressed for less than 1 second. Doing so wi If your unit is powered OFF, simply depress the POWER button will start the unit. If the unit is powered ON, then depressing the POWER button and holding it down for 6 second will cause the unit to power down. The OLED display will go dark when the unit has successfully been powered down. ## BOOT -A) TODO: what happens when unit is powered ON? -B) TODO: what happens when unit is powered OFF? -C) To upload new binary image: depress the BOOT button and hold down, then while holding down the BOOT button disconnect the USB line and then reconnect the USB line and then lift up on the BOOT button. This will cause the unit to await an upload of an image to be stored in its FLASH memory. See further how to flash a new image in the section "Flashing Binary". Note: although the uploader may state it is trying to reset after successful installation of the new image, it seems that software attempt does not work and you have to manually depress the unit's RESET button to force a RESET. Remember, if you want to see the boot's posting, you should have your terminal ready to run "screen" so you capture the initial postings after you click RESET. +A) TODO: what happens when unit is powered ON and you depress BOOT? +B) TODO: what happens when unit is powered OFF and you depress BOOT? +C) To upload new binary image: depress the BOOT button and hold down, then while holding down the BOOT button disconnect the USB line and then reconnect the USB line and then lift up on the BOOT button. This sequence will cause the unit to await an upload of an image over USB to be stored in its FLASH memory. You can place the unit in this mode and then several minutes later perform the upload from your console, the unit will duly await an upload session. See further how to flash a new image in the section "Flashing Binary". Note: although the uploader may state it is trying to reset after successful installation of the new image, it seems that software attempt does not work and you have to manually depress the unit's RESET button to force a RESET. Remember, if you want to see the boot's posting, you should have your terminal ready to run "screen" so you capture the initial postings after you click RESET. +# Button Protocol For Uploading New Image +Pushing BOOT when the unit is currently running will not do anything. You have to shut the unit down first. So: +1) Depress POWER button for 6 seconds +2) Depress BOOT button and while depressed, click RESET button +3) Lift up BOOT button +The unit is now waiting for the serial console so commence an upload. You are not time restricted, so you can go through the above 3 steps and then 5 minutes later proceed with an upload in the command console. + # Exercises -These are progressve tests you can run to confirm how to access the unit's functionality and validate your workbench. +These are progressve tests you can run to confirm how to access the unit's functionality and validate your workbench. Each exercise has it's own README.md Exercise 00: 00_usb_radio_check -Exercise 01: ASCII ping-pong over LoRa (serial only) +Exercise 01: ASCII ping-pong over LoRa (serial only). Using two units, each sends a message to the other and you monitor both units through two screen consoles. Exercise 02: Add OLED display @@ -74,3 +81,8 @@ shared board pin headers in one place: boards/ tbeam-s3-core_pins.h +# Features +## SD Card +You can read and write to SD cards that are FAT formatted. (Can they be Linux formatted?) +## Real Time Clock ("RTC") +## Microphone