Initialisation depot

This commit is contained in:
Serge NOEL
2026-02-10 12:12:11 +01:00
commit c3176e8d79
818 changed files with 52573 additions and 0 deletions

View File

@@ -0,0 +1,91 @@
/**
* @file Config.h
* @brief Configuration management for the Locomotive Test Bench
*
* This module handles persistent storage of system settings
* using ESP32's Preferences library (NVS - Non-Volatile Storage).
*
* @author Locomotive Test Bench Project
* @date 2025
*/
#ifndef CONFIG_H
#define CONFIG_H
#include <Arduino.h>
#include <Preferences.h>
/**
* @struct SystemConfig
* @brief System operation configuration
*
* Stores current control mode and locomotive parameters.
*/
struct SystemConfig {
bool isDCCMode; ///< True = DCC digital, False = DC analog
bool is3Rail; ///< True = 3-rail mode, False = 2-rail mode
bool powerOn; ///< True = power enabled, False = power off
uint16_t dccAddress; ///< DCC locomotive address (1-10239)
uint8_t speed; ///< Speed setting (0-100%)
uint8_t direction; ///< Direction: 0 = reverse, 1 = forward
uint32_t dccFunctions; ///< Bit field for DCC functions F0-F28
};
/**
* @class Config
* @brief Configuration manager with persistent storage
*
* Manages all configuration parameters and provides persistent
* storage using ESP32's NVS (Non-Volatile Storage) via Preferences.
*
* @note All settings are automatically saved to flash memory
* and persist across reboots.
*/
class Config {
public:
/**
* @brief Constructor - initializes with default values
*/
Config();
/**
* @brief Initialize preferences and load saved settings
*
* Must be called during setup() before using configuration.
* Loads previously saved settings from NVS.
*/
void begin();
/**
* @brief Save current configuration to NVS
*
* Writes all system settings to persistent storage.
* Should be called after any configuration changes.
*/
void save();
/**
* @brief Load configuration from NVS
*
* Reads previously saved settings. Called automatically
* by begin(), but can be called manually to reload.
*/
void load();
/**
* @brief Reset all settings to defaults
*
* Clears all stored preferences and resets to factory defaults.
* Use with caution - all saved settings will be lost.
*/
void reset();
SystemConfig system; ///< System operation settings
private:
Preferences preferences; ///< ESP32 NVS preferences object
};
#endif // CONFIG_H
#endif

View File

