Pages

2016/08/22

Arduino Programming Tip - Type Conversion (Byte to String)

Below is a quick example on how to convert from Byte to String in Arduino.

**Code**

String input = "128ABCD";
byte id = 128;
String str = String(id);                  // Converting id from byte-type into string-type

void setup() {
  Serial.begin(9600);                     // Starts the serial communication
}

// The function below is from http://playground.arduino.cc/Main/FindText
// If the search String is found its position is returned, otherwise -1 is returned.
int find_text(String needle, String haystack) {
  int foundpos = -1;
  for (int i = 0; i <= haystack.length() - needle.length(); i++) {
    if (haystack.substring(i,needle.length()+i) == needle) {
      foundpos = i;
    }
  }
  return foundpos;
}

void loop() {
  Serial.print("Input String = ");
  Serial.println(input);
  if (find_text("128", input) != -1) Serial.println("128 is in the string");
  Serial.print("ID = ");
  Serial.println(id);
  Serial.print("str = ");
  Serial.println(str);
  Serial.print("Find str in input string - ");
  if (find_text(str, input) != -1) Serial.println("128 is in the string");
  delay(2000);
}

**Result**


No comments:

Post a Comment