I'm having a problem with code I'm writing for a project.
I'm looking for a gain value to be printed with a "#" in front of it. The "#" is being used as a filtering point in another program.The first iteration of the code works fine but when the case (case'1') is called upon again it returns garbage.
Please find attached a copy of my code, the lines of interest are:
132 to 154 - the PrintGain function.
and 333 where the function is called upon.
Below is the readout from the serial monitor:
The break points are probes in the code to find errors and the print after break point 6 "#10889" is the desired output.
--- Commands: ---
1 -> Full Range Scan
2 -> Band Scan
3 -> Tare
? -> Help
You have selected Full Scan
Returning to high point
Break point 1
10889
Break point 2
10889
Break point 3
Break point 4 #10889
Break point 5
Break point 6 #10889
0, 30
1, 35
2, 38
3, 40
4, 41
5, 42
6, 42
7, 42
8, 42
9, 42
Would you like to perform a background scan?.
Please send one of the following in Write Buffer
For background Scan.
To return to main menu.
--- Commands: ---
1 -> Full Range Scan
2 -> Band Scan
3 -> Tare
? -> Help
You have selected Full Scan
Returning to high point
Break point 1 It returns garbage here*
Plausible would be that GainVal is out of range, so rubbish is returned from the array Gains. Add a debug statement here so you see what its value is.:
OK. I assumed that because it did not get as far as printing "Break point 2", the problem was in the preceding statements.
char buff[5] is too small to hold the largest number (in this case 10889) including the end of string marker '\0'.
I'd also change:
char buff[6];
to:
char buff[6] = {0} ;
Maybe also:
GainPrint = dtostrf(Gain, 4, 0, buff);
to
GainPrint = String( dtostrf(Gain, 4, 0, buff) ) ;
If all that does not work, start commenting out statements until you find which one is printing the rubbish.
Your code:
void PrintGain (int GainVal)
{
Serial.println("Break point 1");
char buff[5];
int Gain = 0;
String GainPrint = "";
Serial.println(GainPrint);
Gain = Gains[GainVal];
Serial.println(Gain);
Serial.println("Break point 2");
GainPrint = dtostrf(Gain, 4, 0, buff);
Serial.println(GainPrint);
Serial.println("Break point 3");
String SendStr = "#";
Serial.println(SendStr);
Serial.println("Break point 4");
SendStr += String(GainPrint);
Serial.println(SendStr);
Serial.println("Break point 5");
SendStr += "\r\n";
Serial.println("Break point 6");
Serial.print(SendStr);
}