@@ -0,0 +1,226 @@
/**
* @file DCCGenerator.h
* @brief NMRA DCC (Digital Command Control) signal generator
*
* Generates DCC protocol signals for controlling digital model locomotives.
* Implements NMRA DCC standard with support for:
* - Short addresses (1-127) and long addresses (128-10239)
* - 128-step speed control
* - Function control (F0-F12 implemented, expandable to F28)
*
* @note Requires external DCC booster circuit for track output
* @author Locomotive Test Bench Project
* @date 2025
*/
#ifndef DCC_GENERATOR_H
#define DCC_GENERATOR_H
#include <Arduino.h>
// Pin definitions for DCC output
// These share the same pins as the motor controller (LM18200)
// In DCC mode: GPIO 18 = DCC Signal A, GPIO 19 = DCC Signal B
// In DC mode: GPIO 18 = PWM, GPIO 19 = Direction
#define DCC_PIN_A 18 ///< DCC Signal A output pin (shared with MOTOR_PWM_PIN)
#define DCC_PIN_B 19 ///< DCC Signal B output pin (shared with MOTOR_DIR_PIN)
// DCC timing constants (microseconds) - NMRA standard
#define DCC_ONE_BIT_TOTAL_DURATION_MAX 64 ///< Max duration for '1' bit
#define DCC_ONE_BIT_TOTAL_DURATION_MIN 55 ///< Min duration for '1' bit
#define DCC_ZERO_BIT_TOTAL_DURATION_MAX 10000 ///< Max duration for '0' bit
#define DCC_ZERO_BIT_TOTAL_DURATION_MIN 95 ///< Min duration for '0' bit
#define DCC_ONE_BIT_PULSE_DURATION 58 ///< Half-cycle for '1' bit (58μs)
#define DCC_ZERO_BIT_PULSE_DURATION 100 ///< Half-cycle for '0' bit (100μs)
/**
* @class DCCGenerator
* @brief DCC protocol signal generator
*
* Generates NMRA-compliant DCC signals for digital locomotive control.
* Supports variable speed, direction, and function commands.
*
* @warning Output signals are low-power logic level.
* Requires external booster circuit for track connection.
*/
class DCCGenerator {
public:
/**
* @brief Constructor
*/
DCCGenerator();
/**
* @brief Initialize DCC generator hardware
*
* Configures output pins to idle state.
*/
void begin();
/**
* @brief Enable DCC signal generation
*
* Starts sending DCC packets to the track.
*/
void enable();
/**
* @brief Disable DCC signal generation
*
* Stops DCC output and sets pins to safe state.
*/
void disable();
/**
* @brief Set locomotive speed and direction
* @param address DCC address (1-10239)
* @param speed Speed value (0-100%)
* @param direction Direction: 0 = reverse, 1 = forward
*/
void setLocoSpeed(uint16_t address, uint8_t speed, uint8_t direction);
/**
* @brief Control DCC function
* @param address DCC address (1-10239)
* @param function Function number (0-28)
* @param state true = ON, false = OFF
*/
void setFunction(uint16_t address, uint8_t function, bool state);
/**
* @brief Update DCC signal generation
*
* Must be called regularly from main loop to send DCC packets.
* Sends speed and function packets at appropriate intervals.
*/
void update();
/**
* @brief Check if DCC is enabled
* @return true if DCC mode is active
*/
bool isEnabled() { return enabled; }
// Programming Track Methods
/**
* @brief Factory reset decoder (send CV8 = 8)
* @return true if successful
*/
bool factoryReset();
/**
* @brief Set decoder address
* @param address New address (1-10239)
* @return true if successful
*/
bool setDecoderAddress(uint16_t address);
/**
* @brief Read CV value from decoder
* @param cv CV number (1-1024)
* @param value Pointer to store read value
* @return true if successful
*/
bool readCV(uint16_t cv, uint8_t* value);
/**
* @brief Write CV value to decoder
* @param cv CV number (1-1024)
* @param value Value to write (0-255)
* @return true if successful
*/
bool writeCV(uint16_t cv, uint8_t value);
private:
bool enabled; ///< DCC generator enabled flag
uint16_t currentAddress; ///< Current locomotive address
uint8_t currentSpeed; ///< Current speed setting
uint8_t currentDirection; ///< Current direction (0=rev, 1=fwd)
uint32_t functionStates; ///< Function states bit field
unsigned long lastPacketTime; ///< Timestamp of last packet sent
static const unsigned long PACKET_INTERVAL = 30; ///< Packet interval (ms)
// DCC packet construction and transmission
/**
* @brief Send a complete DCC packet
* @param data Byte array containing packet data
* @param length Number of bytes in packet
*/
void sendPacket(uint8_t* data, uint8_t length);
/**
* @brief Send a single DCC bit
* @param value true = '1' bit, false = '0' bit
*/
void sendBit(bool value);
/**
* @brief Send DCC preamble (14 '1' bits)
*/
void sendPreamble();
/**
* @brief Send a single byte
* @param data Byte to send
*/
void sendByte(uint8_t data);
/**
* @brief Send speed command packet
*/
void sendSpeedPacket();
/**
* @brief Send function group packet
* @param group Function group number
*/
void sendFunctionPacket(uint8_t group);
/**
* @brief Calculate XOR checksum
* @param data Data bytes
* @param length Number of bytes
* @return XOR checksum byte
*/
uint8_t calculateChecksum(uint8_t* data, uint8_t length);
// Programming track helper methods
/**
* @brief Send service mode packet (programming track)
* @param data Packet data bytes
* @param length Number of bytes
*/
void sendServiceModePacket(uint8_t* data, uint8_t length);
/**
* @brief Verify byte write on programming track
* @param cv CV number
* @param value Expected value
* @return true if ACK detected
*/
bool verifyByte(uint16_t cv, uint8_t value);
/**
* @brief Wait for ACK pulse from decoder
* @return true if ACK detected within timeout
*/
bool waitForAck();
/**
* @brief Calibrate ACS712 current sensor zero point
*
* Reads current sensor with no load to establish baseline.
* Should be called during initialization.
*/
void calibrateCurrentSensor();
};
// Programming track current sensing threshold (mA)
#define PROG_ACK_CURRENT_THRESHOLD 60 ///< Minimum ACK current (mA)
#endif

