m0_46820994
2020-09-30 15:04
采纳率: 57.1%
浏览 115

报错:串口接收出错,输入字符串的格式不对

array^ DataFromSensor = gcnew array(40960); //存储传感器发来的数据
private: System::Void port_DataReceived(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e)
{
//serialPort1->DataReceived += gcnew System::IO::Ports::SerialDataReceivedEventHandler(this, &MyForm::port_DataReceived);
try
{
int ilen = serialPort1->BytesToRead; //串口读取字符数量
//array^ bytes = gcnew array(ilen);
serialPort1->Read(DataFromSensor, 0, ilen);
tbxRecvNum->Text = ilen.ToString();
if (DataFromSensor[0] == 0x64) //串口接收数据校验正确
{
if (time_flag == true)
{
DisplayDataInText(); //将温湿度数据在textBox中显示
DataToArray(); //将接受的数据存入数组,用于曲线显示
}
}
}
catch(Exception^ error)
{

MessageBox::Show("串口接收出错" + error->Message);
toolStripStatusLabel1->Text = "串口数据接收出错,请检查!\r\n";
}
}

public:System::Void DisplayDataInText()
{
String^ str = System::Text::Encoding::Default->GetString(DataFromSensor);
String^ str1 = str->Remove(0, 1);
String^ str2 = str1->Remove(4);
tbxTemp1->Text = str2; //显示传感器1的温度
String^ str3 = str1->Remove(0, 4);
String^ str4 = str3->Remove(4);
tbxHumi1->Text = str4; //显示传感器1的湿度

String^ str5 = str1->Remove(0, 8);
String^ str6 = str5->Remove(4);
tbxTemp2->Text = str6;              //显示传感器2的温度
String^ str7 = str1->Remove(0, 12);
String^ str8 = str7->Remove(4);
tbxHumi2->Text = str8;              //显示传感器2的湿度

String^ str9 = str1->Remove(0, 16);
String^ str10 = str9->Remove(4);
tbxTemp3->Text = str10;             //显示传感器3的温度
String^ str11 = str1->Remove(0, 20);
String^ str12 = str11->Remove(4);
tbxHumi3->Text = str12;             //显示传感器3的湿度

String^ str13 = str1->Remove(0, 24);
String^ str14 = str13->Remove(4);
tbxTemp4->Text = str14;             //显示传感器4的温度
String^ str15 = str1->Remove(0, 28);
String^ str16 = str15->Remove(4);
tbxHumi4->Text = str16;             //显示传感器4的湿度

}

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • threenewbee 2020-09-30 21:56
    已采纳

    具体你看程序出错的代码行,这种错误一般是字符串转换成数字的时候,字符串格式不正确,无法转换成数字造成的。

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题