我通过串口从我的 Arduino 获得一些值。数据的格式为:
"value1,value2,value3\r"
作为string
.
示例:"4.5,550.0,0.02\r"
我可以接收并分离这些值,但是当我尝试将它们转换为时,double
出现以下异常
“输入字符串的格式不正确”`。
double Battery = 0, Voltage = 0, Current = 0;
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = serialPort1.ReadLine();
string bv = data.Substring(0, data.IndexOf(",") - 1);
data = data.Substring(data.IndexOf(",") + 1);
string v0 = data.Substring(0, data.IndexOf(",") - 1);
data = data.Substring(data.IndexOf(",") + 1);
string i = data;
double batteryVoltage = Convert.ToDouble(bv);
double V0 = Convert.ToDouble(v0);
double I = Convert.ToDouble(i);
Battery = batteryVoltage;
Voltage = V0;
Current = I;
}