Arduino에서 메시지 문자열을 받았는데 이제 메시지를 분리하여 별도의 상자에 넣기를 원합니다.C#의 여러 텍스트 상자에 다양한 값을 포함하는 메시지를 넣는 방법
메시지는 다음과 같습니다
"DEVID ~ 첫 번째 값 | $의 DevEUI ~ 2 값 | $의 HWEUI ~ 3 값 | $의 AppKey ~ 4 값 |"
메시지가 $
기호 다음에 오게됩니다. 코드는 다음과 같습니다. 런타임 중에는 메시지를 분할하고 "value"문자열은 매번 새로운 값을 갖지만 모든 텍스트 상자는 현재 동일한 값을 포함합니다.
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort Arduino = (SerialPort)sender;
string indata = Arduino.ReadExisting();
Debug.WriteLine("Data Received:");
Debug.Print(indata);
isConnected = true;
RxString = RxString + indata;
int endmarkerPos = RxString.IndexOf('|');
if(endmarkerPos != -1)
{
//now pack everything till endmarker into messageString and delete this part from RxString
messageString = RxString.Substring(0, RxString.IndexOf('|'));
Debug.Print(messageString);
RxString = RxString.Substring(endmarkerPos + 1);
}
int startmarkerPos = messageString.IndexOf('$');
if (startmarkerPos != -1)
{
messageString = messageString.Substring(startmarkerPos +1);
String command = messageString.Substring(0, messageString.IndexOf('~'));
String value = messageString.Substring(messageString.IndexOf('~') + 1);
Debug.Print("---parsed: command: " + command + "\t value: " + value);
Debug.Print("the trimmed message is: " + messageString);
if (string.Compare(command , " DevID") == 1)
{
//messageString = messageString.Substring(messageString.IndexOf('~') + 1);
textBox1.Invoke(new Action(() => textBox1.Text = value));
//textBox1.Text = value;
messageString = messageString.Substring(messageString.IndexOf('~') + 1);
Debug.Print("1st block");
}
if (string.Compare(command, " DevEUI") == 1)
{
//messageString = messageString.Substring(messageString.IndexOf('~') + 1);
textBox2.Invoke(new Action(() => textBox2.Text = value));
//textBox1.Text = value;
messageString = messageString.Substring(messageString.IndexOf('~') + 1);
Debug.Print("2nd block");
}
if (string.Compare(command, " HWEUI") == 1)
{
//messageString = messageString.Substring(messageString.IndexOf('~') + 1);
textBox2.Invoke(new Action(() => textBox3.Text = value));
//textBox1.Text = value;
messageString = messageString.Substring(messageString.IndexOf('~') + 1);
Debug.Print("3rd block");
}
if (string.Compare(command, " AppKey") == 1)
{
//messageString = messageString.Substring(messageString.IndexOf('~') + 1);
textBox2.Invoke(new Action(() => textBox4.Text = value));
//textBox1.Text = value;
messageString = messageString.Substring(messageString.IndexOf('~') + 1);
Debug.Print("4th block");
}
디버거를 사용하는 방법을 배우는 기회로 삼으십시오. 메서드의 첫 번째 줄에 중단 점을 설정하고 잘못 된 부분을 확인합니다. – LordWilmore
이것은 기껏해야 끔찍합니다. 저는'string.split' 함수를 살펴보고 여러 토큰을 나누는 법을 배웁니다. 이것은 눈에 매우 어렵습니다, 또한 디버거를 사용하여 시작합니다. – MethodMan
팁과 마찬가지로이 코드 라인이 무엇을하는지 또는 어떻게 할 것인지를 설명하는 주석을 코드에 작성하는 것이 도움이됩니다.때때로 그들은 당신의 눈을 뜨고 생각 과정 자체에서 실수를 범한다는 것을 깨닫게합니다. 코드는 단순히이 생각 과정의 결과입니다 :) Welcome to StackOverflow –