Bonjour à tous ,

J'ai un petit souci avec la numérotation de mes boutons
qui disparait dès la mise à jour de l'état
si vous avez un petite suggestion àa m'indiquer je suis preneur

dans le croquis suivant on utilise ceci pour mettre en forme les 9 boutons
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
 // Initialisation des positions des boutons
  int buttonX = 20;
  int buttonY = 20;
  for ( int i = 0; i < 9; ++i)
  {
    buttons[i].x = buttonX;
    buttons[i].y = buttonY;
    //buttons[i].state = false;
	//buttons[i].state = etat[i];
 
    // Affichage des boutons
    drawButton(buttonX, buttonY, buttons[i].state);
    tft.setCursor(buttonX+35,buttonY+15);
    tft.setTextFont(2);
    tft.setTextSize(2);
    if (buttons[i].state == false) {
       tft.setTextColor(TFT_BLACK, TFT_GREEN); 
    } else {
      tft.setTextColor(TFT_BLACK, TFT_RED);   
    }
    if (i==8) {
       tft.print("#");
    } else {
       tft.print(i+1);
    }
 
 
    buttonX += BUTTON_WIDTH + BUTTON_MARGIN;
    if (buttonX + BUTTON_WIDTH > tft.width()) {
      buttonX = 20;
      buttonY += BUTTON_HEIGHT + BUTTON_MARGIN;
    }
  }
ce qui me permet d'afficher le N° des boutons à l'initialisation
mais après un changement d'état le N° disparait car il utilise cette fonction :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
 
/*******************************************************/
// Dessine un bouton à une position donnée avec un état donné
void drawButton(int x, int y, bool state) {
  uint16_t color = state ? TFT_RED : TFT_GREEN;
  tft.fillRoundRect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT,10, color);
  tft.drawRoundRect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT,10,TFT_YELLOW);
}
pour réafficher le N° il faudrait que je puisse y indiquer la variable "i" comme lors de l'initialisation
mais là pb ...

je mets le croquis en entier ci-dessous:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
 
          uPesy
                   ------------------
                   |1             32| GPIO23
   T_IRQ   GPIO36  |2             31| GPIO22
   T_OUT   GPIO39  |3             30| GPIO1
           GPIO34  |4             29| GPIO3
               NC  |5             28| GPIO21 LED
   T_DIN   GPIO32  |6             27| GPIO19   
   T_CS    GPI033  |7             26| GPIO18    
   T_CLK   GPIO25  |8             25| GPIO5 
           GPIO26  |9             24| GPIO17
           GPIO27  |10            23| GPIO16 SDO(MISO)
     SCK   GPIO14  |11            22| GPIO4  TTP223
   RESET   GPIO12  |12            21| GPIO0
 SDI(MOSI) GPIO13  |13            20| GPIO2  D/C
                   |14            19| GPIO15 CS
                   |15            18| 3V3 VCC
              GND  |16     |----| 17| GND
                   \-------|    |---/
                           |----| 
*************************************/
 
#include <SPIFFS.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <XPT2046_Touchscreen.h> // https : //github. com/PaulStoffregen/XPT2046_Touchscreen
#include <esp_now.h>
#include <WiFi.h>
#include <EEPROM.h>
 
TFT_eSPI tft = TFT_eSPI();
 
// Touchscreen pins
#define XPT2046_IRQ 36   // T_IRQ
#define XPT2046_MOSI 32  // T_DIN
#define XPT2046_MISO 39  // T_OUT
#define XPT2046_CLK 25   // T_CLK
#define XPT2046_CS 33    // T_CS
 
#define FM9 &FreeMono9pt7b
 
 
#define DELTA 32
// Bargraff
#define BACKCOLOR 0x18E3
//#define BARCOLOR 0x0620
#define BARCOLOR 0x03EF
 
#define SCALECOLOR 0xFFFF
// Interruption TPP223
const gpio_num_t vbatPin   = GPIO_NUM_35;
 
SPIClass touchscreenSPI = SPIClass(VSPI);
XPT2046_Touchscreen touchscreen(XPT2046_CS, XPT2046_IRQ);
 
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 240
#define FONT_SIZE 2
 
// definition des boutons
#define BUTTON_WIDTH  80
#define BUTTON_HEIGHT 60
#define BUTTON_MARGIN 10
 
// Structure pour représenter un bouton *************
struct Button {
  int x, y;
  bool state;
};
 
RTC_DATA_ATTR int bootCount = 0;
RTC_DATA_ATTR Button buttons[9]; // 9 boutons
RTC_DATA_ATTR float vBat = 0;
RTC_DATA_ATTR int progress = 0;
 
 
/*****************************************************************/
 