View File

@@ -0,0 +1,105 @@
/**
* @file LEDIndicator.h
* @brief WS2812 RGB LED status indicators
*
* Provides visual feedback using two WS2812 LEDs:
* - LED 0: Power status (Green = ON, Red = OFF)
* - LED 1: Mode indicator (Blue = DCC, Yellow = Analog)
*
* @author Locomotive Test Bench Project
* @date 2025
*/
#ifndef LED_INDICATOR_H
#define LED_INDICATOR_H
#include <Arduino.h>
// #include <FastLED.h>
// Pin definition for WS2812 LEDs
#define LED_DATA_PIN 4 ///< Data pin for WS2812 strip
#define NUM_LEDS 4 ///< Number of LEDs (Power + Mode)
// // LED indices
#define LED_POWER 0 ///< Power status indicator
#define LED_MODE 1 ///< Mode indicator (DCC/Analog)
// /**
// * @class LEDIndicator
// * @brief Manages WS2812 RGB LED status displays
// *
// * Controls two LEDs for system status indication:
// * - Power LED: Shows system power state with boot animation
// * - Mode LED: Shows control mode with pulsing effect
// */
class LEDIndicator {
public:
/**
* @brief Constructor
*/
LEDIndicator();
/**
* @brief Initialize LED hardware
*
* Configures FastLED library and sets LEDs to off state.
*/
void begin();
/**
* @brief Update LED display
*
* Must be called regularly from main loop to update
* pulsing effects and animations.
*/
void update();
/**
* @brief Set power status
* @param on true = power on (green), false = off (red)
*/
void setPowerOn(bool on);
/**
* @brief Set operating mode
* @param isDCC true = DCC mode (blue), false = Analog (yellow)
*/
void setMode(bool isDCC);
/**
* @brief Set LED brightness
* @param brightness Brightness level (0-255)
*/
void setBrightness(uint8_t brightness);
/**
* @brief Play power-on animation sequence
*
* Shows 3-flash boot sequence on power LED.
*/
void powerOnSequence();
/**
* @brief Play mode change animation
*
* Smooth fade transition when switching modes.
*/
void modeChangeEffect();
// private:
// CRGB leds[NUM_LEDS]; ///< LED array
// bool powerOn; ///< Power status flag
// bool dccMode; ///< Mode flag (DCC/Analog)
// uint8_t brightness; ///< Current brightness level
// unsigned long lastUpdate; ///< Last update timestamp
// uint8_t pulsePhase; ///< Pulse animation phase
// // LED color definitions
// static constexpr CRGB COLOR_POWER_ON = CRGB::Green; ///< Power ON color
// static constexpr CRGB COLOR_POWER_OFF = CRGB::Red; ///< Power OFF color
// static constexpr CRGB COLOR_DCC = CRGB::Blue; ///< DCC mode color
// static constexpr CRGB COLOR_ANALOG = CRGB::Yellow; ///< Analog mode color
// static constexpr CRGB COLOR_OFF = CRGB::Black; ///< LED off state
};
#endif

View File

