Introduction

In this article, we'll walk you through creating a Windows application using C# to control an Arduino board via serial communication. We will turn an LED on and off using a relay switch connected to the Arduino. This project is perfect for beginners to learn about integrating Arduino with C# applications.

Set Up the Arduino

1. Upload the following code to the Arduino

int relayPin = 7;
void setup() {
  pinMode(relayPin, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  if (Serial.available()) {
    char command = Serial.read();
    if (command == '1') {
      digitalWrite(relayPin, HIGH);
    } else if (command == '0') {
      digitalWrite(relayPin, LOW);
    }
  }
}

2. Create the C# Windows Application

Configure the SerialPort component to match the Arduino's settings (9600 baud rate, COM port, etc.).

3. C# Code to Control Arduino

In the Form 1. cs file, add the following code.

using System;
using System.IO.Ports;
using System.Windows.Forms;
public partial class Form1 : Form
{
    SerialPort arduinoPort;
    public Form1()
    {
        InitializeComponent();
        arduinoPort = new SerialPort("COM3", 9600);
        arduinoPort.Open();
    }
    private void btnOn_Click(object sender, EventArgs e)
    {
        arduinoPort.Write("1");
    }
    private void btnOff_Click(object sender, EventArgs e)
    {
        arduinoPort.Write("0");
    }
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        arduinoPort.Close();
        base.OnFormClosing(e);
    }
}

4. Build and Run the Application

Conclusion

This project demonstrates how to control an Arduino using a C# Windows application via serial communication. By following these steps, you can expand this basic setup to control multiple devices and integrate more complex functionality into your projects.