Okay, so I've done basic java programming before, and in java you can convert an integer to a string using the .toString() function.
Is there any arduino language equivalent? Here's the specific program I'm trying to write. The code works, but when I print out integers that I think I've converted to strings in the serial monitor, I don't get the number I intended to print. Instead, I get a completely different number. For example, if I input '1' the serial monitor will output 49. If I input '2' the serial monitor will output 50. If I input 'd' the serial monitor will output 100. Why?
int onPin; //pin that's currently on
void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pins:
for (int thisPin = 11; thisPin < 14; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// read the sensor:
if (Serial.available() > 0) {
int input = Serial.read();
digitalWrite(onPin, LOW);
if (input == '1') {digitalWrite(11, HIGH); onPin = 11;}
if (input == '2') {digitalWrite(12, HIGH); onPin = 12;}
if (input == '3') {digitalWrite(13, HIGH); onPin = 13;}
String output = String(input); //this is my attempt at converting an integer to a string
Serial.println(output); //when I print stuff out, I don't get the number I intend to get (when I print out 1, I get 49)
Here's the specific program I'm trying to write. The code works, but when I print out integers that I think I've converted to strings in the serial monitor, I don't get the number I intended to print. Instead, I get a completely different number. For example, if I input '1' the serial monitor will output 49. If I input '2' the serial monitor will output 50. If I input 'd' the serial monitor will output 100. Why?
Looks like you're printing the ASCII value of the character, not the character itself. I assume you're using 1.0?
Or you can roll your own. Here's my routine to convert an unsigned int to a NUL-terminated string:
char *u2s(char *b,unsigned x)
{ unsigned t = x; /* Working copy of value to convert */
do ++b; while (t /= 10); /* Find number of digits to be output */
*b = '\0'; /* Output terminating NUL character */
do *--b = x % 10 | '0'; /* Output digits low-order first */
while (x /= 10); /* Until all digits are in the buffer */
return b; /* Return pointer to digit string */
} /* end: i2s() */
It's less than a third the advertized size of the Arduino itoa() function, and is used the same way.