Created
May 16, 2016 15:39
-
-
Save hunandy14/7337c945691c8eee8486e7756592d66c to your computer and use it in GitHub Desktop.
Arduino輸入字串切割成陣列
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************************** | |
Name:Input String Split Arduino | |
DATE:2016/05/16 | |
By CharlotteHong | |
**********************************************************/ | |
#define led 13 | |
char str[32]=""; | |
/* ================================================== */ | |
void setup() { | |
pinMode(led, OUTPUT); | |
Serial.begin(9600); | |
Serial.print("Welocom split.\n"); | |
} | |
void loop() { | |
ScanSerialStr(); | |
} | |
/* ================================================== */ | |
int* str_split(const char* str, const char* sp){ | |
int *ptr; | |
char *temp; | |
// 計算字串內總共有幾個數 | |
int len=1; | |
for (int i = 0; i < strlen(str); ++i){ | |
if ( str[i] == sp[0]) | |
len++; | |
} | |
// 根據長度配置記憶體 | |
ptr = (int*)malloc(sizeof(int)*(len+1)); | |
*ptr = (int)(len); | |
// 開始切割 | |
int tempflag=0,index=1; | |
temp = (char*)malloc(sizeof(char)); | |
for (int i = 0; i <= strlen(str); ++i){ | |
if ( str[i] == sp[0] || i==strlen(str)){ | |
len++; | |
tempflag=0; | |
// printf("temp=%c%c\n",temp[0],temp[1] ); | |
sscanf(temp, "%d", (ptr+index)); | |
index++; | |
free(temp); | |
temp = (char*)malloc(sizeof(char)); | |
} | |
else{ | |
temp[tempflag++]=str[i]; | |
} | |
} | |
free(temp); | |
return ptr; | |
} | |
void ScanSerialStr(){ | |
if(Serial.available()) { | |
int strnum=0; | |
memset( str, 0, strlen(str) ); | |
while (Serial.available() > 0){ | |
str[strnum++] = Serial.read(); | |
delay(3); | |
} | |
/* Arduino印出自己輸入的 */ | |
Serial.print("Arduino Input :"); | |
Serial.println(str); | |
int *array=str_split(str,","); | |
print_arr(array); | |
} | |
} | |
void print_arr(int* array){ | |
Serial.print("["); | |
Serial.print(array[0]); | |
Serial.print("],["); | |
for (int i = 1; i <= array[0]-1; ++i){ | |
Serial.print(array[i]); | |
Serial.print(","); | |
}Serial.print(array[array[0]]); | |
Serial.print("]"); | |
} | |
/* ================================================== */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment