【问题标题】:Reading Serial Data from Arduino in Windows Forms Application在 Windows 窗体应用程序中从 Arduino 读取串行数据
【发布时间】:2021-10-25 05:44:04
【问题描述】:

我目前正在尝试构建一个 Windows 窗体应用程序,该应用程序通过串行 com 从 arduino 获取传感器数据。

在 arduino IDE 中检查时,数据会正确写入串行端口。 但我不知道如何通过 c# 读取数据。

class Program
{
    static SerialPort SP;
    static void Main(string[] args)
    {
        SP = new SerialPort();
        SP.PortName = "COM7";
        SP.BaudRate = 9600;
        SP.Handshake = System.IO.Ports.Handshake.RequestToSend;
        SP.Open();

        while (true)
        {
            Console.WriteLine(DateTime.Now.ToString() + " : " + SP.ReadLine());
        }

    }
}

我的猜测是端口设置不正确,但我不知道我错过了什么。

目标只是从 arduino 接收字符串,我不一定需要向 arduino 发送任何数据。

编辑:我正在使用 arduino micro

【问题讨论】:

  • 添加一些当前行为的更多细节,究竟是什么不以哪种方式工作?你收到什么了吗?接受小冲突,.....
  • 我什么也没收到,用于测试 arduino 每 0.5 秒在串口上打印一个新数字 端口上没有读取这些数字,但在打开串口时都按预期显示arduino IDE。

标签: c# .net arduino


【解决方案1】:
  • 您是否关闭了 Arduino IDE?
  • 从端口读取之前需要添加等待码

下面是一个工作示例:

private SerialPort _currentPort = new SerialPort("COM7", 9600);

private readonly  object _sync = new object();

public bool Open()
{ 
   _currentPort.Encoding = Encoding.UTF8;
   _currentPort.DtrEnable = true;
   _currentPort.ReadTimeout = 2000;
    try
    {
        if (!_currentPort.IsOpen)
            lock (_sync)
            {
                if (_currentPort.IsOpen)
                    return true;
                _currentPort.Open();
                System.Threading.Thread.Sleep(1500);
            }
    }
    catch (Exception e)
    {
        //_localLogger?.Error($"{_currentPort.PortName}, {e.Message}", e);
        return false;
    }

    return _currentPort.IsOpen;
}

public bool Subscribe()
{
    try
    { 
    
        if (Open())
        {
            _currentPort.DataReceived += CurrentPortOnDataReceived;
            return true;
        } 
        return false; 
    }
    catch (Exception e)
    {
        //_localLogger?.Error($"{_currentPort.PortName}, {e.Message}", e);
        return false;
    } 
}
private void CurrentPortOnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    if (!_currentPort.IsOpen)
    {
        //_localLogger.Info($"{_currentPort} is closed");
        Open();
    }

    Console.WriteLine(_currentPort.ReadExisting());
}

【讨论】:

  • 您好,首先感谢您的回答。由于我对 C# 相当陌生,因此实际上让您的代码运行时遇到了一些麻烦。我是否将您的解决方案粘贴到 Windows 窗体 App 中的新类中并在启动时创建该类的新实例?还有什么(你知道的)我必须在 arduino 代码中做的吗?目前我正在使用 Serial.println(); 发送串行数据;
  • 此存档包含一个从 Com 端口 bsasearch.org/WinForms.ComPort.Reader.rar 读取数据的工作示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多