2

I'm trying to make a app that read the outgoing signals from Arduino, but I can't make it work in C# Windows Forms, only in the console. Is my C# Windows Forms code wrong? I don't get any errors when I debug, but it doesn't mean that I haven't forgot something.

Here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace CommunicateWithArduino
{
    public partial class Form1 : Form
    {
        public static System.IO.Ports.SerialPort port;

        delegate void SetTextCallback(string text);

        private BackgroundWorker hardWorker;

        private Thread readThread = null;


        public Form1()
        {
            InitializeComponent();

            hardWorker = new BackgroundWorker();
            sendBtn.Enabled = false;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            System.ComponentModel.IContainer components =
                new System.ComponentModel.Container();
            port = new System.IO.Ports.SerialPort(components);
            port.PortName = comPort.SelectedItem.ToString();
            port.BaudRate = Int32.Parse(baudRate.SelectedItem.ToString());
            port.DtrEnable = true;
            port.ReadTimeout = 5000;
            port.WriteTimeout = 500;
            port.Open();

            readThread = new Thread(new ThreadStart(this.Read));
            readThread.Start();
            this.hardWorker.RunWorkerAsync();

            btnConnect.Text = "<Connected>";

            btnConnect.Enabled = false;
            comPort.Enabled = false;
            sendBtn.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (string s in SerialPort.GetPortNames())
            {
                comPort.Items.Add(s);
            }
            if (comPort.Items.Count > 0)
                comPort.SelectedIndex = comPort.Items.Count-1;
            else
                comPort.SelectedIndex = 0;

            baudRate.Items.Add("2400");
            baudRate.Items.Add("4800");
            baudRate.Items.Add("9600");
            baudRate.Items.Add("14400");
            baudRate.Items.Add("19200");
            baudRate.Items.Add("28800");
            baudRate.Items.Add("38400");
            baudRate.Items.Add("57600");
            baudRate.Items.Add("115200");

            baudRate.SelectedIndex = 2;
        }

        private void sendBtn_Click(object sender, EventArgs e)
        {
            if (port.IsOpen)
            {
                port.Write(sendText.Text);
            }
        }

        private void SetText(string text)
        {

            if (this.receiveText.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.receiveText.Text += "Text: ";
                this.receiveText.Text += text;
                this.receiveText.Text += Environment.NewLine;
            }
        }

        public void Read()
        {
            while (port.IsOpen)
            {
                try
                {
                    if (port.BytesToRead > 0)
                    {
                        string message = port.ReadLine();
                        this.SetText(message);
                    }
                }
                catch (TimeoutException) { }
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if(!(readThread == null))
                    readThread.Abort();
            }
            catch (NullReferenceException)
            {
            }

            try
            {
                port.Close();
            }
            catch (NullReferenceException)
            {
            }
        }
    }
}
3
  • What's not working? Do you receive data on the serialport, or can't you get the data from thread to gui? Commented Sep 30, 2012 at 17:27
  • If you don't know, you could: 1, log the serial data to a file, and 2, create a thread that calls SetTextevery 5th second or so. Commented Sep 30, 2012 at 17:49
  • I cant get data on the serial port in c# winform app. but in the arduino programs serial monitor i get data and i can get data on my c# console app to so there are no wrong with the arduino. but i can not get data in my winform this is driving me crazy cus i dont think there are any wrong with my winform code i posted. I writen the app so i can send data and recive data in a text box. Commented Sep 30, 2012 at 17:54

1 Answer 1

1

By default, the ReadLine method will block until a line is received. Is your Arduino program sending a line? Did you close the Arduino serial monitor program while running your program?

I would change to port.ReadChar until you verify that you are receiving characters.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes arduino its sending a line. I am using the example sketch "Serial Call and Response" that comes with the arduino programmer app. I cant run the Arduino serial monitor program while i run my program. i need to close one to run the other. I cant understand whats wrong becuse its working in c# consloe and arduino serial monitor and not in C# winform the code i posted.
can you debug.print any characters you receive to verify the program is configuring the port correctly?
The Serial Call and Response example that I just looked at is not sending a line. It is sending a single character "A" ( Serial.print('A'); ) and waiting for a response from you.
Jeff your right !! i changed Serial.print('A'); to Serial.println('A'); and it started to work tnx man.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.