C# Serial Port Communication Arduino

About: Green hand in arduino

If you have problems on Serial communication with Arduino in C#, this post is perfect for you!!!

These days, I'm learning serial port communication and want to write a simple demo on my LattePanda. LattePanda is a Win10 single board computer, it integrated Arduino Compatible Processor, so I can run this demo just on one LattePanda board! This post is mainly about serial communication from the Arduino to the PC and communicate from PC to Arduino in C#.

If you don't have a LattePanda, you can connect the Arduino to your PC instead! Hope this tutorial useful for you.

Feel free to ask me if you have any problems while running this demo!

Step 1: What You Need:

Step 2: 1.Communicate From the Arduino to the LattePanda CPU

Function:

  1. Arduino:Send '1'
  2. Computer: Receive '1'

(You can try to send the data of your sensor or any other parameter if you want.)

Creat a new Console application. Use Console to recieve the data.

I found an easiest way to do this.

C# code:

using System;
using System.IO.Ports;
using System.Threading; namespace ConsoleApp1 { class Program { static SerialPort _serialPort; public static void Main() { _serialPort = new SerialPort(); _serialPort.PortName = "COM4";//Set your board COM _serialPort.BaudRate = 9600; _serialPort.Open(); while (true) { string a = _serialPort.ReadExisting(); Console.WriteLine(a); Thread.Sleep(200); } } } }

Arduino sketch:

void setup() {
Serial.begin(9600);
}

void loop() { Serial.print('1'); delay(200); }

Press Start, and you will see the result like the picture above. We received the data from Arduino successfully.

Success? If you have any questions, feel free to ask me!

Step 3: 2. Communicate From the LattePanda CPU to the Arduino

Function:

  • Computer: Send '1' or '0'
  • Arduino: Receive '1' and turn on the light. Receive '0' and turn off the light.

Creat a new Windows Form Application and make two buttons. See the picture above.

C# Code:(Winforms)

using System;
using System.Windows.Forms;
using System.IO.Ports; namespace lightcontrol { public partial class Form1 : Form { SerialPort port; public Form1() { InitializeComponent(); this.FormClosed += new FormClosedEventHandler(Form1_FormClosed); if (port==null) { port = new SerialPort("COM7", 9600);//Set your board COM 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) { port.Write(message); } } }

Arduino sketch:

const int LedPin = 13;
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); }

If you click the button 'ON', you will see the light(pin13) turns on.

So far so good? Feel free to post your qusetions, I will try my best to help you!

There's another way to do this, you can see the tutorial here.

Step 4: Summary

These are the simplest way to communicate between arduino and your PC.

Most of the projects need Arduino to send data to computer and use computer to analize data or do other thing. So communicate is necessary and very important. Hope it's helpful for you. If you have any questions please let me know.

Share

    Recommendations

    • Remix Contest

      Remix Contest
    • Weaving Challenge

      Weaving Challenge
    • Epilog X Contest

      Epilog X Contest

    6 Discussions

    1
    None
    AnthonyC94

    4 days ago

    I'm sending data in from the Serial port from the Arduino. Let's say it's "1234567891234" string which I store in a form field. Now when I go to do a search in my database for this number, the database comes up blank. But if I physically copy and paste this number into the exact same form field, the database shows the entry. How is it when the number comes from the Arduino through the serial input as ASCII, it can't be read in my search string but if I copy it from the exact same form field and paste it right back in the same form field it came from, it works? I can't figure this one out. I've debugged the code and it shows the data is correct. It's perfect with no "\r\n" after the string. Just in case I wrote a trimEnd and removed any possible hidden characters. Anyone have an idea of what's happening? Here's the Serial Input code and Arduino Code.
    Serial IN C#
    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
    dataIN = serialPort1.ReadExisting();
    this.Invoke(new EventHandler(ShowData));
    }
    private void ShowData(object sender, EventArgs e)
    {
    int dataINLength = dataIN.Length;
    lblDataInLength.Text = string.Format("{0:00}", dataINLength);
    if (chBoxAlwaysUpdate.Checked)
    {
    uPCTextBox.Text = "";
    uPCTextBox.Text = dataIN;
    var text = uPCTextBox.Text;
    Clipboard.SetText(text);
    lblDataIn.Text = Clipboard.GetText();
    uPCTextBox.Text = lblDataIn.Text;
    }
    else if (chBoxAdd2Data.Checked)
    {
    uPCTextBox.Text = "";
    uPCTextBox.Text += dataIN;
    var text = uPCTextBox.Text;
    Clipboard.SetText(text);
    lblDataIn.Text = Clipboard.GetText();
    uPCTextBox.Text = lblDataIn.Text;
    }
    }
    Arduino Code:
    int nbts = 3;
    int startpin = 10;
    int bts[3];
    boolean btgs[3];
    int incomingByte = 0;
    //End Button Declarations
    void setup() {
    Serial.begin(9600);
    for(int i=0;i<nbts; i++) bts[i] = i+startpin;
    for(int i=0;i<nbts; i++) btgs[i] = false;
    for(int i=0;i<nbts; i++) pinMode(bts[i], INPUT_PULLUP);
    delay(500);
    Serial.println("Ready for Input when you are!");
    }
    void loop() {
    readBtn();
    }
    void readBtn(){
    for(int i=0;i<nbts;i++){
    if(digitalRead(bts[i])==LOW){
    if(!btgs[i]){
    btgs[i] = true;
    if(bts[i]== 12){
    Serial.println("");
    delay(250);
    }
    else if(bts[i]== 11){
    btgs[i] = false;
    Serial.println("629874846497");
    delay(250);
    }
    else if(bts[i]== 10){
    Serial.println("1234567891234");
    btgs[i] = false;
    delay(250);
    }
    }
    }
    }
    }

    Data Search Code:
    private void btnSearchUPC_Click(object sender, EventArgs e)
    {
    try
    {
    this.inventoryTableAdapter.SearchUPC2(this.inventoryDataSet1.Inventory, uPCTextBox.Text);
    }
    catch (System.Exception ex)
    {
    System.Windows.Forms.MessageBox.Show(ex.Message);
    }

    C# Search Code:
    this.Adapter.SelectCommand = this.CommandCollection[4];
    if ((UPC == null)) {
    this.Adapter.SelectCommand.Parameters[0].Value = global::System.DBNull.Value;
    }
    else {
    this.Adapter.SelectCommand.Parameters[0].Value = ((string)(UPC));
    }
    if ((this.ClearBeforeFill == true)) {
    dataTable.Clear();
    }
    int returnValue = this.Adapter.Fill(dataTable);
    return returnValue;
    }

    And SQL Search Query Code:

    SELECT ID, UPC, ITEM, MODEL, BRAND, DESCRIPTION, VENDOR, VENDOR_CONTACT, VENDOR_PHONE, VENDOR_ADDRESS, VENDOR_EMAIL, DATE_ORDERED,
    DATE_RECEIVED, QUANTITY, COMMENTS, ADMIN
    FROM Inventory
    WHERE (UPC LIKE @UPC + N'%') //Search String

    0
    None
    AndersM10

    Question 9 months ago

    Great tutorial but this only works if you know the serial port and the application will crash the arduino is not connected.

    How would you scan all the open serial ports, send out pings for the arduno, listen for a response and show connected/not connected? Would be great if you did this tutorial.

    2 answers
    0
    None
    hackmattrAndersM10

    Answer 15 days ago

    I know that this comment is late, but I went through some code I wrote a few years ago to find the solution I had to part of this question. The first picture shows part of my form. I populate the drop down list when the form is created using the function in the second picture. It will scan every COM port available and store the names in a string array. It will add the items to the drop down menu and then I use a try catch block to set the first COM port as default if it is available.

    So the user selects the COM port for the arduino and then clicks on connect to connect to that COM port. The third photo shows my connect function.

    Now it won't select the COM port for the arduino automatically unless its the first in the list, but it is an option to prevent problems of connecting to a nonexistent port when the arduino is unplugged..

    Capture1.PNGCapture2.PNGCapture3.PNG
    0
    None
    RicardoG177

    7 months ago

    Nice Tutorial. For me (noob and learning) would be nice the Arduino Schematic; but no big deal. There are tons of schematics to follow up.
    The part I Loved Most was in fact the way you Code SerialPort (Programmatically). I've been struggling to make it work. Thankful for that. (New Skill Achieved here!)

    Either way: I know my question has nothing to do with this; but since I'm having difficulties in finding a "noob tutorial for me"; perhaps you could help me out.
    In my project the intention was to read and write to Arduino.

    i.e: Read Specific Pins Data and Turn them Pin ON/OFF

    Is it possible to send Text from C# App and Receive it in Arduino?
    // See Pseudo Code Image Attached

    Keep up the good job.
    Thanks in advance.



    PseudoCodeExample.png
    0
    None
    AndersM10

    9 months ago

    Great tutorial, this was very useful, defensively going to use this allot.