The c# was not connected to my arduino hardware.

Arduino code

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

void loop()
{
if(Serial.available())
{
int c = Serial.read();
if (c == '1')
{
digitalWrite(13,HIGH);
}
else if (c == '0')
{
digitalWrite(13,LOW);
}
}
}

I was written below c# code for my arduino code.But the C# code was getting error.

The c# was not connected to my arduino hardware. How to solve this issue.

Please help me to solve this problem.

C#Code

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

namespace SerialCommunication
{
public partial class Form1 : Form
{
bool ledState = false;

public Form1()
{
InitializeComponent();

serialPort1.PortName = "COM4";
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");
textBox1.Text = "LED is on!";
buttonOn.Enabled = false;
buttonOff.Enabled = true;
ledState = true;
}

private void buttonOff_Click(object sender, EventArgs e)
{
serialPort1.Write("0");
textBox1.Text = "LED is off!";
buttonOn.Enabled = true;
buttonOff.Enabled = false;
ledState = false;
}
}
}

santhoon:
But the C# code was getting error.

That you don't plan on sharing with us?

Use code tags when posting code.

How do you know that COM4 is the correct COM port to use?

Do you have any other applications running that could be using that COM port at the point your launched your C# application?