avoid using String class on a Mega which has low memory - it can fragment memory causing problems
read the text into a char array and parse it using sscanf(), e.g.
// parse comma seperated int data, e.g. 0,1,2,2,1,2,1
const int numValues = 36; // 받을 정수의 개수
int receivedValues[numValues]; // 수신된 정수 배열을 저장할 배열
int index = 0; // 배열 인덱스 추적
void setup() {
Serial.begin(115200); // 시리얼 통신 속도 설정
}
void loop() {
char data[100] = { 0 };
if (Serial.available() > 0) {
// read text into char array
Serial.readBytesUntil('\n', data, 100);
Serial.println(data);
char *ptr = data; // point at start of text
for (index = 0; index < 36; index++) {
// attempt to read an integer - break if it fails
if (sscanf(ptr, "%d", &receivedValues[index]) != 1) break;
// find next , add 1
ptr = strchr(ptr, ',') + 1;
//Serial.println(receivedValues[index]);
//Serial.println(ptr);
}
// display parsed data
Serial.print("receivedValues ");
for (int i = 0; i < index; i++) {
Serial.print(' ');
Serial.print(receivedValues[i]);
}
}
}
when " 0,1,2,2,1,2,1\n" is entered serial monitor displays
0,1,2,2,1,2,1
receivedValues 0 1 2 2 1 2 1
an alternative is to use strtok() function to break the text into tokens, e.g.
// parse string extracting numeric values to comma seperated list
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void setup() {
Serial.begin(115200);
char str[] = "0,1,2,2,1,2,1";
char* pch;
Serial.print("\nextracting numeric values from comma seperated list: ");
Serial.println(str);
pch = strtok(str, ",");
while (pch != NULL) {
//Serial.print ("token found ");
//Serial.println(pch);
int data;
if (sscanf(pch, "%d", &data) == 1) {
Serial.print("int value ");
Serial.println(data);
}
pch = strtok(NULL, ":,");
}
}
void loop() {}
serial monitor displays
extracting numeric values from comma seperated list: 0,1,2,2,1,2,1
int value 0
int value 1
int value 2
int value 2
int value 1
int value 2
int value 1