Control the LED by GUI in C#

Published

Introduction: Control the LED by GUI in C#

About: Green hand in arduino

I will try to build GUI in C# that can control the LED lights. Originally, we need a laptop and Arduino to realize this function.But now, we have Lattepanda!


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: Hardware List

  • Lattepanda
  • HDMI label
  • Mouse
  • Keyboard

Step 2: Software Setup

Step 3: C# Code

Creat a new windows Form project. Drag out 2 button components from toolbox.Rename them,one is 'ON', one is 'OFF'.

<p>public partial class Form1 : Form<br>    {
        SerialPort port;</p><p>        public Form1()
        {
            InitializeComponent();</p><p>            this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);</p><p>            if (port == null)
            {
                //Change the portname according to your computer
                port = new SerialPort("COM4", 9600);
                port.Open();
            }
        }</p><p>void Form1_FormClosed(object sender, FormClosedEventArgs e)<br>        {
            if (port != null && port.IsOpen)
            {
                port.Close();
            }
        }</p><p>private void button1_Click(object sender, EventArgs e)<br>        {
            
                PortWrite("1");
            
        }</p><p>        
        private void button2_Click(object sender, EventArgs e)
        {
           
                PortWrite("0");
            
        }</p><p>private void PortWrite(string message)<br>        {
            if (port != null && port.IsOpen)
            {
                port.Write(message);
            }
        }
    }</p>

<br>

Step 4: Arduino Sketch

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

Step 5: Result

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

If you other things instead of the LED, then you can use your mouse to control everything!!

That's a very useful function, so I post this tutorial to show you how to do that.

Hope this tutorial is useful for you!

Enjoy:-)

Share

    Recommendations

    • Oil Contest

      Oil Contest
    • Woodworking Contest

      Woodworking Contest
    • Planter Challenge

      Planter Challenge
    user

    We have a be nice policy.
    Please be positive and constructive.

    Tips

    Questions

    Comments