/*Imprimer les informations de l'écran tactile concernant X, Y et la pression (Z) sur le moniteur série*/
void printTouchToSerial(int touchX, int touchY, int touchZ) {
  Serial.print("X = ");
  Serial.print(touchX);
  Serial.print(" | Y = ");
  Serial.print(touchY);
  Serial.print(" | Pressure = ");
  Serial.print(touchZ);
  Serial.println();
}
/*****************************************************************/
 
/*** Structure Fichier Config.txt ********************************/
const size_t tailleMaxNom = 16;     // y compris le caractère nul final
struct ClientPC {
  char nom[tailleMaxNom];            // le nom du client PC
  uint8_t adresse[6];               // les 6 octets de son adresse
};
const size_t nbMaxClients = 20;     // nombre maximum de clients
ClientPC clients[nbMaxClients];
size_t nbClientsPC = 0;            // le nombre de clients lu dans le fichier de config
 
/*****************************************************************/
 
// ***** Structure du récepteur *************************************
struct struct_message {
  char a[32]; // ex PC1
  bool b;     // Etat = 0 ou 1
};
// Créer une struct_message appelée myData
struct_message myData;
 
//........... Etat enoi ********************************************
esp_now_peer_info_t peerInfo;
 
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nÉtat de l'envoi du dernier paquet:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Succès" : "Échec");
}
//*********************************************************************
 
// Init ESP Now with fallback
void InitESPNow() {
  WiFi.disconnect();
  if (esp_now_init() == ESP_OK) {
    Serial.println("ESPNow Init Success");
  }
  else {
    Serial.println("ESPNow Init Failed");
    // Retry InitESPNow, add a counte and then restart?
    // InitESPNow();
    // or Simply Restart
    ESP.restart();
  }
}
 
unsigned long currentTime=0;
unsigned long previousTime=0;
int touchX, touchY, touchZ , i;
int LastPercent = 0;
int valeurBrute ;
int k;
 
//************************************************
// SETUP
//************************************************
void setup()
{
  Serial.begin(115200);
  pinMode(35, INPUT);
  Calcul_vBat();
 
  //Incrémente le numéro de démarrage et l'imprime à chaque redémarrage
  ++bootCount;
  Serial.println("Boot number: " + String(bootCount));
 
  // Lire le fichier Config.txt 
  if (!SPIFFS.begin(true)) {
    Serial.println("Une erreur s'est produite lors du montage de SPIFFS");
    return;
  }
  File fichierConfig = SPIFFS.open("/config.txt", FILE_READ);
  if (!fichierConfig) {
    Serial.println("Impossible d'ouvrir le fichier en lecture");
    return;
  }
  char bufferLigne[100]; // Buffer pour stocker chaque ligne
  char format[64]; // pour bâtir dynamiquement le format en tenant compte de la longueur max du nom (reco de Kernighan et Pike dans "The Practice of Programming")
  snprintf(format, sizeof format, "%%%ds %%hhx %%hhx %%hhx %%hhx %%hhx %%hhx", tailleMaxNom - 1); // lire une chaine de taille max tailleMaxNom - 1 suivie de 6 octets en hexa
  nbClientsPC = 0;
  while (fichierConfig.available() && nbClientsPC < nbMaxClients) {   // tant qu'on peut lire quelque chose et qu'on a de la place pour stocker
    memset(bufferLigne, '\0', sizeof bufferLigne); // Effacer le buffer
    fichierConfig.readBytesUntil('\n', bufferLigne, sizeof bufferLigne); // Lire la ligne dans le buffer
    memset(clients[nbClientsPC].nom, '\0', sizeof clients[nbClientsPC].nom); // on efface le nom pour être tranquille
    int nbChampsLus = sscanf(bufferLigne, format,
                             clients[nbClientsPC].nom,
                             &clients[nbClientsPC].adresse[0], &clients[nbClientsPC].adresse[1],
                             &clients[nbClientsPC].adresse[2], &clients[nbClientsPC].adresse[3],
                             &clients[nbClientsPC].adresse[4], &clients[nbClientsPC].adresse[5]);
 
    if (nbChampsLus == 7) {
      // la lecture des 7 champs (le nom et 8 octets sous forme hexadécimale) s'est bien passée
      nbClientsPC++;
    } else {
      // on arrête de lire là
      break;
    }
  }
  fichierConfig.close();
 
  // Affichage des adresses lues depuis le fichier
  for (size_t i = 0; i < nbClientsPC; i++) {
    Serial.printf("%3zu %-*s : ", i + 1, tailleMaxNom - 1, clients[i].nom); // l'index sur 3 caractères, le nom sur tailleMaxNom - 1 cadrée à gauche
    for (int j = 0; j < 6; j++) Serial.printf("0x%02X ", clients[i].adresse[j]);
    Serial.println();
  }
 
  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);
 
  // Init ESP-NOW
  InitESPNow();
  if (esp_now_init() != ESP_OK) {
    Serial.println("Erreur d'initialisation de l'ESP-NOW");
  }
  esp_now_register_send_cb(OnDataSent);
  for (size_t i = 0; i < nbClientsPC; i++) {   // Enregistrer les  devices
    peerInfo.channel = 0;
    peerInfo.encrypt = false;
    memcpy(peerInfo.peer_addr, clients[i].adresse, 6);
    if (esp_now_add_peer(&peerInfo) != ESP_OK) {
      Serial.printf("Échec de l'ajout de %s\n", clients[i].nom);
      return;
    }
  }
 
  // Démarrer le SPI pour l'écran tactile et initialiser l'écran tactile
  touchscreenSPI.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS);
  touchscreen.begin(touchscreenSPI);
  touchscreen.setRotation(3);
  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_BLACK);
 
  // Graph Batterie
  drawScale();
  Affich_vBat(); // Afficage du niveau Batterie
 
  // Initialisation des positions des boutons
  int buttonX = 20;
  int buttonY = 20;
  for ( int i = 0; i < 9; ++i)
  {
    buttons[i].x = buttonX;
    buttons[i].y = buttonY;
    //buttons[i].state = false;
	//buttons[i].state = etat[i];
 
    // Affichage des boutons
    drawButton(buttonX, buttonY, buttons[i].state);
    tft.setCursor(buttonX+35,buttonY+15);
    tft.setTextFont(2);
    tft.setTextSize(2);
    if (buttons[i].state == false) {
       tft.setTextColor(TFT_BLACK, TFT_GREEN); 
    } else {
      tft.setTextColor(TFT_BLACK, TFT_RED);   
    }
    if (i==8) {
       tft.print("#");
    } else {
       tft.print(i+1);
    }
 
 
    buttonX += BUTTON_WIDTH + BUTTON_MARGIN;
    if (buttonX + BUTTON_WIDTH > tft.width()) {
      buttonX = 20;
      buttonY += BUTTON_HEIGHT + BUTTON_MARGIN;
    }
  }
 
  //Imprimer la raison du réveil de l'ESP32
  //print_wakeup_reason();
  esp_sleep_enable_ext0_wakeup(GPIO_NUM_4,1); //1 = High, 0 = Low
 
}
 
