I am getting some values from my Arduino over the serial port. The data has the format:
"value1,value2,value3\r"
as a string
.
Example: "4.5,550.0,0.02\r"
I can recieve and separate the values but when I try to convert them to double
I get the following exception
"input string was not in a correct format"`.
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;
}
Two things are a problem here. First, the conversion may fail because of regional settings (invalid decimal point character), so use CultureInfo.InvariantCulture
from System.Globalization
namespace as an additional parameter. Second thing, you are cutting off one character from your substrings, so remove -1
.
string data = "4.5,550.0,0.02\r";
string bv = data.Substring(0, data.IndexOf(","));
data = data.Substring(data.IndexOf(",") + 1);
string v0 = data.Substring(0, data.IndexOf(","));
data = data.Substring(data.IndexOf(",") + 1);
string i = data;
double batteryVoltage = Convert.ToDouble(bv, CultureInfo.InvariantCulture);
double V0 = Convert.ToDouble(v0, CultureInfo.InvariantCulture);
double I = Convert.ToDouble(i, CultureInfo.InvariantCulture);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With