Introduction: C# Arduino GUI to Control the LED

About: Green hand in arduino

This tutorial will tell you how to make a simplest GUI to control your arduino. Basicly, this post is about communication between C# and Arduino: Send data and commands from Computer to an Arduino. So, you will also learn something about C# serial communication.

I will use LattePanda to do this project. Make the best use of its touch screen, I can just use my finger to play this GUI! LattePanda is a Win10 single board computer, it also integrated Arduino Compatible Processor, so you can control the physical world easily. If you don't have it, no worries, you can connect the Arduino to your PC instead!

Step 1: What You Need

Hardware

Software

  • Viusal Studio
  • Arduino IDE

Step 2: C# Code

Creat a new windows Form project. In the Toolbox on the left side, drag out 2 button components from toolbox. Rename them,one is 'ON', one is 'OFF'.

public partial class Form1 : Form
{
SerialPort port;

public Form1() { InitializeComponent();

this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);

if (port == null) { //Change the portname according to your computer port = new SerialPort("COM4", 9600); port.Open(); } }

void Form1_FormClosed(object sender, FormClosedEventArgs e)
{ if (port != null && port.IsOpen) { port.Close(); } }

private void button1_Click(object sender, EventArgs e)
{ PortWrite("1"); }

private void button2_Click(object sender, EventArgs e) { PortWrite("0"); }

private void PortWrite(string message)
{ if (port != null && port.IsOpen) { port.Write(message); } } }

Step 3: Arduino Sketch

Open Arduino IDE, Upload the following code to your board.

const int LedPin = 3;int ledState = 0;
void setup() { pinMode(LedPin, OUTPUT); Serial.begin(9600); } void loop() { char receiveVal; if(Serial.available() > 0) { receiveVal = Serial.read(); if(receiveVal == '1') ledState = 1; else ledState = 0; } digitalWrite(LedPin, ledState); delay(50); }

Step 4: Showtime

When you click the 'ON' button the LED light will turn on.

So far so good?

If you other things instead of the LED, then you can use your mouse to control everything!! That's a very useful function. Hope this tutorial is useful for you! If you have any questions, please let me know!