Morning everyone I've been knock my head against a wall for some reason. I need to send back to the computer 2 fixed length strings. One of 6 characters and the other of 3 characters. For example the first would be "000001" to "100000" and the other "001" to "999".
For some reason my first Serial.print puts out nothing but the second is ok. Please see my code below. I've tried everything I know or could find.
char WOWINDING[6] = "000000";
char WOLAYER[3] = "000";
int n;
int m;
n = sprintf(WOWINDING, "%06d", 1);
m = sprintf(WOLAYER, "%03d", 1);
Serial.print(WOWINDING);
delay(1000); // waits for a second
Serial.println(n); // m and WOLAYER works ok
delay(1000);
Send_Progess();
This seems to work fine: char WOLAYER[3] = "000";
But this doesn't: char WOWINDING[6] = "000000";
if I use n I get a 6, if I use m I get a 3.
Any ideas please?
Ray
Ray_Richter:
Any ideas please?
Yes, don't overwrite your sprintf buffers.
How many bytes are needed for "%06d", or "%03d"?
Where should the terminating zero byte go?
I didn't realize the sprintf was the buffer. I thought it was a conversion function.
I need to implement 2 counters, "windCounter" for each revolution that my stepper motor turns and I want to send this back to the PC. I also need a "layerCounter" to be sent back to the PC at the end of the "windCounter".
The PC is set to see a 6 digit and a 3 digit length variable so the user knows the progress of the coil making. Right now Im just testing the formatting part.
I need front padding of zeros to keep the variable lengths. The results I get back on the PC and serial monitor are different but, I'm mostly concerned with what the PC sees.
Thanks
Ray
So far the closest I have come is this:
int n = 11;
int m = 11;
sprintf("WOWINDING,%06d", n);
Serial.println(WOWINDING); //WOWINDING
delay(500); // waits for a second
sprintf("WOLAYER,%03d", m);
Serial.println(WOLAYER); //WOLAYER
delay(500);
With the results on serial.monitor of:
000000
000
I11000000000000000
The last 9 positions are what I'm interested in right now.
Ray
Ray_Richter:
I didn't realize the sprintf was the buffer.
It isn't. You always have to allocate your own buffer for it to use. Character strings are always null (zero) terminated. Did you allow space in the buffers for the null character?
Ah nuts, I totally forgot about that. Thank you very much aarg.
I got it working now with this code:
char WOWINDING[7];
char WOLAYER[4];
int n = 11;
int m = 11;
sprintf(WOWINDING, "%06d", n);
Serial.println(WOWINDING); //WOWINDING
delay(500); // waits for a second
sprintf(WOLAYER, "%03d", m);
Serial.println(WOLAYER); //WOLAYER
delay(500);
Send_Progess();
Sometimes it's hard to see the forest from the tree, LOL.
I just have to include the 'n' & 'm' in the proper loops using better variable names.
Thank you again aarg.
Ray