Arduino and C#

Hi!

I write a simple code in C# (windows forms) that turn on and off led by clicking with mouse on "buttonOFF" and "buttonON".

How to program (in C#) that windows form show arduino serial output in textbox? ( As shown in serial monitor for example: Serial.println ("LED IS ON"); ) -> that "LED IS ON" i want to display in text box..

My C# code:

namespace Arduino_serial
{
    
    public partial class Form1 : Form
    {
        static SerialPort serialPort1;
       
        public Form1()
        {
            serialPort1 = new SerialPort();
            InitializeComponent();
            serialPort1.PortName = "COM3";
            serialPort1.BaudRate = 9600;
            serialPort1.Open();      
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen) serialPort1.Close();
        }

        private void buttonON_Click(object sender, EventArgs e)
        {
            serialPort1.Write("1");
            buttonON.Enabled = false;
            buttonOFF.Enabled = true;
        }

        private void buttonOFF_Click(object sender, EventArgs e)
        {
            serialPort1.Write("0");
            buttonON.Enabled = true;
            buttonOFF.Enabled = false;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    
    }
}

My Arduino IDE code:

int ledPin = 13;

void setup()
{
  Serial.begin(9600); 
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  if (Serial.available())
  {
  //while (Serial.available() == 0);
   int val = Serial.read();  
  
  //svjetli
  if (val == '1') 
  {
    Serial.println("SVIJETLI"); 
    digitalWrite(ledPin, HIGH);
  }
  
  //gasi se
  else if (val == '0')
  {
    Serial.println("NE SVIJETLI");
    digitalWrite(ledPin, LOW);
  } 
   //krivi unos
   else
   {
     Serial.println("KRIVI UNOS");
   }
 }
}

Sorry on my bad English and thanks in advance! :slight_smile:

Writing serial comms routines in C# is a little more difficult than what you show.
You need to take advantage of the C# multitasking functions so that the comms
routines will run as a background task, and interface properly with the Forms
routines running in the foreground.

Also, you cannot rely on COM3 being available for your port, as Windows reserves the
lower port #'s for its own use. What you need to do is to plug in the Arduino board
and see which commport# it uses, and then use that value in your C# program.

Take a look at Smiley's Simple Terminal program. The C# source code is contained
in the downloadable Workshop16 zip file found here - you can embed it in your
own program:

http://smileymicros.com/blog/2011/06/10/serial-communications-part-2-a-simple-terminal-2/