OLED液晶屏幕(3)串口读取文字并分割

时间:2021-07-18 08:47:17

 

 

 https://blog.csdn.net/iracer/article/details/50334041

OLED液晶屏幕(3)串口读取文字并分割

String comdata = "";
 
void setup() {
  Serial.begin(9600);
  while(Serial.read()>= 0){} //clear serialbuffer
}
 
void loop() {
  // read data from serial port
  if(Serial.available()>0){
      delay(100);
      comdata = Serial.readString();
      Serial.print("Serial.readString:");
      Serial.println(comdata);
    }
    comdata = "";

}

  OLED液晶屏幕(3)串口读取文字并分割

Serial.readStringUntil();
说明
从串口缓存区读取字符到一个字符串型变量,直至读完或遇到某终止字符。

语法
Serial.readStringUntil(terminator)

参数
terminator:终止字符(cha型)

返回
从串口缓存区中读取的整个字符串,直至检测到终止字符。

String comdata = "";
char terminator = ',';
void setup() {
  Serial.begin(9600);
  while(Serial.read()>= 0){} //clear serialbuffer
}
 
void loop() {
  // read data from serial port
  if(Serial.available()>0){
      delay(100);
      comdata =Serial.readStringUntil(terminator);
     Serial.print("Serial.readStringUntil: ");
      Serial.println(comdata);
    }
    while(Serial.read()>= 0){}
}

  

 

分割函数

https://codeday.me/bug/20181128/417224.html


Web上和*上已经存在多个源(例如Split String into String array).

// 1待分割文字
String application_command = "{10,12,13,9,1; 4,5; 2}"


// 2分割函数
// https://*.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }

  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}


// 3调用分割

String part01 = getValue(application_command,';',0);
String part02 = getValue(application_command,';',1);
String part03 = getValue(application_command,';',2);