Merge pull request #6 from bleackstorm/feat/g29-rumble-vibrations

Feat/g29 rumble vibrations
This commit is contained in:
bleackstorm authored and GitHub committed 2026-11-12 16:07:26 +01:00
commit 8006dbdcbe
2 files changed
+616 -20

No files matched your search

+274 -20
View File
@@ -57,6 +57,9 @@ const uint16_t GAZ_AVANT_MAX_PAR_VITESSE[3] = {
#define EXPO_DEFAUT 0.25f // 0.0f = Linéaire, 0.25f = Doux au centre (FPU RP2350)
#define FORCE_RESSORT_DEFAUT 140 // Force du retour au centre : 0 à 255
#define PENTE_RESSORT_G29 7 // Raideur autour du centre : 1 à 7
#define ETAPES_INIT_FFB_TOTAL 2 // Nombre d'étapes d'init FFB (0=Range, 1=Spring)
#define VIBRATION_DEFAUT 100 // Intensité par défaut des vibrations (0 à 100%)
#define MAGIC_NUMBER_CONFIG 0x48 // Identifiant de validité en EEPROM
Adafruit_NeoPixel rgb_led(NUM_PIXELS, PIN_LED_RGB, NEO_GRB + NEO_KHZ800);
Adafruit_USBH_Host USBHost;
@@ -76,10 +79,11 @@ struct ConfigG29 {
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 magicNumber; // Identifiant de validité en EEPROM (0x47)
uint8_t intensiteVibration; // Intensité globale des vibrations : 0 à 100%
uint8_t magicNumber; // Identifiant de validité en EEPROM (0x48)
};
ConfigG29 configSysteme;
volatile ConfigG29 configSysteme;
volatile int32_t maxDeltaVolant = 0;
void recalculerParametresVolant() {
@@ -132,6 +136,14 @@ volatile uint32_t momentDernierChangementDurete_ms = 0;
volatile bool logDureteRequis = false;
volatile bool demandeSauvegardeEEPROM = 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;
char serialBuffer[32];
uint8_t serialBufferIdx = 0;
@@ -143,6 +155,7 @@ void reinitialiserCanauxCRSF() {
}
void reinitialiserConfigurationDefaut() {
memset((void*)&configSysteme, 0, sizeof(ConfigG29));
configSysteme.volant = 1;
configSysteme.accel = 2;
configSysteme.frein = 3;
@@ -150,13 +163,26 @@ void reinitialiserConfigurationDefaut() {
configSysteme.forceRessort = FORCE_RESSORT_DEFAUT;
configSysteme.angleSouhaiteTotal = ANGLE_DEFAUT_TOTAL;
configSysteme.expoVolant = EXPO_DEFAUT;
configSysteme.magicNumber = 0x47;
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();
rp2040.idleOtherCore();
EEPROM.put(0, configSysteme);
memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29));
EEPROM.put(0, cfgActuelle);
EEPROM.commit();
rp2040.resumeOtherCore();
Serial.println(">> Configuration sauvegardée en mémoire Flash !");
@@ -173,16 +199,43 @@ void afficherConfiguration() {
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.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, S(save), R(reset), ?");
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), ?");
}
void chargerConfiguration() {
EEPROM.get(0, configSysteme);
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;
if (configSysteme.magicNumber != 0x47 || conflitArm ||
configSysteme.angleSouhaiteTotal < 40 || configSysteme.angleSouhaiteTotal > 900) {
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 <= 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();
@@ -219,11 +272,31 @@ void traiterLigneSerie(char* commande) {
if (periph == 'V' || periph == 'v' || periph == 'A' || periph == 'a' ||
periph == 'F' || periph == 'f' || periph == 'E' || periph == 'e') {
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;
}
if (nouveauCanal >= 1 && nouveauCanal <= 16) {
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;
@@ -235,7 +308,6 @@ void traiterLigneSerie(char* commande) {
rp2040.resumeOtherCore();
sauvegarderConfiguration();
afficherConfiguration();
}
} else if (periph == 'D' || periph == 'd') {
int val = atoi(&commande[2]);
if (val >= 0 && val <= 255) {
@@ -272,6 +344,17 @@ void traiterLigneSerie(char* commande) {
} 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();
sauvegarderConfiguration();
afficherConfiguration();
} else {
Serial.println("!! Vibrations (T) doit etre entre 0 et 100% !!");
}
}
}
}
@@ -417,15 +500,91 @@ bool evaluerFailsafe() {
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 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)) {
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]);
int16_t deltaPitch = abs(pitch - prevPitch);
int16_t deltaRoll = abs(roll - prevRoll);
prevPitch = pitch;
prevRoll = roll;
uint16_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;
}
}
}
// 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;
@@ -453,18 +612,25 @@ void loop() {
configSysteme.forceRessort, (configSysteme.forceRessort * 100) / 255);
}
// Sauvegarde automatique 2s après la fin du réglage à la molette
if (momentDernierChangementDurete_ms > 0 && (millis() - momentDernierChangementDurete_ms >= 2000)) {
// 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;
sauvegarderConfiguration();
}
}
static uint32_t dernierHeartbeat = 0;
static uint32_t dernierCompteOK = 0;
@@ -474,16 +640,25 @@ void loop() {
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/6 | Durete=%d/255 | Plage=%d deg | Rapport=%d | Arme=%d | Statut_LED=%d | USB=%lu rap/s | Rejetes=%lu | Failsafe=%d\n",
volant_est_pret, g29_pid, etapeInitMoteur, configSysteme.forceRessort, configSysteme.angleSouhaiteTotal,
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 | 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, failsafeActif);
}
// Transmission CRSF précise à 166.67 Hz (toutes les 6000 µs sans dérive)
// Transmission CRSF précise à 166.67 Hz (toutes les 6000 µs sans dérive ni burst)
static uint32_t dernier_envoi_us = 0;
if (micros() - dernier_envoi_us >= 6000) {
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());
}
}
@@ -500,7 +675,7 @@ bool envoyerTrameG29_0x30(const uint8_t cmd7[7]) {
}
void gererInitMoteurG29() {
if (!volant_est_pret || etapeInitMoteur >= 6) return;
if (!volant_est_pret || etapeInitMoteur >= ETAPES_INIT_FFB_TOTAL) return;
if (millis() - momentConnexionUSB_ms < 600) return;
uint16_t angle = configSysteme.angleSouhaiteTotal;
@@ -509,7 +684,7 @@ void gererInitMoteurG29() {
switch (etapeInitMoteur) {
case 0: if (envoyerTrameG29_0x30(cmdRange)) etapeInitMoteur++; break;
case 1: if (envoyerTrameG29_0x30(cmdSpring)) etapeInitMoteur = 6; break;
case 1: if (envoyerTrameG29_0x30(cmdSpring)) etapeInitMoteur = ETAPES_INIT_FFB_TOTAL; break;
}
}
@@ -539,6 +714,60 @@ void envoyerLedsG29(uint8_t masque5bits) {
}
}
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;
uint8_t intensite = configSysteme.intensiteVibration;
if (intensite == 0 || !estArme) {
if (!forceEstAuNeutre) {
const uint8_t cmdNeutre[7] = {0x11, 0x00, 128, 0x00, 0x00, 0x00, 0x00};
if (envoyerTrameG29_0x30(cmdNeutre)) {
forceEstAuNeutre = true;
}
}
return;
}
forceEstAuNeutre = false;
float gainGlobal = (float)intensite / 100.0f;
float t = (float)millis() * 0.001f;
float forceCalc = 128.0f;
uint32_t now = millis();
uint32_t dtChoc = now - momentDernierChocRapport_ms;
// Cas A : À-coup sec au passage de rapport (durée 70 ms)
if (dtChoc < 70) {
forceCalc = 128.0f + (float)directionDernierChocRapport * 85.0f * gainGlobal;
}
// Cas B : Freinage violent (> 70%) -> vibration ABS à 45 Hz
else if (dernierFreinPct > 70.0f) {
float absAmp = (dernierFreinPct - 70.0f) * 2.5f * gainGlobal;
forceCalc = 128.0f + absAmp * sinf(2.0f * 3.14159265f * 45.0f * t);
}
// 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) * sinf(2.0f * 3.14159265f * freq12 * t);
// 60 Hz : Grain de roulement lié à la vitesse (rapport engagé) et aux gaz
float ampVitesse60 = (dernierAccelPct * 0.30f) * (1.0f + (float)rapportEngage * 0.25f) * gainGlobal;
float ampTerrain60 = ((float)rugositeTerrainExterne * 0.20f) * gainGlobal;
float v60 = (ampVitesse60 + ampTerrain60) * sinf(2.0f * 3.14159265f * 60.0f * t);
forceCalc = 128.0f + v12 + v60;
}
uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255);
const uint8_t cmdForce[7] = {0x11, 0x00, forceByte, 0x00, 0x00, 0x00, 0x00};
envoyerTrameG29_0x30(cmdForce);
}
void setup1() {
sleep_ms(100);
pio_usb_configuration_t pio_cfg = PIO_USB_DEFAULT_CONFIG;
@@ -554,7 +783,7 @@ void loop1() {
if (volant_est_pret && (millis() - dernierTickG29 >= 50)) {
dernierTickG29 = millis();
if (etapeInitMoteur < 6) {
if (etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) {
gererInitMoteurG29();
return;
}
@@ -578,7 +807,8 @@ void loop1() {
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
if (momentDernierChangementDurete_ms > 0 && (millis() - momentDernierChangementDurete_ms < 1500)) {
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)
@@ -597,6 +827,13 @@ void loop1() {
}
envoyerLedsG29(masqueCible);
}
// Moteur de vibration haptique (Mix 12 Hz + 60 Hz cadencé à ~125 Hz, toutes les 8 ms)
static uint32_t dernierTickVib = 0;
if (volant_est_pret && etapeInitMoteur >= ETAPES_INIT_FFB_TOTAL && (millis() - dernierTickVib >= 8)) {
dernierTickVib = millis();
gererVibrationHaptique();
}
}
// =========================================================================
@@ -634,7 +871,14 @@ void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_re
rapportEngage = 0;
demandeRetourNeutre = false;
estArme = false;
forceEstAuNeutre = false;
rugositeTerrainExterne = 0;
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;
@@ -654,6 +898,8 @@ void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) {
etapeInitMoteur = 0;
rapportEngage = 0;
estArme = false;
forceEstAuNeutre = false;
rugositeTerrainExterne = 0;
reinitialiserCanauxCRSF();
majLedRequise = true;
}
@@ -692,6 +938,10 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
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);
@@ -719,6 +969,8 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
if (rapportEngage < 3 && !(rapportEngage < 0 && accelRaw > DEADZONE_PEDALE)) {
rapportEngage++;
majLedRequise = true;
momentDernierChocRapport_ms = millis();
directionDernierChocRapport = 1; // À-coup sec vers la droite
}
palettePlusDejaEnfoncee = true;
} else if (!pPlusActuel && palettePlusDejaEnfoncee) {
@@ -729,6 +981,8 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
if (rapportEngage > -1 && !(rapportEngage <= 0 && accelRaw > DEADZONE_PEDALE)) {
rapportEngage--;
majLedRequise = true;
momentDernierChocRapport_ms = millis();
directionDernierChocRapport = -1; // À-coup sec vers la gauche
}
paletteMoinsDejaEnfoncee = true;
} else if (!pMoinsActuel && paletteMoinsDejaEnfoncee) {
+342
View File
@@ -0,0 +1,342 @@
#!/usr/bin/env python3
"""
Test interactif de Force Feedback : Vibrations, Textures de terrain et Rumble pour Logitech G29
Permet de tester différentes fréquences, amplitudes et simulations de terrain accidenté.
"""
import os
import sys
import glob
import time
import math
import select
def find_g29():
for h in sorted(glob.glob('/dev/hidraw*')):
uevent = f'/sys/class/hidraw/{os.path.basename(h)}/device/uevent'
if os.path.exists(uevent):
try:
with open(uevent) as f:
c = f.read().upper()
if '046D:0000C260' in c or '046D:0000C24F' in c or 'LOGITECH' in c:
return h
except Exception:
pass
return '/dev/hidraw2'
def send_r30(fd, cmd7):
"""Envoie une trame de 7 octets dans le rapport HID 0x30 (64 octets au total)."""
payload = bytes([0x30]) + bytes(cmd7) + bytes([0x00] * 56)
return os.write(fd, payload)
def stop_ffb(fd):
"""Arrête les forces actives et remet le slot 0 au neutre."""
send_r30(fd, [0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) # STOP_FORCE slot 0
send_r30(fd, [0x11, 0x00, 128, 0x00, 0x00, 0x00, 0x00]) # Force neutre (128)
# Réactiver le ressort de rappel par défaut (force 140)
send_r30(fd, [0xFE, 0x0D, 0x07, 0x07, 140, 0x00, 0x00])
def play_vibration(fd, freq_hz, amplitude_0_127, duration_sec, desc=""):
"""
Génère une oscillation sinusoïdale de force constante autour du neutre (128).
freq_hz : Fréquence de la vibration en Hertz (ex: 15 à 60 Hz).
amplitude_0_127 : Force de la vibration (1 à 127).
"""
if desc:
print(f" ▶ {desc} (f = {freq_hz} Hz, amplitude = {amplitude_0_127}/127, durée = {duration_sec}s)")
t_start = time.time()
dt_target = 0.008 # Cadence d'envoi USB à ~125 Hz
while True:
t = time.time() - t_start
if t >= duration_sec:
break
# Valeur centrée sur 128 (0 = plein gauche, 128 = neutre, 255 = plein droite)
force = int(128 + amplitude_0_127 * math.sin(2.0 * math.pi * freq_hz * t))
force = max(0, min(255, force))
send_r30(fd, [0x11, 0x00, force, 0x00, 0x00, 0x00, 0x00])
time.sleep(dt_target)
stop_ffb(fd)
def test_frequences(fd):
print("\n=== TEST 1 : COMPARAISON DES FRÉQUENCES DE VIBRATION ===")
print("Pose tes mains sur le volant pour ressentir la texture...")
time.sleep(1)
samples = [
(12, 60, 2.0, "12 Hz : Grondement sourd / Régime moteur au ralenti"),
(25, 75, 2.0, "25 Hz : Gravier / Piste en terre battue"),
(40, 80, 2.0, "40 Hz : Pavés / Tôle ondulée / Vibreur de circuit"),
(60, 90, 2.0, "60 Hz : Vibration aiguë / Micro-aspérités du bitume"),
]
for freq, amp, dur, desc in samples:
play_vibration(fd, freq, amp, dur, desc)
time.sleep(0.5)
def test_amplitudes(fd):
print("\n=== TEST 2 : GRADATION D'INTENSITÉ (À 30 Hz) ===")
time.sleep(1)
intensites = [
(30, 25, 1.5, "Intensité Faible (20%) : Léger frémissement"),
(30, 60, 1.5, "Intensité Moyenne (50%) : Route accidentée"),
(30, 95, 1.5, "Intensité Forte (75%) : Gros cailloux / Ornières"),
(30, 125, 1.5, "Intensité Maximale(100%): Terrain très cassant"),
]
for freq, amp, dur, desc in intensites:
play_vibration(fd, freq, amp, dur, desc)
time.sleep(0.5)
def test_simulation_terrain(fd):
print("\n=== TEST 3 : PARCOURS DE TERRAIN PROGRESSIF ===")
print("Ce test simule un véhicule qui traverse différents types de sols :")
time.sleep(1)
sections = [
("1. Asphalte lisse", 0, 0, 2.0),
("2. Transition sur gravier fin", 35, 30, 2.0),
("3. Piste en terre avec trous et bosses", 22, 85, 3.0),
("4. Zone de gros franchissement / Cailloux", 15, 120, 2.5),
("5. Retour sur route goudronnée", 0, 0, 1.5),
]
for nom, freq, amp, duree in sections:
print(f" 🚗 Section : {nom}...")
if amp == 0:
stop_ffb(fd)
time.sleep(duree)
else:
play_vibration(fd, freq, amp, duree)
def test_chocs_ponctuels(fd):
print("\n=== TEST 4 : CHOCS SOUDAINS (Nids-de-poule & Pierres) ===")
print("Simule une roue gauche ou droite qui heurte un obstacle franc...")
time.sleep(1)
for i in range(3):
# Pause de roulage calme
stop_ffb(fd)
time.sleep(0.8)
# Choc à gauche ou à droite
direction = "GAUCHE" if i % 2 == 0 else "DROITE"
force_choc = 20 if direction == "GAUCHE" else 235
print(f" 💥 CHOC ROUE {direction} !")
# Impulsion très brève et forte (50 ms)
for _ in range(5):
send_r30(fd, [0x11, 0x00, force_choc, 0x00, 0x00, 0x00, 0x00])
time.sleep(0.01)
# Rebond opposé amorti (40 ms)
force_rebond = 170 if direction == "GAUCHE" else 85
for _ in range(4):
send_r30(fd, [0x11, 0x00, force_rebond, 0x00, 0x00, 0x00, 0x00])
time.sleep(0.01)
stop_ffb(fd)
def test_mix_12_60(fd):
print("\n=== TEST 6 : MIX DOUBLE-COUCHE HAPTIQUE (12 Hz + 60 Hz) ===")
print("Compare les deux fréquences isolées puis leur superposition simultanée :")
time.sleep(1)
print(" 1/4 : 12 Hz seul (Gros grondement / secousses mécaniques)...")
play_vibration(fd, 12, 65, 2.0)
time.sleep(0.5)
print(" 2/4 : 60 Hz seul (Texture de surface / grain du bitume)...")
play_vibration(fd, 60, 65, 2.0)
time.sleep(0.5)
print(" 3/4 : SUPERPOSITION 12 Hz + 60 Hz (Double texture simultanée)...")
t_start = time.time()
while time.time() - t_start < 3.0:
t = time.time() - t_start
# 12 Hz donne l'amplitude de fond, 60 Hz superpose le grain de surface
v12 = 45.0 * math.sin(2.0 * math.pi * 12.0 * t)
v60 = 35.0 * math.sin(2.0 * math.pi * 60.0 * t)
force = int(128 + v12 + v60)
force = max(0, min(255, force))
send_r30(fd, [0x11, 0x00, force, 0x00, 0x00, 0x00, 0x00])
time.sleep(0.008)
stop_ffb(fd)
time.sleep(0.5)
print(" 4/4 : SIMULATION TOUT-TERRAIN DYNAMIQUE...")
print(" (Fond de roulement 60 Hz continu + bouffées de 12 Hz sur les ornières)")
t_start = time.time()
while time.time() - t_start < 4.0:
t = time.time() - t_start
# Enveloppe d'ornières toutes les 0.8s
choc_orniere = math.sin(2.0 * math.pi * 1.25 * t)
amp12 = 70.0 if choc_orniere > 0.4 else 15.0
v12 = amp12 * math.sin(2.0 * math.pi * 12.0 * t)
v60 = 30.0 * math.sin(2.0 * math.pi * 60.0 * t)
force = int(128 + v12 + v60)
force = max(0, min(255, force))
send_r30(fd, [0x11, 0x00, force, 0x00, 0x00, 0x00, 0x00])
time.sleep(0.008)
stop_ffb(fd)
def test_interactif_pedales(fd):
print("\n=== TEST 5 : SIMULATEUR INTERACTIF EN DIRECT (PÉDALES & VOLANT) ===")
print("Prends le volant et appuie sur les pédales :")
print(" - ACCÉLÉRATEUR : Augmente le régime moteur (fréquence + rumble)")
print(" - FREIN FORT : Déclenche la vibration d'ABS / blocage de roue")
print(" - PALETTES +/- : Secousse mécanique de passage de rapport")
print(" - [Ctrl + C] : Quitter le simulateur")
print("\nInitialisation en cours...")
# Assurer le recentrage et la butée 180°
send_r30(fd, [0xF8, 0x81, 0xB4, 0x00, 0x00, 0x00, 0x00]) # Range 180°
send_r30(fd, [0xFE, 0x0D, 0x07, 0x07, 130, 0x00, 0x00]) # Ressort
rapport = 1
palette_plus_prev = False
palette_moins_prev = False
choc_rapport_timer = 0
choc_direction = 1
t_start = time.time()
try:
while True:
# 1. Lecture non bloquante des rapports HID du G29
r, _, _ = select.select([fd], [], [], 0.008)
accel_pct = 0.0
frein_pct = 0.0
p_plus = False
p_moins = False
if r:
data = os.read(fd, 64)
if len(data) >= 51 and data[0] == 0x01:
accel_raw = 65535 - (data[45] | (data[46] << 8))
frein_raw = 65535 - (data[47] | (data[48] << 8))
accel_pct = max(0.0, min(100.0, (accel_raw / 65535.0) * 100.0))
frein_pct = max(0.0, min(100.0, (frein_raw / 65535.0) * 100.0))
b6 = data[6]
p_moins = bool(b6 & 0x01)
p_plus = bool(b6 & 0x02)
# Gestion des passages de vitesses
if p_plus and not palette_plus_prev:
if rapport < 4: rapport += 1
choc_rapport_timer = time.time()
choc_direction = 1
if p_moins and not palette_moins_prev:
if rapport > 1: rapport -= 1
choc_rapport_timer = time.time()
choc_direction = -1
palette_plus_prev = p_plus
palette_moins_prev = p_moins
# 2. Calcul du retour de force (FFB) en fonction de l'état
now = time.time()
force_calc = 128
# Cas A : À-coup sec au passage de rapport (durée 70 ms)
if now - choc_rapport_timer < 0.07:
force_calc = 128 + choc_direction * 90
# Cas B : Freinage violent (> 70%) -> Vibration ABS rapide
elif frein_pct > 70.0:
abs_amp = int((frein_pct - 70.0) * 3.0)
force_calc = int(128 + abs_amp * math.sin(2.0 * math.pi * 45.0 * now))
# Cas C : Régime moteur lié à l'accélérateur et au rapport (Mix 12 Hz + 60 Hz)
else:
# 12 Hz : Grondement moteur qui monte légèrement en fréquence et amplitude avec les gaz
freq_moteur = 12.0 + (accel_pct * 0.15)
amp_moteur = 15.0 + (accel_pct * 0.45)
v_moteur = amp_moteur * math.sin(2.0 * math.pi * freq_moteur * now)
# 60 Hz : Grain de roulement et vibration mécanique qui augmente avec la vitesse
amp_vitesse = (accel_pct * 0.35) * (1.0 + (rapport - 1) * 0.25)
v_roulement = amp_vitesse * math.sin(2.0 * math.pi * 60.0 * now)
force_calc = int(128 + v_moteur + v_roulement)
force_calc = max(0, min(255, force_calc))
send_r30(fd, [0x11, 0x00, force_calc, 0x00, 0x00, 0x00, 0x00])
# Affichage console synthétique toutes les 150 ms
if int(now * 6) != int((now - 0.008) * 6):
barre_gaz = "█" * int(accel_pct / 5) + "-" * (20 - int(accel_pct / 5))
barre_frein = "█" * int(frein_pct / 5) + "-" * (20 - int(frein_pct / 5))
sys.stdout.write(f"\r[VITESSE: {rapport}] Gaz: [{barre_gaz}] Frein: [{barre_frein}] FFB: {force_calc:3d} ")
sys.stdout.flush()
except KeyboardInterrupt:
print("\n\nArrêt du simulateur interactif.")
finally:
stop_ffb(fd)
def main():
dev = find_g29()
print(f"============================================================")
print(f" TEST FORCE FEEDBACK : VIBRATIONS & RUGOSITÉ G29 ({dev}) ")
print(f"============================================================")
try:
fd = os.open(dev, os.O_RDWR)
except Exception as e:
print(f"Erreur d'ouverture du périphérique {dev} : {e}")
print("Vérifie les permissions (ex: sudo ou groupe input/plugdev).")
sys.exit(1)
menu = {
"1": ("Tester les différentes fréquences (12 Hz à 60 Hz)", test_frequences),
"2": ("Tester les différentes intensités (20% à 100%)", test_amplitudes),
"3": ("Simulation complète de terrain (Asphalte -> Terre -> Cailloux)", test_simulation_terrain),
"4": ("Simulation de chocs soudains (Trous & Cailloux isolés)", test_chocs_ponctuels),
"5": ("SIMULATEUR COMPLET EN DIRECT (Moteur, Pédales, Boîte & ABS)", test_interactif_pedales),
"6": ("TEST DOUBLE-COUCHE HAPTIQUE (Superposition 12 Hz + 60 Hz)", test_mix_12_60),
"0": ("Remettre à zéro (Arrêt FFB et recentrage par défaut)", stop_ffb),
}
if len(sys.argv) > 1:
choix = sys.argv[1].strip()
if choix in menu:
desc, action = menu[choix]
print(f"\n▶ Exécution : {desc}")
action(fd)
stop_ffb(fd)
os.close(fd)
return
try:
while True:
print("\nChoisis un test à lancer :")
for k, (desc, _) in menu.items():
print(f" [{k}] {desc}")
print(" [Q] Quitter")
choix = input("\nTon choix : ").strip().upper()
if choix in ('Q', 'QUIT'):
break
if choix in menu:
desc, action = menu[choix]
action(fd)
stop_ffb(fd)
else:
print("Choix invalide.")
except KeyboardInterrupt:
print("\nInterruption.")
finally:
stop_ffb(fd)
os.close(fd)
print("Fin du programme. G29 remis au neutre.")
if __name__ == '__main__':
main()