//************************************************
// LOOP
//************************************************
void loop()
{
    currentTime=millis();
	  // Vérifie si l'écran tactile a été touché et imprime les informations X, Y et la pression (Z) sur l'écran TFT et le moniteur série.
	if (touchscreen.tirqTouched() && touchscreen.touched())
	{
		previousTime=currentTime;  
		// Get Touchscreen points
		TS_Point p = touchscreen.getPoint();
		// Calibrate Touchscreen points with map function to the correct width and height
		touchX = map(p.x, 200, 3700, 1, SCREEN_WIDTH);
		touchY = map(p.y, 240, 3800, 1, SCREEN_HEIGHT);
		touchZ = p.z;
		//printTouchToSerial(touchX, touchY, touchZ);
 
		for (int i = 0; i < 9; ++i)
		{
		  if (touchX >= buttons[i].x && touchX <= buttons[i].x + BUTTON_WIDTH &&
			  touchY >= buttons[i].y && touchY <= buttons[i].y + BUTTON_HEIGHT)
		  {
				// Si un bouton est touché, inverse son état et met à jour l'affichage
        Serial.println();
				if( i < 8 )
				{
					buttons[i].state = !buttons[i].state;
					drawButton(buttons[i].x, buttons[i].y, buttons[i].state);
 
					/*******************************************************/
					if (buttons[i].state == 1) {
					  Serial.print("Btn "); Serial.print(i + 1); Serial.println(" enfoncé");
					  snprintf(myData.a, sizeof myData.a, "PC%02d=> ON", i + 1);
					  myData.b =  true;
					  esp_err_t result = esp_now_send(clients[i].adresse, (uint8_t *)&myData, sizeof(myData));
					  if (result == ESP_OK) {
						Serial.print("PC"); Serial.print(i + 1); Serial.println(" Envoyé avec succès");
						//etat[i] = 1;
					  } else {
						Serial.print("Erreur d'envoi des données PC"); Serial.print(i + 1);
					  }
					}
					/*******************************************************/ 
					if (buttons[i].state == 0)
					{
					  Serial.println("Btn "); Serial.print(i + 1); Serial.println(" relaché");
					  snprintf(myData.a, sizeof myData.a, "PC%02d=> OFF", i + 1);
					  myData.b =  false;
					  esp_err_t result = esp_now_send(clients[i].adresse, (uint8_t *)&myData, sizeof(myData));
					  if (result == ESP_OK) {
						Serial.print("PC"); Serial.print(i + 1); Serial.println(" Envoyé avec succès");
						//etat[i] = 0;
					  } else {
						Serial.print("Erreur d'envoi des données PC"); Serial.print(i + 1);
					  }
					}
				} 	
				if (i ==8 )
				{   
			    i = 0;
					for (i = 0; i < 8; ++i)
					{
            Serial.println();
						if (buttons[i].state == 1)
						{
						    buttons[i].state = 0;
							drawButton(buttons[i].x, buttons[i].y, buttons[i].state); 
                           	Serial.print("Btn "); Serial.print(i + 1); Serial.println(" relaché");
					        snprintf(myData.a, sizeof myData.a, "PC%02d=> OFF", i + 1);
					        myData.b =  false;
					        esp_err_t result = esp_now_send(clients[i].adresse, (uint8_t *)&myData, sizeof(myData));
					        if (result == ESP_OK)
							{
						       Serial.print("PC"); Serial.print(i + 1); Serial.println(" Envoyé avec succès");
						       //etat[i] = 0;
					        } else {
						       Serial.print("Erreur d'envoi des données PC"); Serial.print(i + 1);
					        }					
						}	
					}
				}	
		    }
		  //break;
		  delay(200);
		}
	  }
     /* 
	   if((currentTime-previousTime)>5000){  
	   //Go to sleep now
         Serial.println("Je vais m'endormir maintenant");
         delay(1000);
         esp_deep_sleep_start();  
	   }
     */ 
}
 
