T3.6 Simple AnalogRead While loop with Serial Debug generates corrupt debug

Status
Not open for further replies.

cloudy9

New member
The below code outputs crazy debug on a T3.6 - seems to be related to the analog read - any ideas?
It's worse if A10 is floating, but the output is still corrupted if I ground A10....

n

n

⸮D ⸮⸮ ⸮
n
Brake Pressure reached:
n
⸮⸮⸮.
n

n


n
C
n
⸮@
n

n
Brake Pressure reached:
n
@
n

n
$
n
l
n
Brake Pressure reached:
n
Brake Pressure reached:
n
Brake Pressure reached:



Code:
void setup() {
Serial.begin(115200);
Serial.println("STARTUP");
}

void loop() {
ApplyParkBrake(400);
delay(20);
}

void ApplyParkBrake(int pressure)
{
int  currentpressure;
elapsedMillis timeElapsed;
 Serial.println("Applying park brake at pressure: " + pressure);
while(analogRead(A10) < pressure){
  delay(10);
   currentpressure = analogRead(A10);
   if (timeElapsed > 3000){ //Give up if pressure not reached in 3 seconds
   Serial.println("Specified Brake Pressure not reached - Timeout");
    break;
  }
}
 Serial.println("Brake Pressure reached: " + currentpressure);
}
 
Reason was Serial.print("Applying park brake at pressure: " + pressure); not valid - instead

Serial.print("Applying park brake at pressure: ");
Serial.println(pressure);

This seems to work normally now, but interested to know why it gave this behaviour?
 
but interested to know why it gave this behaviour?

Technically the string literal is an array of characters. From the compiler's point of view, it's the address in memory where the array of chars is stored. When you add an integer to a char array (not a String object, but array of chars), you're telling the compiler to start printing whatever chars happen to be in memory *after* the beginning of the array. For a small number, this could be used to skip the first part of the array. But if you add a large number, you're telling the compiler to give Serial.print() the address of whatever happens to exist in memory *after* the end of your chars.

You could instead try something like this:

Code:
Serial.println(String("Applying park brake at pressure: ") + pressure);

This creates a String object which gets initialized with an array of chars. String objects do support addition to append, and they do support adding non-String objects which get converted to String.

But if neither of the things you're adding is already a String object, then the compiler see a string literal (stuff between double quotes) as an array of chars, not a String object.

Most people just use 2 Serial.print(), or Serial.printf() if they're familiar with the somewhat cryptic syntax of printf.
 
Status
Not open for further replies.
Back
Top