Receive and send data from arduino to c# and vice

2019-08-08 13:09发布

问题:

first of all I started using c# yesterday morning so I apologize for potential numb questions.

So far I wrote the following code. I'm able to send data from c# to arduino which seems to be working fine. Now i would like to receive data from arduino, through serial.print, at the same time and display it in a box (ListBox?). How could add this to the code?

I would be thankful for any input, tips and ideas.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            stop.Enabled = false;
            left.Enabled = false;
            right.Enabled = false;
            up.Enabled = false;
            down.Enabled = false;
            string[] ports = SerialPort.GetPortNames();
            comboBox1.Items.AddRange(ports);

        }
        private void Form1_Load(object sender, EventArgs e)
        {


        }
        private void start_Click(object sender, EventArgs e)
        {


            if (comboBox1.SelectedIndex > -1)
            {
                string port = (string)comboBox1.SelectedItem;
                serialPort2.PortName = port; // "port";
                serialPort2.BaudRate = 9600;
                serialPort2.Open();
                if (serialPort2.IsOpen)
                {
                    start.Enabled = false;
                    stop.Enabled = true;
                    left.Enabled = true;
                    right.Enabled = true;
                    up.Enabled = true;
                    down.Enabled = true;
                }
            }
                else
                {
                    MessageBox.Show("Please connect the Arduino and select a Port");
                }

        }
        private void stop_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.Close();
                start.Enabled = true;
                stop.Enabled = false;
                left.Enabled = false;
                right.Enabled = false;
                up.Enabled = false;
                down.Enabled = false;
            }
        }
        private void up_Click(object sender, EventArgs e)
        {

            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("1");
            }

        }

        private void left_Click(object sender, EventArgs e)
        {

            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("4");
            }

        }

        private void right_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("2");
            }
        }

        private void down_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.WriteLine("3");
            }
        }

回答1:

With SolidSoils4Arduino you can simultaneously read and write serial messages. The Solid.Arduino.IStringProtocol supports asynchronous reading of string messages and the Solid.Arduino.ArduinoSession has a StringReceived event that fires when a message has been received.



回答2:

i did the same like you , but i used a potentiometer the out anologic send to C# and C# read it but i used the protocols for read arduino, your code in arduino It dependsabout what you want read and send ok hehe i hope this help you :D

you have to use this in C# :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Data;

namespace ArduinoValor
 {
internal class Class1
{
    public string port = "";
    static SerialPort currentPort;
    public Boolean connect(int baud, string recognizeText, byte paramone, byte paramtwo, byte paramthree)
    {
        try
        {
            byte[] buffer = new byte[3];
            buffer[0] = Convert.ToByte(paramone);
            buffer[1] = Convert.ToByte(paramtwo);//para los detalles 
            buffer[2] = Convert.ToByte(paramthree); //

            int intReturnASCII = 0;
            char charReturnValue = (Char)intReturnASCII;
            string[] ports = SerialPort.GetPortNames();
            foreach (string newport in ports)
            {
                currentPort = new SerialPort(newport, baud); 
                currentPort.Open();// Abre el serial 
                currentPort.Write(buffer, 0,3); 
                Thread.Sleep(1000); 
                int count = currentPort.BytesToRead; //lee los bytes
                string returnMessage = "";
                while (count > 0)
                {
                    intReturnASCII = currentPort.ReadByte();
                    returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                    count--;
                }
                currentPort.Close();
                port = newport;
                if (returnMessage.Contains(recognizeText))
                {
                    return true;
                }
            }
            return false;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    public string message(byte paramone, byte paramtwo, byte paramthree)
    {
        try
        {
            byte[] buffer = new byte[3];
            buffer[0] = Convert.ToByte(paramone);
            buffer[1] = Convert.ToByte(paramtwo);
            buffer[2] = Convert.ToByte(paramthree);

            currentPort.Open();
            currentPort.Write(buffer, 0, 3);
            int intReturnASCII = 0;
            char charReturnValue = (char)intReturnASCII;
            Thread.Sleep(1000); 
            int count = currentPort.BytesToRead;
            string returnMessage = "";
            while (count > 0)
            {
                intReturnASCII = currentPort.ReadByte();
                returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                count--;
            }
            currentPort.Close();
            return returnMessage;
        }
        catch (Exception e)
        {
            return "Error";
        }
    }
}

}



回答3:

If you are looking for a lightweight solution, you can have a look on Sharer : https://github.com/Rufus31415/Sharer

#include <Sharer.h>

// A simple function that sums an integer and a byte and return an integer
int Sum(int a, byte b) {
    return a + b;
}

// A simple function that return a^2
float Square(float a) {
    return a * a;
}

// Init Sharer and declare your function to share
void setup() {
    Sharer.init(115200); // Init Serial communication with 115200 bauds

    // Expose this function to Sharer : int Sum(int a, byte b) 
    Sharer_ShareFunction(int, Sum, int, a, byte, b);

    // Expose this function to Sharer : float Square(float a)
    Sharer_ShareFunction(float, Square, float, a);
}

// Run Sharer engine in the main Loop
void loop() {
    Sharer.run();
}

In your C# application :

// Connect to Arduino board
var connection = new SharerConnection("COM3", 115200);
connection.Connect();

// Scan all functions shared
connection.RefreshFunctions();

// remote call function on Arduino and wait for the result
var result = connection.Call("Sum", 10, 12);

// Display the result
Console.WriteLine("Status : " + result.Status);
Console.WriteLine("Type : " + result.Type);
Console.WriteLine("Value : " + result.Value);

// Status : OK
// Type : int
// Value : 22