@@ -0,0 +1,101 @@
/**
* @file MotorController.h
* @brief DC motor control using LM18200 H-Bridge driver
*
* Provides bidirectional PWM motor control with brake functionality.
* Suitable for DC analog model locomotive control.
*
* @author Locomotive Test Bench Project
* @date 2025
*/
#ifndef MOTOR_CONTROLLER_H
#define MOTOR_CONTROLLER_H
#include <Arduino.h>
// Pin definitions for LM18200
// Adjusted for ESP32-2432S028R available GPIOs
#define MOTOR_PWM_PIN 18 ///< PWM signal output pin
#define MOTOR_DIR_PIN 19 ///< Direction control pin
#define MOTOR_BRAKE_PIN 23 ///< Brake control pin (active low)
/**
* @class MotorController
* @brief Controls DC motor via LM18200 H-Bridge
*
* Features:
* - Variable speed control (0-100%)
* - Bidirectional operation (forward/reverse)
* - Electronic braking
* - 20kHz PWM frequency for silent operation
* - 8-bit resolution (256 speed steps)
*/
class MotorController {
public:
/**
* @brief Constructor
*/
MotorController();
/**
* @brief Initialize motor controller hardware
*
* Configures GPIO pins and PWM channels.
* Sets motor to safe stopped state.
*/
void begin();
/**
* @brief Set motor speed and direction
* @param speed Speed value (0-100%)
* @param direction Direction: 0 = reverse, 1 = forward
*/
void setSpeed(uint8_t speed, uint8_t direction);
/**
* @brief Stop motor (coast to stop)
*
* Sets speed to zero and releases brake.
* Motor will coast to a stop.
*/
void stop();
/**
* @brief Apply electronic brake
*
* Activates LM18200 brake function for quick stop.
* More aggressive than stop().
*/
void brake();
/**
* @brief Update motor controller state
*
* Called from main loop for safety checks.
* Currently placeholder for future features.
*/
void update();
/**
* @brief Get current speed setting
* @return Speed (0-100%)
*/
uint8_t getCurrentSpeed() { return currentSpeed; }
/**
* @brief Get current direction
* @return Direction: 0 = reverse, 1 = forward
*/
uint8_t getCurrentDirection() { return currentDirection; }
private:
uint8_t currentSpeed; ///< Current speed setting (0-100)
uint8_t currentDirection; ///< Current direction (0=rev, 1=fwd)
static const int PWM_CHANNEL = 0; ///< ESP32 PWM channel
static const int PWM_FREQUENCY = 20000; ///< PWM frequency in Hz
static const int PWM_RESOLUTION = 8; ///< PWM resolution in bits
};
#endif

View File

@@ -0,0 +1,59 @@
/**
* @file RelayController.h
* @brief Relay control for switching between 2-rail and 3-rail track configurations
*
* Controls a relay module to switch track wiring between:
* - 2-rail mode: Standard DC/DCC operation
* - 3-rail mode: Center rail + outer rails configuration
*
* @author Locomotive Test Bench Project
* @date 2025
*/
#ifndef RELAY_CONTROLLER_H
#define RELAY_CONTROLLER_H
#include <Arduino.h>
// Pin definition for relay control
#define RELAY_PIN 4 ///< Relay control pin (active HIGH)
/**
* @class RelayController
* @brief Controls relay for track configuration switching
*
* Simple relay control for switching between 2-rail and 3-rail modes.
* Relay energized = 3-rail mode
* Relay de-energized = 2-rail mode
*/
class RelayController {
public:
/**
* @brief Constructor
*/
RelayController();
/**
* @brief Initialize relay controller hardware
*
* Configures GPIO pin and sets to default 2-rail mode.
*/
void begin();
/**
* @brief Set rail mode
* @param is3Rail true = 3-rail mode, false = 2-rail mode
*/
void setRailMode(bool is3Rail);
/**
* @brief Get current rail mode
* @return true if 3-rail mode, false if 2-rail mode
*/
bool is3RailMode() { return is3Rail; }
private:
bool is3Rail; ///< Current rail mode state
};
#endif // RELAY_CONTROLLER_H

View File

