Resetting sprintf buffer

I’ve got these definitions in the prolog of my sketch:

float temp = 0;
int light = 0;
int len;
char tempstr[7];
char SPRbuffer[120];

And tihs code inside my main loop():

  void loop() {  
  light = analogRead(LightPin);
  temp = analogRead(TempPin);
  temp *= 5;
  temp /= 1023;
  temp -= 0.5;
  temp *= 100;
  dtostrf(temp, 7, 2, tempstr);
  len = sprintf (SPRbuffer, "Temp: %s, Light: %d ", tempstr, light);
  Serial.println(SPRbuffer);
}

It’s reading a TMP36 temp sensor and a photo resistor (just to get some interesting data to play with).
The sketch keeps failing with a buffer overflow due to the continual growth of SPRbuffer.

Temp:   13.05Temp: , Light: 552
Temp:   13.05Temp:   13.05Temp:   13.05Temp: , Light: 552
Temp:   13.05Temp:   13.05Temp:   13.05Temp:   13.05Temp:   13.05Temp: , Light: 552
Temp:   13.05Temp:   13.05Temp:   13.05Temp:   13.05Temp:   13.05Temp:   13.05Temp:   13.05Temp: , Light: 552

How do I pursuade sprintf to start at the beginning of the buffer each time round the loop?

Dougie:
How do I pursuade sprintf to start at the beginning of the buffer each time round the loop?

I honestly wouldn’t have thought you would have needed to do that, but how about adding a

SPRbuffer[0] = '\0';

Right after the Serial.println call?

Brad (KF7FER)

I honestly wouldn't have thought you would have needed to do that

You don't. tempstr is too small. In needs to be at least eight bytes in size.

I suspect that tempstr is not null terminated, because it is only 7 characters long and you are telling dtostrf() to fill in at least 7 characters.

Also, it's safer to use snprintf() than sprintf() so you can avoid buffer overruns.

[quote author=Coding Badly link=topic=93189.msg700280#msg700280 date=1329878162]

I honestly wouldn't have thought you would have needed to do that

You don't. tempstr is too small. In needs to be at least eight bytes in size. [/quote]

Ah... that's why. I guess I missed that, thanks. I didn't think that was needed.

Brad.

Thanks everyone.

Changing

dtostrf(temp, 7, 2, tempstr);

to

dtostrf(temp, 6, 2, tempstr);

Solved the problem.