076 Software Controlled LED

Objective

 
Use C# to toggle power to LED.

 

Parts

 
1x Arduino R3

1x USB A-to-B cable

1x 300 ohm resistor (or there about)

1x 5mm LED

1x Breadboard

2x Jumper wires

 

Required Apps

 
Download Arduino IDE and install

Download Visual Studio and install

* This was tested using Arduino 1.8.13 and Visual Studio Community 2019

 

Build Circuit


On your breadboard

Connect your LED, resistor, and two jumper wires. The white jumper will connect to the ground. The red jumper will connect to the positive.

 

On the Arduino

Connect the white jumper to the GND. Connect the red jumper to #13.

Connect USB cable to Arduino board and computer. The computer should detect it.

 

Code


In the Arduino IDE

To start a new project: File > New

To select the Arduino board: Tools > Board > Arduino Uno

To select com port: Tools > Port > click the port that has the Arduino board (could be port 3, 4, etc.)

Copy/Paste the Arduino Code and Compile it.


Arduino Code

int data;  
void setup() {  
    Serial.begin(9600);  
    pinMode(13, OUTPUT);  
}  
void loop() {  
    if (Serial.available()) {  
        data = Serial.read();  
        if (data == 'A') {  
            digitalWrite(13, HIGH);  
        } else {  
            digitalWrite(13, LOW);  
        }  
    }  
} 

Now, upload the program you just created to the Arduino board: Sketch > Upload, or click the right facing arrow button.

 

In the Visual Studio IDE

To create a new project: File > New > select Windows Forms App (.NET Framework)

 

On the Form1.cs [Design], just drag over two buttons and name them ON OFF.

Double-click ON. Return back to form. Double-click OFF. Return back to form. We’ll add code later.

 

Drag over a SerialPort component.

 

Make sure PortName matches the port number of the Arduino board from the Arduino IDE.

 

Now, select Form1.cs (just the code).

Copy/paste the below C# code, overwriting all the code, and save.


C# Code

using System;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            serialPort1.Write("A");
        }
        private void Button2_Click(object sender, EventArgs e)
        {
            serialPort1.Write("B");
        }
    }
}

 

Compile and run

Test Form

If you did everything right, you have successfully programmed an Arduino board and created a simple application to control an LED. Good job!

 

Finished Product

 

< back to projects

 

Notes

 

Video of form working

 

Troubleshooting

Check your connections.

Make sure you’re using the right com port.

Verify your Arduino and C# code are correct.

Make sure your USB cable is working.

 

Other code, in case something doesn’t work

 

Make sure your code matches this:

 

Form1.Designer.cs

namespace WindowsFormsApp2
{
    partial class Form1
    {
        /// 



<summary>
        /// Required designer variable.
        /// 

<summary>


        private System.ComponentModel.IContainer components = null;

        /// 



<summary>
        /// Clean up any resources being used.
        /// 

<summary>


        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.<param>
        protected override void Dispose(bool disposing)
        {
            if (disposing &amp;&amp; (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 



<summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 

<summary>


        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.serialPort1 = new System.IO.Ports.SerialPort(this.components);
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(131, 187);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(182, 72);
            this.button1.TabIndex = 0;
            this.button1.Text = "ON";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.Button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(486, 187);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(171, 72);
            this.button2.TabIndex = 1;
            this.button2.Text = "OFF";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.Button2_Click);
            // 
            // serialPort1
            // 
            this.serialPort1.PortName = "COM4";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.IO.Ports.SerialPort serialPort1;
    }
}

 

 

Resources.Designer.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// <auto-generated>
//------------------------------------------------------------------------------

namespace WindowsFormsApp2.Properties
{


    /// 



<summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// 

<summary>


    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources
    {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources()
        {
        }

        /// 



<summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// 

<summary>


        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager
        {
            get
            {
                if ((resourceMan == null))
                {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApp2.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// 



<summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// 

<summary>


        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture
        {
            get
            {
                return resourceCulture;
            }
            set
            {
                resourceCulture = value;
            }
        }
    }
}

 

 

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    static class Program
    {
        /// 
<summary>
        /// The main entry point for the application.
        /// </summary>

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}