Haoming Weng
Published © GPL3+

C# Arduino GUI to control the LED

Make a simple Arduino GUI in C# to control the LED.Tutorial about Serial communication between computer and Arduino.

BeginnerFull instructions provided1 hour21,227

Things used in this project

Story

Read more

Code

Code snippet #1

Plain text
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);
            }
        }
    }

Code snippet #2

Plain text
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);    
}

Credits

Haoming Weng

Haoming Weng

4 projects • 21 followers
A graduated student

Comments