#include #include #include #include #include #include // Brochage natif de la Waveshare RP2350-USB-A #define HOST_PIN_DP 12 // USB-A D+ (D- est automatiquement sur GP13) #define NUM_PIXELS 1 #define PIN_LED_RGB 16 // LED RGB WS2812 intégrée #define EEPROM_SIZE 32 // Sécurité : failsafe, watchdog et identification du volant #define TIMEOUT_FAILSAFE_MS 500 // Sans rapport USB valide depuis X ms -> canaux au neutre #define WATCHDOG_TIMEOUT_MS 500 // Reboot matériel si le cœur 0 se fige #define G29_VID 0x046D #define G29_PID_PS4 0xC260 // G29 en mode PS4 (le mode PS3 = 0xC24F a un autre format de rapport) #define G29_REPORT_ID 0x01 // Masques des palettes et boutons dans report[6] #define PALETTE_MOINS_MASK 0x01 // L1 (Palette gauche : Rétrograder) #define PALETTE_PLUS_MASK 0x02 // R1 (Palette droite : Monter un rapport) #define BOUTON_ARM_MASK 0x08 // R2 (Bascule Armé / Désarmé) // Masques additionnels dans report[54] (Molette et boutons + / - / Enter en mode PS4) #define DIAL_ENTER_MASK 0x01 // Bouton central de la molette (Sauvegarde Flash) #define DIAL_CCW_MASK 0x02 // Molette sens anti-horaire (Dureté -) #define DIAL_CW_MASK 0x04 // Molette sens horaire (Dureté +) #define BOUTON_MOINS_MASK 0x08 // Bouton [-] (Dureté -) #define BOUTON_PLUS_MASK 0x10 // Bouton [+] (Dureté +) // Armement ELRS : AUX1 = canal 5 (réservé, ne peut pas être mappé ailleurs) #define CANAL_ARM 5 // Bornes officielles CRSF #define CRSF_VAL_MIN 172 // ~988 us #define CRSF_VAL_MID 992 // 1500 us (Neutre) #define CRSF_VAL_MAX 1811 // ~2012 us // Plages de gaz progressives (Marche avant : rapports 1, 2, 3) #define GAZ_AVANT_MIN 1065 const uint16_t GAZ_AVANT_MAX_PAR_VITESSE[3] = { 1100, // 1ère vitesse (Manœuvre) 1150, // 2ème vitesse (Normale) 1220 // 3ème vitesse (Rapide) }; #define GAZ_ARRIERE_MIN 905 #define GAZ_ARRIERE_MAX 850 #define DEADZONE_PEDALE 800 // Configuration par défaut du volant G29 #define CENTRE_VOLANT_BRUT 32768 #define DELTA_MAX_VOLANT_BRUT 31600 // ~96,4% de la demi-course (début de la butée logicielle) #define HYSTERESIS_MUR_BRUT 450 // ~1,6° de marge pour repousser franchement sans osciller #define ANGLE_DEFAUT_TOTAL 240.0f // Plage totale par defaut : 240 degres (+/- 120 degres) #define EXPO_DEFAUT 0.25f // 0.0f = Lineaire, 0.25f = Doux au centre (FPU RP2350) #define FORCE_RESSORT_DEFAUT 140 // Force du retour au centre : 0 a 255 #define PENTE_RESSORT_G29 7 // Raideur autour du centre : 1 a 7 #define ETAPES_INIT_FFB_TOTAL 2 // Nombre d'etapes d'init FFB (0=Range, 1=Spring) #define VIBRATION_DEFAUT 100 // Intensite par defaut des vibrations (0 a 100%) #define MAGIC_NUMBER_CONFIG 0x49 // Identifiant de validite en EEPROM (mis a jour pour 240 degres) Adafruit_NeoPixel rgb_led(NUM_PIXELS, PIN_LED_RGB, NEO_GRB + NEO_KHZ800); Adafruit_USBH_Host USBHost; volatile uint16_t crsf_channels[16] = { CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MIN, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, // Canal 5 (ARM) : désarmé CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID }; struct ConfigG29 { uint8_t volant; uint8_t accel; uint8_t frein; uint8_t embrayage; uint8_t forceRessort; // Force du retour au centre : 0 à 255 uint16_t angleSouhaiteTotal; // Plage totale en degrés : 40 à 900 float expoVolant; // Expo volant : 0.0f à 0.8f uint8_t intensiteVibration; // Intensité globale des vibrations : 0 à 100% uint8_t magicNumber; // Identifiant de validité en EEPROM (MAGIC_NUMBER_CONFIG) }; volatile ConfigG29 configSysteme; volatile int32_t maxDeltaVolant = 0; void recalculerParametresVolant() { // Le G29 en mode PS4 redistribue ses 65535 points (16-bit) sur la plage configurée par cmdRange. // Pour les plages réduites (< 900°), la butée logicielle démarre à ~96,4% de la demi-course (31600 points). // À 900° complets, on utilise la course mécanique intégrale (32768) pour s'appuyer sur la butée physique. maxDeltaVolant = (configSysteme.angleSouhaiteTotal >= 900) ? 32768 : DELTA_MAX_VOLANT_BRUT; } // Boîte séquentielle : -1 = R, 0 = N (Point Mort), 1 = 1ère, 2 = 2ème, 3 = 3ème volatile int8_t rapportEngage = 0; volatile bool palettePlusDejaEnfoncee = false; volatile bool paletteMoinsDejaEnfoncee = false; volatile bool majLedRequise = true; // Armement (bascule par R2) : écrit uniquement par le cœur 1 volatile bool estArme = false; volatile bool boutonArmDejaEnfonce = false; volatile int8_t logArmRequis = 0; // 1 = armé, -1 = désarmé, 2 = armement refusé // État USB Host et diagnostic inter-cœurs volatile uint8_t g29_dev_addr = 0; volatile uint8_t g29_instance = 0; volatile uint16_t g29_desc_len = 0; volatile uint16_t g29_vid = 0; volatile uint16_t g29_pid = 0; volatile bool volant_est_pret = false; volatile uint32_t dernierRapportUSB_ms = 0; volatile uint32_t momentConnexionUSB_ms = 0; volatile bool logMountRequis = false; volatile int8_t statutEnvoiLed = 0; // Failsafe et diagnostic volatile bool failsafeActif = true; // Écrit uniquement par le cœur 0 volatile bool demandeRetourNeutre = false; // Cœur 0 -> Cœur 1 : forcer le point mort volatile uint32_t compteurRapportsOK = 0; // Écrit uniquement par le cœur 1 volatile uint32_t compteurRapportsRejetes = 0; volatile uint16_t dernierRejetLen = 0; volatile uint8_t dernierRejetId = 0; volatile bool logRejetRequis = false; volatile uint16_t rejet_vid = 0; volatile uint16_t rejet_pid = 0; volatile uint8_t dernierMasqueLedG29 = 0xFF; volatile uint8_t etapeEnvoiLed = 0; volatile uint8_t etapeInitMoteur = 0; // Variables pour le réglage FFB à la volée (Molette / Boutons +/- et Série) volatile bool majRessortRequise = false; volatile bool majRangeRequise = false; volatile bool dialPlusDejaEnfonce = false; volatile bool dialMoinsDejaEnfonce = false; volatile bool dialEnterDejaEnfonce = false; volatile uint32_t momentDernierChangementDurete_ms = 0; volatile bool logDureteRequis = false; volatile bool demandeSauvegardeEEPROM = false; volatile bool sauvegardeDifferee = false; // Variables pour les vibrations haptiques et la télémétrie volatile uint8_t rugositeTerrainExterne = 0; // 0 à 255 (pilotable via CRSF télémétrie / FC) volatile float dernierAccelPct = 0.0f; // 0.0 à 100.0% volatile float dernierFreinPct = 0.0f; // 0.0 à 100.0% volatile uint32_t momentDernierChocRapport_ms = 0; // Horodatage du passage de vitesse volatile int8_t directionDernierChocRapport = 0; // -1 gauche, +1 droite volatile bool forceEstAuNeutre = false; volatile int32_t dernierVolantCentre = 0; // Position mesurée du volant par rapport au centre volatile bool murActifDroite = false; volatile bool murActifGauche = false; char serialBuffer[32]; uint8_t serialBufferIdx = 0; void reinitialiserCanauxCRSF() { for (int i = 0; i < 16; i++) { crsf_channels[i] = CRSF_VAL_MID; } crsf_channels[CANAL_ARM - 1] = CRSF_VAL_MIN; // Toujours désarmé par défaut } void reinitialiserConfigurationDefaut() { memset((void*)&configSysteme, 0, sizeof(ConfigG29)); configSysteme.volant = 1; configSysteme.accel = 2; configSysteme.frein = 3; configSysteme.embrayage = 4; configSysteme.forceRessort = FORCE_RESSORT_DEFAUT; configSysteme.angleSouhaiteTotal = ANGLE_DEFAUT_TOTAL; configSysteme.expoVolant = EXPO_DEFAUT; configSysteme.intensiteVibration = VIBRATION_DEFAUT; configSysteme.magicNumber = MAGIC_NUMBER_CONFIG; recalculerParametresVolant(); } void sauvegarderConfiguration() { ConfigG29 cfgActuelle; memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29)); ConfigG29 cfgStockee; EEPROM.get(0, cfgStockee); if (memcmp(&cfgActuelle, &cfgStockee, sizeof(ConfigG29)) == 0) { return; // Déjà synchronisé : évite un gel du Cœur 1 et préserve les cycles Flash } rp2040.wdt_reset(); // Note : EEPROM.commit() gère déjà automatiquement idleOtherCore() / resumeOtherCore() memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29)); EEPROM.put(0, cfgActuelle); EEPROM.commit(); Serial.println(">> Configuration sauvegardée en mémoire Flash !"); } void afficherConfiguration() { Serial.println("\n--- Configuration G29-CRSF (Waveshare RP2350-USB-A) ---"); Serial.printf("Volant (V) : Canal %d\n", configSysteme.volant); Serial.printf("Accel (A) : Canal %d\n", configSysteme.accel); Serial.printf("Frein (F) : Canal %d\n", configSysteme.frein); Serial.printf("Embrayage (E) : Canal %d\n", configSysteme.embrayage); Serial.printf("ARM (R2) : Canal %d (reserve)\n", CANAL_ARM); Serial.printf("Durete FFB (D) : %d / 255 (%d%%) [Molette / Boutons +/- ou D=xxx]\n", configSysteme.forceRessort, (configSysteme.forceRessort * 100) / 255); Serial.printf("Plage Volant(P): %d degres [P=40..900]\n", configSysteme.angleSouhaiteTotal); Serial.printf("Expo Volant(X) : %.2f [X=0.00..0.80]\n", configSysteme.expoVolant); Serial.printf("Vibrations (T) : %d%% [T=0..100] (Mix 12Hz/60Hz + Telemetrie)\n", configSysteme.intensiteVibration); Serial.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, S(save), R(reset), B(bootsel), ?"); } void chargerConfiguration() { ConfigG29 cfgStockee; EEPROM.get(0, cfgStockee); memcpy((void*)&configSysteme, &cfgStockee, sizeof(ConfigG29)); bool conflitArm = configSysteme.volant == CANAL_ARM || configSysteme.accel == CANAL_ARM || configSysteme.frein == CANAL_ARM || configSysteme.embrayage == CANAL_ARM; bool canauxValides = (configSysteme.volant >= 1 && configSysteme.volant <= 16) && (configSysteme.accel >= 1 && configSysteme.accel <= 16) && (configSysteme.frein >= 1 && configSysteme.frein <= 16) && (configSysteme.embrayage >= 1 && configSysteme.embrayage <= 16); bool canauxDistincts = (configSysteme.volant != configSysteme.accel) && (configSysteme.volant != configSysteme.frein) && (configSysteme.volant != configSysteme.embrayage) && (configSysteme.accel != configSysteme.frein) && (configSysteme.accel != configSysteme.embrayage) && (configSysteme.frein != configSysteme.embrayage); bool expoValide = !isnan(configSysteme.expoVolant) && (configSysteme.expoVolant >= 0.0f) && (configSysteme.expoVolant <= 0.8f); bool angleValide = (configSysteme.angleSouhaiteTotal >= 40) && (configSysteme.angleSouhaiteTotal <= 900); bool vibValide = (configSysteme.intensiteVibration >= 10) && (configSysteme.intensiteVibration <= 100); if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitArm || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide) { if (conflitArm) Serial.println("!! Un axe etait mappe sur le canal ARM : configuration reinitialisee !!"); else if (!canauxValides || !canauxDistincts) Serial.println("!! Conflit ou canal invalide en EEPROM : configuration reinitialisee !!"); else if (!expoValide || !angleValide || !vibValide) Serial.println("!! Valeur invalide en EEPROM : configuration reinitialisee !!"); else Serial.println(">> Initialisation configuration d'usine par defaut..."); reinitialiserConfigurationDefaut(); sauvegarderConfiguration(); } else { recalculerParametresVolant(); } } // ------------------------------------------------------------------------- // GESTION SÉRIE NON BLOQUANTE // ------------------------------------------------------------------------- void demanderOuExecuterSauvegarde() { if (estArme) { sauvegardeDifferee = true; Serial.println(">> Modification appliquee (sauvegarde Flash differee au desarmement)."); } else { momentDernierChangementDurete_ms = 0; sauvegardeDifferee = false; sauvegarderConfiguration(); } } void traiterLigneSerie(char* commande) { if (commande[0] == '?') { afficherConfiguration(); return; } if (commande[0] == 'B' || commande[0] == 'b') { if (estArme) { Serial.println("!! Redemarrage BOOTSEL refuse pendant la conduite (desarmer d'abord) !!"); return; } Serial.println(">> Redemarrage en mode BOOTSEL..."); Serial.flush(); rp2040.rebootToBootloader(); return; } if (commande[0] == 'S' || commande[0] == 's') { if (estArme) { Serial.println("!! Sauvegarde Flash refusee pendant la conduite (desarmer d'abord) !!"); return; } momentDernierChangementDurete_ms = 0; sauvegardeDifferee = false; sauvegarderConfiguration(); return; } if (commande[0] == 'R' || commande[0] == 'r') { if (estArme) { Serial.println("!! Reinitialisation refusee pendant la conduite (desarmer d'abord) !!"); return; } rp2040.idleOtherCore(); reinitialiserConfigurationDefaut(); reinitialiserCanauxCRSF(); rapportEngage = 0; estArme = false; majLedRequise = true; momentDernierChangementDurete_ms = 0; sauvegardeDifferee = false; rp2040.resumeOtherCore(); majRangeRequise = true; majRessortRequise = true; sauvegarderConfiguration(); afficherConfiguration(); return; } if (strlen(commande) >= 3 && commande[1] == '=') { char periph = commande[0]; if (periph == 'V' || periph == 'v' || periph == 'A' || periph == 'a' || periph == 'F' || periph == 'f' || periph == 'E' || periph == 'e') { if (estArme) { Serial.println("!! Remappage des canaux refuse pendant la conduite (desarmer d'abord) !!"); return; } int nouveauCanal = atoi(&commande[2]); if (nouveauCanal < 1 || nouveauCanal > 16) { Serial.println("!! Canal invalide : doit etre entre 1 et 16 !!"); return; } if (nouveauCanal == CANAL_ARM) { Serial.printf("!! Canal %d reserve a l'armement (R2) !!\n", CANAL_ARM); return; } uint8_t cV = configSysteme.volant; uint8_t cA = configSysteme.accel; uint8_t cF = configSysteme.frein; uint8_t cE = configSysteme.embrayage; bool conflit = false; switch (periph) { case 'V': case 'v': if (nouveauCanal == cA || nouveauCanal == cF || nouveauCanal == cE) conflit = true; break; case 'A': case 'a': if (nouveauCanal == cV || nouveauCanal == cF || nouveauCanal == cE) conflit = true; break; case 'F': case 'f': if (nouveauCanal == cV || nouveauCanal == cA || nouveauCanal == cE) conflit = true; break; case 'E': case 'e': if (nouveauCanal == cV || nouveauCanal == cA || nouveauCanal == cF) conflit = true; break; } if (conflit) { Serial.printf("!! Conflit : le canal %d est deja utilise par un autre axe !!\n", nouveauCanal); return; } rp2040.idleOtherCore(); switch (periph) { case 'V': case 'v': configSysteme.volant = nouveauCanal; break; case 'A': case 'a': configSysteme.accel = nouveauCanal; break; case 'F': case 'f': configSysteme.frein = nouveauCanal; break; case 'E': case 'e': configSysteme.embrayage = nouveauCanal; break; } reinitialiserCanauxCRSF(); rp2040.resumeOtherCore(); sauvegarderConfiguration(); afficherConfiguration(); } else if (periph == 'D' || periph == 'd') { int val = atoi(&commande[2]); if (val >= 0 && val <= 255) { rp2040.idleOtherCore(); configSysteme.forceRessort = (uint8_t)val; rp2040.resumeOtherCore(); majRessortRequise = true; demanderOuExecuterSauvegarde(); afficherConfiguration(); } else { Serial.println("!! Durete (D) doit etre entre 0 et 255 !!"); } } else if (periph == 'P' || periph == 'p') { if (estArme) { Serial.println("!! Reglage de plage (P) refuse pendant la conduite (desarmer d'abord) !!"); return; } int val = atoi(&commande[2]); if (val >= 40 && val <= 900) { rp2040.idleOtherCore(); configSysteme.angleSouhaiteTotal = (uint16_t)val; recalculerParametresVolant(); rp2040.resumeOtherCore(); majRangeRequise = true; sauvegarderConfiguration(); afficherConfiguration(); } else { Serial.println("!! Plage d'angle (P) doit etre entre 40 et 900 degres !!"); } } else if (periph == 'X' || periph == 'x') { if (estArme) { Serial.println("!! Reglage d'expo (X) refuse pendant la conduite (desarmer d'abord) !!"); return; } float val = atof(&commande[2]); if (val >= 0.0f && val <= 0.8f) { rp2040.idleOtherCore(); configSysteme.expoVolant = val; rp2040.resumeOtherCore(); sauvegarderConfiguration(); afficherConfiguration(); } else { Serial.println("!! Expo volant (X) doit etre entre 0.0 et 0.8 !!"); } } else if (periph == 'T' || periph == 't') { int val = atoi(&commande[2]); if (val >= 0 && val <= 100) { rp2040.idleOtherCore(); configSysteme.intensiteVibration = (uint8_t)val; rp2040.resumeOtherCore(); demanderOuExecuterSauvegarde(); afficherConfiguration(); } else { Serial.println("!! Vibrations (T) doit etre entre 0 et 100% !!"); } } } } void verifierCommandesSerie() { while (Serial.available() > 0) { char c = (char)Serial.read(); if (c == '\n' || c == '\r') { if (serialBufferIdx > 0) { serialBuffer[serialBufferIdx] = '\0'; traiterLigneSerie(serialBuffer); serialBufferIdx = 0; } } else if (serialBufferIdx < sizeof(serialBuffer) - 1) { serialBuffer[serialBufferIdx++] = c; } } } // ------------------------------------------------------------------------- // GESTION LED RGB SUR GP16 // ------------------------------------------------------------------------- void actualiserLED() { uint8_t r = 0, g = 0, b = 0; if (!volant_est_pret) { b = 255; // Bleu : Attente G29 } else if (failsafeActif) { r = 255; g = 255; b = 255; // Blanc : Failsafe (G29 muet) } else { switch (rapportEngage) { case -1: r = 255; g = 0; b = 0; break; // Rouge : R case 0: r = 255; g = 100; b = 0; break; // Orange : N case 1: r = 0; g = 255; b = 255; break; // Cyan : 1ère case 2: r = 0; g = 255; b = 0; break; // Vert : 2ème case 3: r = 180; g = 0; b = 255; break; // Violet : 3ème } if (!estArme) { // Désarmé : couleur du rapport très atténuée r /= 10; g /= 10; b /= 10; } } rgb_led.setPixelColor(0, rgb_led.Color(r, g, b)); rgb_led.show(); } // ------------------------------------------------------------------------- // ENVOI CRSF DEPUIS LA SRAM DU RP2350 // ------------------------------------------------------------------------- uint8_t __not_in_flash_func(calculerCrc8Crsf)(const uint8_t* data, size_t len) { uint8_t crc = 0; for (size_t i = 0; i < len; i++) { crc ^= data[i]; for (int j = 0; j < 8; j++) { if (crc & 0x80) crc = (crc << 1) ^ 0xD5; else crc <<= 1; } } return crc; } void __not_in_flash_func(envoyer_paquet_crsf)(bool neutre) { uint8_t packet[26]; uint16_t ch[16]; for (int i = 0; i < 16; i++) { ch[i] = neutre ? CRSF_VAL_MID : crsf_channels[i]; } if (neutre) ch[CANAL_ARM - 1] = CRSF_VAL_MIN; // Failsafe : toujours désarmé packet[0] = 0xC8; packet[1] = 24; packet[2] = 0x16; packet[3] = (uint8_t)(ch[0]); packet[4] = (uint8_t)((ch[0] >> 8) | (ch[1] << 3)); packet[5] = (uint8_t)((ch[1] >> 5) | (ch[2] << 6)); packet[6] = (uint8_t)(ch[2] >> 2); packet[7] = (uint8_t)((ch[2] >> 10) | (ch[3] << 1)); packet[8] = (uint8_t)((ch[3] >> 7) | (ch[4] << 4)); packet[9] = (uint8_t)((ch[4] >> 4) | (ch[5] << 7)); packet[10] = (uint8_t)(ch[5] >> 1); packet[11] = (uint8_t)((ch[5] >> 9) | (ch[6] << 2)); packet[12] = (uint8_t)((ch[6] >> 6) | (ch[7] << 5)); packet[13] = (uint8_t)(ch[7] >> 3); packet[14] = (uint8_t)(ch[8]); packet[15] = (uint8_t)((ch[8] >> 8) | (ch[9] << 3)); packet[16] = (uint8_t)((ch[9] >> 5) | (ch[10] << 6)); packet[17] = (uint8_t)(ch[10] >> 2); packet[18] = (uint8_t)((ch[10] >> 10) | (ch[11] << 1)); packet[19] = (uint8_t)((ch[11] >> 7) | (ch[12] << 4)); packet[20] = (uint8_t)((ch[12] >> 4) | (ch[13] << 7)); packet[21] = (uint8_t)(ch[13] >> 1); packet[22] = (uint8_t)((ch[13] >> 9) | (ch[14] << 2)); packet[23] = (uint8_t)((ch[14] >> 6) | (ch[15] << 5)); packet[24] = (uint8_t)(ch[15] >> 3); packet[25] = calculerCrc8Crsf(&packet[2], 23); Serial1.write(packet, 26); } // ========================================================================= // CŒUR 0 : Initialisation, CRSF 166Hz, Série, EEPROM et LED RGB // ========================================================================= void setup() { Serial.begin(115200); EEPROM.begin(EEPROM_SIZE); rgb_led.begin(); rgb_led.setBrightness(50); actualiserLED(); delay(500); chargerConfiguration(); Serial1.setTX(0); Serial1.setRX(1); Serial1.begin(420000); Serial.println("\n--- WAVESHARE RP2350-USB-A PRETE ---"); afficherConfiguration(); // Watchdog matériel : reboot si loop() ne le nourrit plus pendant WATCHDOG_TIMEOUT_MS if (watchdog_caused_reboot()) { Serial.println("!! [WATCHDOG] Redemarrage suite a un blocage !!"); } rp2040.wdt_begin(WATCHDOG_TIMEOUT_MS); } // Évalue le failsafe (cœur 0). Retourne true si les canaux doivent être forcés au neutre. bool evaluerFailsafe() { // Lire l'horodatage AVANT millis() : si le cœur 1 le met à jour entre les deux, // la soustraction reste positive (pas de faux déclenchement par débordement). uint32_t dernier = dernierRapportUSB_ms; uint32_t age = millis() - dernier; bool stale = !volant_est_pret || (age > TIMEOUT_FAILSAFE_MS); if (stale && !failsafeActif) { failsafeActif = true; demandeRetourNeutre = true; // Au retour du signal, la voiture repart au point mort majLedRequise = true; Serial.printf("!! [FAILSAFE] ACTIF (dernier rapport USB il y a %lu ms) !!\n", (unsigned long)age); } else if (!stale && failsafeActif) { failsafeActif = false; majLedRequise = true; Serial.println("[FAILSAFE] Signal G29 retabli"); } return stale; } // ------------------------------------------------------------------------- // RÉCEPTION TÉLÉMÉTRIE CRSF SUR GP1 (Serial1 RX) // ------------------------------------------------------------------------- void traiterTelemetrieCRSF() { static uint8_t crsfRxBuffer[64]; static uint8_t crsfRxIdx = 0; static uint8_t paquetLongueurAttendue = 0; static int16_t prevPitch = 0; static int16_t prevRoll = 0; static bool attitudeInitialisee = false; static uint32_t dernierPaquetTelemetrie_ms = 0; while (Serial1.available() > 0) { uint8_t b = Serial1.read(); if (crsfRxIdx == 0) { // Les trames CRSF débutent par une adresse connue (0xC8, 0xEE, 0xEA, etc.) if (b == 0xC8 || b == 0xEE || b == 0xEA) { crsfRxBuffer[0] = b; crsfRxIdx = 1; paquetLongueurAttendue = 0; } } else if (crsfRxIdx == 1) { paquetLongueurAttendue = b; if (paquetLongueurAttendue < 2 || paquetLongueurAttendue > 62) { crsfRxIdx = 0; // Trame invalide, rejet } else { crsfRxBuffer[1] = b; crsfRxIdx = 2; } } else { crsfRxBuffer[crsfRxIdx++] = b; // Trame complète reçue : taille totale = 2 octets d'en-tête + longueur indiquée if (crsfRxIdx >= (paquetLongueurAttendue + 2)) { uint8_t crcAttendu = crsfRxBuffer[paquetLongueurAttendue + 1]; uint8_t crcCalcule = calculerCrc8Crsf(&crsfRxBuffer[2], paquetLongueurAttendue - 1); if (crcCalcule == crcAttendu) { dernierPaquetTelemetrie_ms = millis(); uint8_t frameType = crsfRxBuffer[2]; // Trame d'attitude (0x1E) : Pitch (int16), Roll (int16), Yaw (int16) if (frameType == 0x1E && paquetLongueurAttendue >= 8) { int16_t pitch = (int16_t)((crsfRxBuffer[3] << 8) | crsfRxBuffer[4]); int16_t roll = (int16_t)((crsfRxBuffer[5] << 8) | crsfRxBuffer[6]); if (!attitudeInitialisee) { prevPitch = pitch; prevRoll = roll; attitudeInitialisee = true; } else { int32_t deltaPitch = abs((int32_t)pitch - (int32_t)prevPitch); int32_t deltaRoll = abs((int32_t)roll - (int32_t)prevRoll); prevPitch = pitch; prevRoll = roll; int32_t secousses = deltaPitch + deltaRoll; rugositeTerrainExterne = (uint8_t)constrain(map(secousses, 15, 250, 0, 255), 0, 255); } } // Trame personnalisée (0x7F ou 0x2A pour accéléromètre brut / rugosité) else if ((frameType == 0x7F || frameType == 0x2A) && paquetLongueurAttendue >= 3) { rugositeTerrainExterne = crsfRxBuffer[3]; } } crsfRxIdx = 0; } if (crsfRxIdx >= sizeof(crsfRxBuffer)) { crsfRxIdx = 0; } } } if (dernierPaquetTelemetrie_ms > 0 && (millis() - dernierPaquetTelemetrie_ms > 500)) { attitudeInitialisee = false; } // Décroissance douce de la rugosité si la télémétrie ne transmet plus depuis > 200 ms if (rugositeTerrainExterne > 0 && (millis() - dernierPaquetTelemetrie_ms > 200)) { static uint32_t dernierDecul = 0; if (millis() - dernierDecul >= 50) { dernierDecul = millis(); rugositeTerrainExterne = (rugositeTerrainExterne > 10) ? (rugositeTerrainExterne - 10) : 0; } } } void loop() { rp2040.wdt_reset(); verifierCommandesSerie(); traiterTelemetrieCRSF(); static int8_t dernierRapportLog = 0xFF; if (majLedRequise) { majLedRequise = false; actualiserLED(); if (rapportEngage != dernierRapportLog) { dernierRapportLog = rapportEngage; Serial.printf("[BOITE] Rapport engage : %d\n", rapportEngage); } } if (logMountRequis) { logMountRequis = false; Serial.printf("[USB HOST] G29 detecte ! VID=%04X, PID=%04X, dev=%d, inst=%d, desc_len=%d\n", g29_vid, g29_pid, g29_dev_addr, g29_instance, g29_desc_len); } if (logRejetRequis) { logRejetRequis = false; Serial.printf("[USB HOST] Peripherique ignore (VID=%04X, PID=%04X) : pas un G29 en mode PS4\n", rejet_vid, rejet_pid); } int8_t evtArm = logArmRequis; if (evtArm != 0) { logArmRequis = 0; if (evtArm == 1) Serial.println(">> [ARM] ARME (R2)"); else if (evtArm == -1) Serial.println(">> [ARM] DESARME"); else if (evtArm == 3) Serial.println("!! [ARM] Refuse : initialisation FFB du G29 en cours (patienter) !!"); else Serial.println("!! [ARM] Refuse : passer au point mort (N) et relacher l'accelerateur !!"); } if (logDureteRequis) { logDureteRequis = false; Serial.printf(">> [DURETE G29] Force ressort : %d / 255 (%d%%)\n", configSysteme.forceRessort, (configSysteme.forceRessort * 100) / 255); } // Sauvegarde différée suite à une commande série (D= / T=) passée pendant la conduite if (!estArme && sauvegardeDifferee) { sauvegardeDifferee = false; sauvegarderConfiguration(); } // Sauvegarde automatique 2s après la fin du réglage à la molette. // Sécurité : différée tant que le véhicule est armé pour éviter un gel Flash en conduite. uint32_t momentChgt = momentDernierChangementDurete_ms; if (!estArme && momentChgt > 0 && (millis() - momentChgt >= 2000)) { momentDernierChangementDurete_ms = 0; sauvegarderConfiguration(); } // Sauvegarde immédiate lors d'un appui sur le bouton central Enter de la molette // (uniquement autorisée si désarmé pour des raisons de sécurité) if (demandeSauvegardeEEPROM) { demandeSauvegardeEEPROM = false; if (estArme) { Serial.println("!! Sauvegarde Flash refusee pendant la conduite (desarmer d'abord) !!"); } else { momentDernierChangementDurete_ms = 0; sauvegardeDifferee = false; sauvegarderConfiguration(); } } static uint32_t dernierHeartbeat = 0; static uint32_t dernierCompteOK = 0; if (millis() - dernierHeartbeat >= 2000) { uint32_t dt = millis() - dernierHeartbeat; dernierHeartbeat = millis(); uint32_t compteOK = compteurRapportsOK; uint32_t rapportsParSec = ((compteOK - dernierCompteOK) * 1000UL) / (dt ? dt : 1); dernierCompteOK = compteOK; Serial.printf("[ETAT] G29_Pret=%d (PID=%04X) | InitFFB=%d/%d | Durete=%d/255 | Vib=%d%% | Rugosite=%d | Plage=%d deg | Rapport=%d | Arme=%d | Statut_LED=%d | USB=%lu rap/s | Rejetes=%lu (L=%d,ID=%02X) | Failsafe=%d\n", volant_est_pret, g29_pid, etapeInitMoteur, ETAPES_INIT_FFB_TOTAL, configSysteme.forceRessort, configSysteme.intensiteVibration, rugositeTerrainExterne, configSysteme.angleSouhaiteTotal, rapportEngage, estArme, statutEnvoiLed, (unsigned long)rapportsParSec, (unsigned long)compteurRapportsRejetes, dernierRejetLen, dernierRejetId, failsafeActif); } // Transmission CRSF précise à 166.67 Hz (toutes les 6000 µs sans dérive ni burst) static uint32_t dernier_envoi_us = 0; if (dernier_envoi_us == 0) { dernier_envoi_us = micros(); } uint32_t now_us = micros(); if (now_us - dernier_envoi_us >= 6000) { if (now_us - dernier_envoi_us >= 12000) { dernier_envoi_us = now_us; } else { dernier_envoi_us += 6000; } envoyer_paquet_crsf(evaluerFailsafe()); } } // ========================================================================= // CŒUR 1 : PILE PIO-USB, AUTO-CENTER ET LEDS G29 // ========================================================================= int32_t obtenirDeltaMaxVolant() { return (maxDeltaVolant > 0) ? maxDeltaVolant : DELTA_MAX_VOLANT_BRUT; } bool envoyerTrameG29_0x30(const uint8_t cmd7[7]) { if (!tuh_hid_send_ready(g29_dev_addr, g29_instance)) return false; static uint8_t payload63[63]; memset(payload63, 0, sizeof(payload63)); memcpy(payload63, cmd7, 7); return tuh_hid_send_report(g29_dev_addr, g29_instance, 0x30, payload63, sizeof(payload63)); } bool envoyerPlageG29(uint16_t angle) { const uint8_t cmdRange[7] = {0xF8, 0x81, (uint8_t)(angle & 0xFF), (uint8_t)(angle >> 8), 0x00, 0x00, 0x00}; return envoyerTrameG29_0x30(cmdRange); } bool envoyerRessortG29(uint8_t force) { const uint8_t cmdSpring[7] = {0xFE, 0x0D, (uint8_t)(PENTE_RESSORT_G29 & 0x07), (uint8_t)(PENTE_RESSORT_G29 & 0x07), force, 0x00, 0x00}; return envoyerTrameG29_0x30(cmdSpring); } bool envoyerForceG29(uint8_t forceByte) { const uint8_t cmdForce[7] = {0x11, 0x00, forceByte, 0x00, 0x00, 0x00, 0x00}; return envoyerTrameG29_0x30(cmdForce); } void gererInitMoteurG29() { if (!volant_est_pret || etapeInitMoteur >= ETAPES_INIT_FFB_TOTAL) return; // Attendre 6s après la connexion USB pour que le G29 ait terminé son calibrage matériel if (millis() - momentConnexionUSB_ms < 6000) return; switch (etapeInitMoteur) { case 0: if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) etapeInitMoteur++; break; case 1: if (envoyerRessortG29(configSysteme.forceRessort)) etapeInitMoteur = ETAPES_INIT_FFB_TOTAL; break; } } uint8_t calculerMasqueLedG29() { uint8_t masqueCible = 0x00; // Si la dureté a été modifiée il y a moins de 1.5s, afficher la jauge de dureté sur les LEDs uint32_t momentDernierChg = momentDernierChangementDurete_ms; if (momentDernierChg > 0 && (millis() - momentDernierChg < 1500)) { uint8_t f = configSysteme.forceRessort; if (f >= 240) masqueCible = 0x1F; // 5 LEDs (Rouge) else if (f >= 180) masqueCible = 0x0F; // 4 LEDs (Jaune haut) else if (f >= 120) masqueCible = 0x07; // 3 LEDs (Jaune bas) else if (f >= 60) masqueCible = 0x03; // 2 LEDs (Vert haut) else if (f > 0) masqueCible = 0x01; // 1 LED (Vert bas) else masqueCible = 0x00; // 0 LED (libre) } else { switch (rapportEngage) { case -1: masqueCible = 0x1F; break; // 5 LEDs fixes en marche arriere (pas de spam USB cyclique) case 0: masqueCible = 0x00; break; case 1: masqueCible = 0x01; break; case 2: masqueCible = 0x03; break; case 3: masqueCible = 0x07; break; } } if (murActifDroite || murActifGauche) { masqueCible = 0x1F; // Allumer les 5 LEDs du volant dès qu'on touche la butée FFB ! } return masqueCible; } bool envoyerLedsPendingG29() { if (!volant_est_pret || etapeEnvoiLed == 0) return false; if (millis() - momentConnexionUSB_ms < 500) return false; // Format validé sur G29 PS4 physique : // Report ID = 0x30, payload 63 octets débutant par F8 12 suivi de zéros const uint8_t cmdLed[7] = {0xF8, 0x12, (uint8_t)(dernierMasqueLedG29 & 0x1F), 0x00, 0x00, 0x00, 0x00}; if (envoyerTrameG29_0x30(cmdLed)) { statutEnvoiLed = 1; etapeEnvoiLed = 0; return true; } return false; } void actualiserEtatButee() { int32_t posCentre = dernierVolantCentre; int32_t deltaMax = obtenirDeltaMaxVolant(); if (!murActifDroite) { if (posCentre > deltaMax) { murActifDroite = true; } } else if (posCentre <= deltaMax - HYSTERESIS_MUR_BRUT) { murActifDroite = false; } if (!murActifGauche) { if (posCentre < -deltaMax) { murActifGauche = true; } } else if (posCentre >= -deltaMax + HYSTERESIS_MUR_BRUT) { murActifGauche = false; } } float calculerForceButee(int32_t posCentre, int32_t deltaMax) { if (!murActifDroite && !murActifGauche) return 0.0f; int32_t depassement = murActifDroite ? (posCentre - deltaMax) : (-deltaMax - posCentre); float f = 0.0f; if (depassement >= 0) { // Dans le mur strict : contre-force ultra-ferme immédiate (115 à 127, soit 90% à 100% du couple max) f = constrain(115.0f + (float)depassement * 0.60f, 115.0f, 127.0f); } else { // Zone d'hystérésis : éjection ferme continue puis décroissance vers 0 int32_t surplus = HYSTERESIS_MUR_BRUT + depassement; f = constrain((float)surplus * (115.0f / (float)HYSTERESIS_MUR_BRUT), 0.0f, 115.0f); } return murActifDroite ? f : -f; } float avancerPhaseSinus(float& phase, float freqHz, float dt_s) { constexpr float DEUX_PI = 6.28318530718f; phase += DEUX_PI * freqHz * dt_s; if (phase >= DEUX_PI) { phase = fmodf(phase, DEUX_PI); } return sinf(phase); } void gererVibrationHaptique() { if (!volant_est_pret || etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) return; if (etapeEnvoiLed != 0 || majRangeRequise || majRessortRequise) return; if (!tuh_hid_send_ready(g29_dev_addr, g29_instance)) return; static uint32_t dernierCalculPhase_us = 0; static float phase12 = 0.0f; static float phase60 = 0.0f; static float phase45 = 0.0f; // 1. Si on est dans le mur : le mur actif de blocage est prioritaire absolu float forceButee = calculerForceButee(dernierVolantCentre, obtenirDeltaMaxVolant()); if (forceButee != 0.0f) { dernierCalculPhase_us = 0; forceEstAuNeutre = false; uint8_t forceByte = (uint8_t)constrain((int)(128.0f + forceButee), 0, 255); envoyerForceG29(forceByte); return; } // 2. Gestion des vibrations haptiques et retours mécaniques uint8_t intensite = configSysteme.intensiteVibration; if (intensite == 0) { dernierCalculPhase_us = 0; if (!forceEstAuNeutre) { if (envoyerForceG29(128)) { forceEstAuNeutre = true; } } return; } float gainGlobal = (float)intensite / 100.0f; uint32_t now = millis(); uint32_t dtChoc = now - momentDernierChocRapport_ms; // Cas A : À-coup sec au passage de rapport (durée 70 ms) // Toujours actif lors du changement vers un rapport avant, pour un ressenti mécanique direct aux palettes ! if (dtChoc < 70 && directionDernierChocRapport != 0) { dernierCalculPhase_us = 0; forceEstAuNeutre = false; static uint32_t dernierMomentChocEnvoye = 0; if (momentDernierChocRapport_ms != dernierMomentChocEnvoye) { dernierMomentChocEnvoye = momentDernierChocRapport_ms; float forceCalc = 128.0f + (float)directionDernierChocRapport * 85.0f * gainGlobal; uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255); envoyerForceG29(forceByte); } return; } // Silence complet en marche arrière (-1) ou au point mort désarmé (0 && !estArme) if (rapportEngage == -1 || (rapportEngage == 0 && !estArme)) { dernierCalculPhase_us = 0; if (!forceEstAuNeutre) { if (envoyerForceG29(128)) { forceEstAuNeutre = true; } } return; } forceEstAuNeutre = false; uint32_t now_us = micros(); float dt_s = (dernierCalculPhase_us == 0) ? 0.020f : (float)(now_us - dernierCalculPhase_us) * 1e-6f; if (dt_s > 0.05f) dt_s = 0.020f; dernierCalculPhase_us = now_us; float forceCalc = 128.0f; // Cas B : Freinage violent (> 70%) -> vibration ABS à 45 Hz if (dernierFreinPct > 70.0f) { float absAmp = (dernierFreinPct - 70.0f) * 2.5f * gainGlobal; forceCalc = 128.0f + absAmp * avancerPhaseSinus(phase45, 45.0f, dt_s); } // Cas C : Double-couche haptique (12 Hz grondement/terrain + 60 Hz roulement/vitesse) else { // 12 Hz : Grondement moteur au ralenti / régime + secousses terrain float freq12 = 12.0f + (dernierAccelPct * 0.15f); float ampMoteur12 = (14.0f + dernierAccelPct * 0.40f) * gainGlobal; float ampTerrain12 = ((float)rugositeTerrainExterne * 0.45f) * gainGlobal; float v12 = (ampMoteur12 + ampTerrain12) * avancerPhaseSinus(phase12, freq12, dt_s); // 60 Hz : Grain de roulement lié à la vitesse (rapport engagé) et aux gaz // Baseline de 8.0f sur les rapports avant pour un retour haptique franc dès le rapport engagé float baseVitesse = (rapportEngage > 0) ? 8.0f : 0.0f; float ampVitesse60 = (baseVitesse + dernierAccelPct * 0.30f) * (1.0f + (float)rapportEngage * 0.25f) * gainGlobal; float ampTerrain60 = ((float)rugositeTerrainExterne * 0.20f) * gainGlobal; float v60 = (ampVitesse60 + ampTerrain60) * avancerPhaseSinus(phase60, 60.0f, dt_s); forceCalc = 128.0f + v12 + v60; } uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255); envoyerForceG29(forceByte); } void setup1() { sleep_ms(100); pio_usb_configuration_t pio_cfg = PIO_USB_DEFAULT_CONFIG; pio_cfg.pin_dp = HOST_PIN_DP; USBHost.configure_pio_usb(0, &pio_cfg); USBHost.begin(0); } void loop1() { USBHost.task(); if (!volant_est_pret) return; // Watchdog USB-Host : si aucun rapport reçu depuis > 25 ms, réarmer (ou avorter si bloqué > 50 ms) if (millis() - dernierRapportUSB_ms > 25) { if (tuh_hid_receive_ready(g29_dev_addr, g29_instance)) { tuh_hid_receive_report(g29_dev_addr, g29_instance); } else if (millis() - dernierRapportUSB_ms > 50) { tuh_hid_receive_abort(g29_dev_addr, g29_instance); tuh_hid_receive_report(g29_dev_addr, g29_instance); } } // 1. Séquence d'initialisation FFB (6s après connexion USB, espacée de 50 ms) static uint32_t dernierTickInit = 0; if (etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) { if (millis() - dernierTickInit >= 50) { dernierTickInit = millis(); gererInitMoteurG29(); } return; } // 2. Mise à jour continue de l'état de la butée active (avant LEDs et FFB) actualiserEtatButee(); // 3. Rafraîchissement périodique de la cible LED (50 ms) static uint32_t dernierTickLed = 0; if (millis() - dernierTickLed >= 50) { dernierTickLed = millis(); uint8_t masqueCible = calculerMasqueLedG29(); if (masqueCible != dernierMasqueLedG29) { dernierMasqueLedG29 = masqueCible; etapeEnvoiLed = 1; } } // 4. Envoi immédiat des trames prioritaires dès que le pipe USB est libre (sans bloquer loop1) if (majRangeRequise) { if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) { majRangeRequise = false; } } if (majRessortRequise) { if (envoyerRessortG29(configSysteme.forceRessort)) { majRessortRequise = false; } } if (etapeEnvoiLed != 0) { if (envoyerLedsPendingG29()) { return; // Laisse 20 ms au G29 pour digérer la commande LED avant le prochain envoi FFB } } // 5. Moteur de vibration haptique & butée active (cadencé à 50 Hz, toutes les 20 ms) static uint32_t dernierTickVib = 0; if ((millis() - dernierTickVib >= 20) && tuh_hid_send_ready(g29_dev_addr, g29_instance)) { dernierTickVib = millis(); gererVibrationHaptique(); } } void reinitialiserEtatVolant() { dernierMasqueLedG29 = 0xFF; etapeEnvoiLed = 0; etapeInitMoteur = 0; statutEnvoiLed = 0; rapportEngage = 0; estArme = false; forceEstAuNeutre = false; murActifDroite = false; murActifGauche = false; dernierVolantCentre = 0; dernierAccelPct = 0.0f; dernierFreinPct = 0.0f; rugositeTerrainExterne = 0; } // ========================================================================= // CALLBACKS HID USB HOST (Exécutés sur Core 1) // ========================================================================= extern "C" { void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) { if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) { crsf_channels[numeroCh - 1] = valeur11bits; } } void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) { (void)desc_report; // Filtrage : n'accepter que le G29 en mode PS4, et une seule interface à la fois uint16_t vid = 0, pid = 0; tuh_vid_pid_get(dev_addr, &vid, &pid); if (vid != G29_VID || pid != G29_PID_PS4 || volant_est_pret) { rejet_vid = vid; rejet_pid = pid; logRejetRequis = true; return; // Pas de tuh_hid_receive_report() : on ignore ce périphérique } g29_vid = vid; g29_pid = pid; g29_dev_addr = dev_addr; g29_instance = instance; g29_desc_len = desc_len; reinitialiserEtatVolant(); demandeRetourNeutre = false; boutonArmDejaEnfonce = true; // Ignorer R2 s'il est déjà enfoncé au branchement palettePlusDejaEnfoncee = true; // Exiger relâchement des palettes et molette au boot paletteMoinsDejaEnfoncee= true; dialPlusDejaEnfonce = true; dialMoinsDejaEnfonce = true; dialEnterDejaEnfonce = true; momentConnexionUSB_ms = millis(); dernierRapportUSB_ms = millis(); volant_est_pret = true; majLedRequise = true; logMountRequis = true; tuh_hid_receive_report(dev_addr, instance); } void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) { // Ignorer la déconnexion d'un autre périphérique que le G29 if (!volant_est_pret || dev_addr != g29_dev_addr || instance != g29_instance) return; volant_est_pret = false; g29_vid = 0; g29_pid = 0; reinitialiserEtatVolant(); reinitialiserCanauxCRSF(); majLedRequise = true; } void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) { // Ignorer tout rapport ne venant pas du G29, ou n'ayant pas le bon format if (dev_addr != g29_dev_addr || instance != g29_instance) { return; // Ne pas réarmer la réception d'un périphérique étranger } if (len < 51 || report[0] != G29_REPORT_ID) { compteurRapportsRejetes++; dernierRejetLen = len; dernierRejetId = (len > 0) ? report[0] : 0; dernierRapportUSB_ms = millis(); // Le périphérique répond, ce n'est pas une perte de liaison ! tuh_hid_receive_report(dev_addr, instance); return; } { compteurRapportsOK++; // Retour du signal après un failsafe : repartir au point mort ET désarmé if (demandeRetourNeutre) { demandeRetourNeutre = false; if (rapportEngage != 0) { rapportEngage = 0; majLedRequise = true; } if (estArme) { estArme = false; logArmRequis = -1; majLedRequise = true; } boutonArmDejaEnfonce = true; // Exiger un relâchement de R2 avant de réarmer } uint16_t volantRaw = (report[44] << 8) | report[43]; uint16_t accelRaw = 65535 - ((report[46] << 8) | report[45]); uint16_t freinRaw = 65535 - ((report[48] << 8) | report[47]); uint16_t embrayageRaw = 65535 - ((report[50] << 8) | report[49]); // Pourcentages des pédales pour la synthèse haptique (0.0 à 100.0%) dernierAccelPct = (accelRaw > DEADZONE_PEDALE) ? (((float)(accelRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; dernierFreinPct = (freinRaw > DEADZONE_PEDALE) ? (((float)(freinRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; uint8_t boutonsEpaule = report[6]; bool pPlusActuel = (boutonsEpaule & PALETTE_PLUS_MASK); bool pMoinsActuel = (boutonsEpaule & PALETTE_MOINS_MASK); bool armActuel = (boutonsEpaule & BOUTON_ARM_MASK); // Bascule ARM / DÉSARMÉ sur front montant de R2. // Armement autorisé uniquement après l'init FFB, au point mort et accélérateur relâché. if (armActuel && !boutonArmDejaEnfonce) { if (estArme) { estArme = false; logArmRequis = -1; } else if (etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) { logArmRequis = 3; } else if (rapportEngage == 0 && accelRaw <= DEADZONE_PEDALE) { estArme = true; logArmRequis = 1; } else { logArmRequis = 2; } majLedRequise = true; boutonArmDejaEnfonce = true; } else if (!armActuel && boutonArmDejaEnfonce) { boutonArmDejaEnfonce = false; } if (pPlusActuel && !palettePlusDejaEnfoncee) { if (rapportEngage < 3 && !(rapportEngage < 0 && accelRaw > DEADZONE_PEDALE)) { int8_t ancienRapport = rapportEngage; rapportEngage++; majLedRequise = true; if (ancienRapport >= 0) { momentDernierChocRapport_ms = millis(); directionDernierChocRapport = 1; // À-coup sec vers la droite } } palettePlusDejaEnfoncee = true; } else if (!pPlusActuel && palettePlusDejaEnfoncee) { palettePlusDejaEnfoncee = false; } if (pMoinsActuel && !paletteMoinsDejaEnfoncee) { if (rapportEngage > -1 && !(rapportEngage <= 0 && accelRaw > DEADZONE_PEDALE)) { rapportEngage--; majLedRequise = true; if (rapportEngage >= 0) { momentDernierChocRapport_ms = millis(); directionDernierChocRapport = -1; // À-coup sec vers la gauche } } paletteMoinsDejaEnfoncee = true; } else if (!pMoinsActuel && paletteMoinsDejaEnfoncee) { paletteMoinsDejaEnfoncee = false; } // Réglage de la dureté du volant à la volée via la molette ou boutons [+] / [-] uint8_t b54 = (len >= 55) ? report[54] : 0; bool dialPlusActuel = (b54 & DIAL_CW_MASK) || (b54 & BOUTON_PLUS_MASK); bool dialMoinsActuel = (b54 & DIAL_CCW_MASK) || (b54 & BOUTON_MOINS_MASK); bool dialEnterActuel = (b54 & DIAL_ENTER_MASK); if (dialPlusActuel && !dialPlusDejaEnfonce) { if (configSysteme.forceRessort <= 245) configSysteme.forceRessort += 10; else configSysteme.forceRessort = 255; majRessortRequise = true; logDureteRequis = true; momentDernierChangementDurete_ms = millis(); dialPlusDejaEnfonce = true; } else if (!dialPlusActuel && dialPlusDejaEnfonce) { dialPlusDejaEnfonce = false; } if (dialMoinsActuel && !dialMoinsDejaEnfonce) { if (configSysteme.forceRessort >= 10) configSysteme.forceRessort -= 10; else configSysteme.forceRessort = 0; majRessortRequise = true; logDureteRequis = true; momentDernierChangementDurete_ms = millis(); dialMoinsDejaEnfonce = true; } else if (!dialMoinsActuel && dialMoinsDejaEnfonce) { dialMoinsDejaEnfonce = false; } if (dialEnterActuel && !dialEnterDejaEnfonce) { demandeSauvegardeEEPROM = true; dialEnterDejaEnfonce = true; } else if (!dialEnterActuel && dialEnterDejaEnfonce) { dialEnterDejaEnfonce = false; } int32_t volantCentre = (int32_t)volantRaw - CENTRE_VOLANT_BRUT; dernierVolantCentre = volantCentre; int32_t deltaMax = obtenirDeltaMaxVolant(); int32_t volantBorne = constrain(volantCentre, -deltaMax, deltaMax); float x = (float)volantBorne / (float)deltaMax; float expo = configSysteme.expoVolant; float y = x * (1.0f - expo + expo * (x * x)); uint16_t vVolant = constrain((int32_t)(CRSF_VAL_MID - y * (CRSF_VAL_MAX - CRSF_VAL_MID)), CRSF_VAL_MIN, CRSF_VAL_MAX); uint16_t vAccel = CRSF_VAL_MID; if (estArme && accelRaw > DEADZONE_PEDALE) { // Désarmé : gaz coupés quoi qu'il arrive if (rapportEngage == -1) { vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, GAZ_ARRIERE_MIN, GAZ_ARRIERE_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX); } else if (rapportEngage >= 1 && rapportEngage <= 3) { uint16_t maxVitesse = GAZ_AVANT_MAX_PAR_VITESSE[rapportEngage - 1]; vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, GAZ_AVANT_MIN, maxVitesse), CRSF_VAL_MIN, CRSF_VAL_MAX); } } uint16_t vFrein = (freinRaw > DEADZONE_PEDALE) ? constrain(map(freinRaw, DEADZONE_PEDALE, 65535, CRSF_VAL_MID, CRSF_VAL_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX) : CRSF_VAL_MID; uint16_t vEmbrayage = (embrayageRaw > DEADZONE_PEDALE) ? constrain(map(embrayageRaw, DEADZONE_PEDALE, 65535, CRSF_VAL_MID, CRSF_VAL_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX) : CRSF_VAL_MID; assignerCanalCRSF(configSysteme.volant, vVolant); assignerCanalCRSF(configSysteme.accel, vAccel); assignerCanalCRSF(configSysteme.frein, vFrein); assignerCanalCRSF(configSysteme.embrayage, vEmbrayage); crsf_channels[CANAL_ARM - 1] = estArme ? CRSF_VAL_MAX : CRSF_VAL_MIN; // Horodatage APRÈS l'écriture des canaux : à la sortie d'un failsafe, le cœur 0 // ne peut pas renvoyer d'anciennes valeurs (d'avant la coupure) pendant un paquet. dernierRapportUSB_ms = millis(); } tuh_hid_receive_report(dev_addr, instance); } } // extern "C"