【问题标题】:Receive and send data from arduino to c# and vice versa从 arduino 接收和发送数据到 c#,反之亦然
【发布时间】:2014-09-24 01:51:28
【问题描述】:

首先我昨天早上开始使用 c#,所以我为潜在的麻木问题道歉。

到目前为止,我编写了以下代码。我能够将数据从 c# 发送到 arduino,这似乎工作正常。现在我想同时通过serial.print从arduino接收数据并将其显示在一个框(ListBox?)中。怎么能把它添加到代码中?

感谢您提供任何意见、提示和想法。

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");
            }
        }

【问题讨论】:

  • “同时”是什么意思?您是希望收到每次按钮点击的响应,还是希望无论活动如何都持续接收和显示数据?
  • 是的,不管我是否向 arduino 发送数据,都会持续接收和显示数据
  • 您需要使用单独的线程来处理从 Arduino 接收数据。有很多使用BackgroundWorker 在应用程序 UI 线程继续进行时处理工作的示例。

标签: c# arduino serial-communication


【解决方案1】:

使用SolidSoils4Arduino,您可以同时读取和写入串行消息。 Solid.Arduino.IStringProtocol 支持异步读取字符串消息,Solid.Arduino.ArduinoSession 有一个StringReceived 事件,在收到消息时触发。

【讨论】:

    【解决方案2】:

    如果你正在寻找一个轻量级的解决方案,你可以看看 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();
    }
    

    在您的 C# 应用程序中:

    // 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
    

    【讨论】:

      【解决方案3】:

      我和你一样,但我用的是电位器。
      Pot 模拟输出通过 Serial 发送到 C#;并且 C# 应用程序会读取它。
      唯一的区别是我使用了从 Arduino 读取的协议。
      您的 Arduino 草图代码取决于您尝试发送和/或接收的内容。 我提供我的例子。我希望这会有所帮助。


      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); // For Details
                  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(); // Open Serial Port (Use the Port) 
                      currentPort.Write(buffer, 0,3); 
                      Thread.Sleep(1000); 
                      int count = currentPort.BytesToRead; //Read 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"; }
          }
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-26
        • 1970-01-01
        • 2010-12-30
        • 1970-01-01
        • 1970-01-01
        • 2012-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多