Something weird is going on

Hi,
after 'sprintf' command ohsk value changes from 0 to 50, 51,52,...57,12337 with each trigger.
if loop is triggered with a button on arduino,

hacscont = digitalRead(hac_trg);
if (hacscont != ohsk)
{Serial.println(ohsk);
if 
(hacscont == HIGH) {hacs++;
Serial.println(ohsk);
char chacs[5];
Serial.println(ohsk);
String stra(hacs);
Serial.println(ohsk);
stra.toCharArray (chacs,5);  
Serial.println(ohsk);
char charchacs[5];
Serial.println(ohsk);
String strx(chacs);
Serial.println(ohsk);
strx.toCharArray(charchacs,5);  
Serial.println(ohsk);
sprintf(HCSson,"%s %s",HCS,charchacs);
Serial.println("AFTER THAT");                                  //!!!!!!
Serial.println(ohsk);                                                //!!!!
delay (50);
mqttClient.setServer(server, 1883);if (mqttClient.connect("Counter 1")){ Serial.println("Connected to server -------HCS"); mqttClient.setCallback(subscribeReceive);} 
delay (50) ;
mqttClient.subscribe("Counter 1");if(mqttClient.publish("Counter 1", HCSson)){ Serial.println("Message Sent-------HCS");}
delay(50);
}
ohsk = hacscont;
}

I have three similar if loops with exact same pattern runs regularly.
I don't know if is there something I'm missing.

Serial monitor screen capture is attached

You need to show more code. We have no idea how ohsk is declared.

Please - use the auto-format tool before posting code.

AWOL:
Please - use the auto-format tool before posting code.

That's gotta be a troll. Nobody writes code like that. Someone obviously went through and removed all the line breaks and then added them back in at random.

Effective use of comments:

Serial.println("AFTER THAT");                                  //!!!!!!
Serial.println(ohsk);                                                //!!!!

Perehama:
You need to show more code. We have no idea how ohsk is declared.

Sorry for the format
Yes I've deleted irrelevant lines beacause I wanted to leave the required lines, it was not a good idea. :slightly_frowning_face:

The code is attached
My problem is at line 203

I've added serial.println to every line at this loop beacause I wanted to see when ohsk value goes to 50's

I'll be happy if you can help me

Thank You

for_forum_2.ino (26.6 KB)

char HCSson [15];
const char* HCS = "Wrong status :";  //
 char charchacs[5];
 sprintf(HCSson, "%s %s", HCS, charchacs);

The HCSson array is not large enough to hold the data being put in it so other data is being overwritten

UKHeliBob:
The HCSson array is not large enough to hold the data being put in it so other data is being overwritten

Thank You so much for your support.

Changed to:

char HCSson [25];

And all good now.
:slight_smile:

If you had used snprintf, as I suggested, you would have found this problem much sooner and your program would fail much more gracefully.