Hi
I'am using analogRead() just for testing and got a output from 0-1023
I want to convert the output to 0000-1023, so I have always 4 numbers.
How can I convert the output from analogRead()
Peter
potmeter.ino (402 Bytes)
Hi
I'am using analogRead() just for testing and got a output from 0-1023
I want to convert the output to 0000-1023, so I have always 4 numbers.
How can I convert the output from analogRead()
Peter
potmeter.ino (402 Bytes)
You could use sprintf and "%04d", or you could use a simple filter to add the leading zeroes.
dummyload:
I am using analogRead() just for testing and got a output from 0-1023
I want to convert the output to 0000-1023, so I have always 4 numbers.
Maybe check to see if the number X is:
0 <= X <= 9.... or 10 <= X <= 99.... or 100 <= X <= 999.
For each case.... you will then know how many leading zeroes to tack onto the front end. Eg..... the number 8 is >= 0 and <= 9... so need to tack on 3 leading zeros. If number is 888 ....it's <= 999 and >= 100 .... so tack on 1 leading zero.
The remaining case would be X >= 1000...... which won't require any modifications.
dummyload:
HiI'am using analogRead() just for testing and got a output from 0-1023
I want to convert the output to 0000-1023, so I have always 4 numbers.
How can I convert the output from analogRead()Peter
Hi
I solved this to add the leading zero(s) with:
if (val < 1000) serial.print("0");
if (val < 100) serial.print("0");
if (val < 10) serial.print("0");
serial.print (val);
Peter
Another way is to convert the value to a string. Then use a built-in function to get the length of the string.
Eg.... if the number was 123, then the number of characters (ie. length of it) of it is '3'. So the number of leading zeros to tack onto the front is 4 - '3' = 1 leading zero. And, if the number was 8, then the length is '1'. So the number of leading zeros to tack onto the front is 4 - '1' = 3 leading zeros.
To produce the required number of leading zeros, just use a for loop or while loop to generate 'N' zeros...where 'N' is equal to "4 - character length".
But..... instead of using leading zeros ...... it's probably better to use leading 'space' characters (ie. white-space' character). So numbers would print out kind of like...
3
23
456
1021
dummyload:
HiI solved this to add the leading zero(s) with:
if (val < 1000) serial.print("0");
if (val < 100) serial.print("0");
if (val < 10) serial.print("0");
serial.print (val);Peter
You have it right. The sprintf() function is bigger and no faster.
It will be a little quicker if you Serial.write( '0' ) instead of using print().