/*******************************************************/
// Dessine un bouton à une position donnée avec un état donné
void drawButton(int x, int y, bool state) {
  uint16_t color = state ? TFT_RED : TFT_GREEN;
  tft.fillRoundRect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT,10, color);
  tft.drawRoundRect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT,10,TFT_YELLOW);
}
 
/*******************************************************/
void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;
 
  wakeup_reason = esp_sleep_get_wakeup_cause();
 
  switch(wakeup_reason)
  {
    case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Réveil causé par un signal externe utilisant RTC_IO"); break;
    case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Réveil provoqué par un signal externe utilisant RTC_CNTL"); break;
    case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Réveil provoqué par la minuterie"); break;
    case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
    case ESP_SLEEP_WAKEUP_ULP : Serial.println("Réveil causé par le programme ULP"); break;
    default : Serial.printf("Le réveil n'a pas été causé par un sommeil profond : %d\n",wakeup_reason); break;
  }
}
 
void Calcul_vBat(){
    int cmpt = 8;
    int vBatOld = 0 ; 
    do {
       cmpt--;
       valeurBrute  = analogRead(vbatPin); // tension échantillonnée brute
       vBatOld = valeurBrute;
    } while((abs(valeurBrute-vBatOld) > DELTA) && (cmpt > 0));
    vBat = 1.40*(valeurBrute/4095.0)*3.3; // modification changement carte uPesy Vbat Brute = 3804 pour 100%
    progress = ((vBat-3.2)*100);
}
 
void Affich_vBat() 
{
  // Niveau batterie ************************************************
    Serial.print(" Valeur Brute = "); Serial.println(valeurBrute);
    Serial.print(" Vbat = "); Serial.print(vBat,2);Serial.println(" Volts"); 
    Serial.print(" % = "); Serial.println(progress); 
    if (progress != LastPercent){
      drawBar(progress);     
    }
}
 
//**************************************************************
void drawScale()
{  
  tft.drawFastVLine(300, 50,100, SCALECOLOR );  // Vertical Scale Line  
  tft.drawFastHLine(297, 50, 8,  SCALECOLOR);   // Major Division
  tft.drawFastHLine(300, 75, 5,  SCALECOLOR);   // Major Division
  tft.drawFastHLine(297, 100, 8,  SCALECOLOR);   // Minor Division
  tft.drawFastHLine(300, 125, 5,  SCALECOLOR);   // Major Division
  tft.drawFastHLine(297, 150, 8,  SCALECOLOR);   // Minor Division
}
 
//***************************************************************
void drawBar (int progress){
  if(progress < LastPercent){
    tft.fillRect(305, 50 + (100-LastPercent), 20, LastPercent - progress,  BACKCOLOR);     
  }
  else{
    tft.fillRect(305, 50 + (100-progress), 20, progress - LastPercent,  BARCOLOR);
  }    
  LastPercent = progress;  
  tft.setCursor(290,40);
  tft.setTextFont(1);
  tft.setTextSize(1);
  tft.setTextColor(TFT_WHITE, TFT_BLACK);
  tft.print(progress);tft.println("%");
}