Problems reading data from arduino to C#

I have a temprature sensor (TMP36), and I want to show it's value in c# in a text label and a progressbar.
I have floating values in my serial monitor but I get an error when I try to get them into c#. The progress bar needs an int value?

using System.IO.Ports;

namespace Recieve_data_from_Arduino
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();

        }

        static string line;

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //MessageBox.Show(serialPort1.ReadLine());
            line = serialPort1.ReadLine();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = line;
          if(line == null)
            {
                line = "0";
            }
            int pBar =Int32.Parse(line);
            progressBar1.Value = pBar;
        }
    }
}

FormatExeption unhandled: An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

I get that the "line" value is "19.34\r"

Tell me if you need to see my arduino code. Thanks for answars :slight_smile:

It looks like at the end of your float obtained from the arduino, you have got some formatting characters:

19.34\r

which int32.Parse() doesn't like.

Try stripping these characters out of line before the conversion attempt.

I'm really curious as to why you are using Int32.Parse() to parse a string that you KNOW isn't an ASCII representation of an int.

Hmm, I tried with an different arduino code, and that worked well(without the calculation), so I guess it is the "\r" c# does not like.

What should i change or add to my orignial arduino code?

int analogpin = 0;

void setup() {
Serial.begin(9600); 
}

void loop() {
int val = analogRead(analogpin);

float voltage = val * 5;

voltage /= 1024;

float temp = (voltage-0.5)*100;

Serial.print(temp);

delay(1000);

}

Working code, but without calculation:

int analogpin = 0;

void setup() {
Serial.begin(9600);
}

void loop() {
int val = analogRead(analogpin);
Serial.println(val);
delay(1000);
}

What should i change or add to my orignial arduino code?

That depends on what change you want to happen.

You can make the C# application get rid of the \r on the end of the string instance, by using the TrimEnd() method.

You'll most likely still have to convert your float to a integer scale if your progress bar only accepts integers though. Or suffer truncation :slight_smile:

Thank you guys for answers:) I have now trimmed my value in c#, "18.52\r" becomes "18.52". But I am still struggling... I am able to show the value as a text label, but can't convert it to an int for the progress bar, due to some format trouble. When converting I get the error: "FormatExeption unhandled: An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll" - "Additional information: input string had an invalid format."

namespace Recieve_data_from_Arduino
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();

        }

        static string line;

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            line = serialPort1.ReadLine();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
           label1.Text = line;

         if(line == null)
            {
                line = "0";
            }


            string arduino = line.Replace("\r", "");

            
            line = line.TrimEnd();

            int pBar = Convert.ToInt32(line);

            progressBar1.Value = pBar;
        }
    }
}

Any suggestions?:slight_smile:

Jens1024:
Any suggestions?:slight_smile:

As PaulS mentioned above, you're calling Int32.Parse() with a string that doesn't represent an integer. If you want an integer, there are a few ways to go:

  • Have your Arduino sketch send an integer to begin with. If your progress bar just goes from 0-100%, and if you don't need the number for any other reason, then this approach is somewhat attractive because numbers in the range of 0-100 will fit into a single byte, and sending/receiving single bytes (instead of big long character strings) is really cheap, performance-wise. (The fact that you're sending floats might suggest other opportunities in your Arduino sketch to get rid of the floats, as they're a performance killer in general.)
  • Turn the parsed float into an int, e.g.: int pBar = **(int)**float.Parse(line);
  • Chop off everything from the "." onward (not just the "\r") before calling int.Parse().

I'd say those options are in order of my own preference. The last one only really makes sense if you've got some academic reason for calling int.Parse() no matter what.

Final suggestion: If you anticipate doing a lot of C# coding, I'd suggest a C# primer and some time spent warming up to MSDN and to the Microsoft forums. Asking general C# questions on an Arduino forum isn't going to be the most efficient or effective. :slight_smile:

and some time spent warming up to MSDN and to the Microsoft forums.

I've been dabbling with C# programming for years, and those are the worst possible places to get help.

PaulS:
I've been dabbling with C# programming for years, and those are the worst possible places to get help.

I agree, go to StackOverflow instead