@@ -0,0 +1,188 @@
/**
* @file TouchscreenUI.h
* @brief Touchscreen user interface for locomotive test bench
*
* Provides a graphical interface on the ILI9341 TFT display with touch controls for:
* - Power ON/OFF button
* - DCC/Analog mode switching
* - Speed slider (0-100%)
* - 2-rail/3-rail configuration selector
* - Direction control
* - Status display
*
* @author Locomotive Test Bench Project
* @date 2025
*/
#ifndef TOUCHSCREEN_UI_H
#define TOUCHSCREEN_UI_H
#include <Arduino.h>
#include <TFT_eSPI.h>
#include <XPT2046_Touchscreen.h>
#include "Config.h"
#include "MotorController.h"
#include "DCCGenerator.h"
#include "RelayController.h"
// Touch calibration values for ESP32-2432S028R
#define TS_MIN_X 200
#define TS_MAX_X 3700
#define TS_MIN_Y 200
#define TS_MAX_Y 3750
// UI Colors
#define COLOR_BG 0x0000 // Black
#define COLOR_PANEL 0x2945 // Dark gray
#define COLOR_TEXT 0xFFFF // White
#define COLOR_POWER_ON 0x07E0 // Green
#define COLOR_POWER_OFF 0xF800 // Red
#define COLOR_DCC 0x07FF // Cyan
#define COLOR_ANALOG 0xFFE0 // Yellow
#define COLOR_SLIDER 0x435C // Gray
#define COLOR_SLIDER_ACTIVE 0x07E0 // Green
#define COLOR_BUTTON 0x4A49 // Button gray
#define COLOR_BUTTON_ACTIVE 0x2124 // Darker gray
#define COLOR_FUNCTION_OFF 0x31A6 // Dark blue-gray
#define COLOR_FUNCTION_ON 0xFD20 // Orange
/**
* @struct Button
* @brief Simple button structure for touch areas
*/
struct Button {
int16_t x, y, w, h;
String label;
uint16_t color;
bool visible;
};
/**
* @class TouchscreenUI
* @brief Manages touchscreen display and user interactions
*
* Provides complete UI for controlling the locomotive test bench,
* handling touch events, updating displays, and coordinating with
* motor controller, DCC generator, and relay controller.
*/
class TouchscreenUI {
public:
/**
* @brief Constructor
* @param cfg Pointer to configuration object
* @param motor Pointer to motor controller
* @param dcc Pointer to DCC generator
* @param relay Pointer to relay controller
*/
TouchscreenUI(Config* cfg, MotorController* motor, DCCGenerator* dcc, RelayController* relay);
/**
* @brief Initialize touchscreen and display
*
* Sets up TFT display, touch controller, and draws initial UI.
*/
void begin();
/**
* @brief Update UI and handle touch events
*
* Must be called regularly from main loop.
* Handles touch detection, UI updates, and state changes.
*/
void update();
/**
* @brief Force full screen redraw
*/
void redraw();
/**
* @brief Get power state
* @return true if power is ON
*/
bool isPowerOn() { return powerOn; }
private:
TFT_eSPI tft;
XPT2046_Touchscreen touch;
Config* config;
MotorController* motorController;
DCCGenerator* dccGenerator;
RelayController* relayController;
bool powerOn;
uint8_t lastSpeed;
bool lastDirection;
bool lastIsDCC;
bool lastIs3Rail;
uint32_t lastDccFunctions;
// Programming screen state
bool programmingMode;
uint16_t cvNumber;
uint8_t cvValue;
uint16_t newAddress;
uint8_t keypadMode; // 0=address, 1=CV number, 2=CV value
// UI element positions
Button btnPower;
Button btnMode;
Button btnRails;
Button btnDirection;
Button btnDccAddress;
// DCC function buttons (F0-F12)
#define NUM_FUNCTIONS 13
Button btnFunctions[NUM_FUNCTIONS];
// Programming mode buttons
Button btnProgramming;
Button btnProgBack;
Button btnFactoryReset;
Button btnSetAddress;
Button btnReadCV;
Button btnWriteCV;
// Numeric keypad (0-9, backspace, enter)
#define NUM_KEYPAD_BUTTONS 12
Button btnKeypad[NUM_KEYPAD_BUTTONS];
// Slider position and state
int16_t sliderX, sliderY, sliderW, sliderH;
int16_t sliderKnobX;
bool sliderPressed;
// Private methods
void drawUI();
void drawPowerButton();
void drawModeButton();
void drawRailsButton();
void drawDirectionButton();
void drawSpeedSlider();
void drawStatusBar();
void drawDccFunctions();
void drawDccAddressButton();
void drawProgrammingScreen();
void drawNumericKeypad();
void drawProgrammingStatus();
void handleTouch(int16_t x, int16_t y);
void updatePowerState(bool state);
void updateMode(bool isDCC);
void updateRailMode(bool is3Rail);
void updateDirection();
void updateSpeed(uint8_t newSpeed);
void toggleDccFunction(uint8_t function);
void enterProgrammingMode();
void exitProgrammingMode();
void handleKeypadPress(uint8_t key);
void performFactoryReset();
void performSetAddress();
void performReadCV();
void performWriteCV();
int16_t mapTouch(int16_t value, int16_t inMin, int16_t inMax, int16_t outMin, int16_t outMax);
};
#endif // TOUCHSCREEN_UI_H