简体   繁体   English

C# 控制台串口读取丢失数据

[英]C# Console Serial Port Read losing data

I tried to run serial communication using C# from Microsoft Example https://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport?view=dotnet-plat-ext-3.1 .我尝试使用来自 Microsoft Example https: //docs.microsoft.com/en-us/dotnet/api/system.io.plat-ext-serport3 的 C# 运行串行通信。 and I connecting with HC-06 Bluetooth Module which connected with an Arduino Nano Board.我连接了与 Arduino Nano Board 连接的 HC-06 蓝牙模块。

The problem is when running it on my Laptop it seems to lose a lot of data, I'm not sure what causes this problem.问题是在我的笔记本电脑上运行它时似乎丢失了很多数据,我不确定是什么导致了这个问题。 However, when I running it on my Desktop it is seem everything working fine.但是,当我在桌面上运行它时,似乎一切正常。 By Desktop lose only 1 or 2 data in 200 samples per second, while on laptop loss around 50~70 samples.台式机每秒仅丢失 200 个样本中的 1 或 2 个数据,而笔记本电脑每秒丢失约 50~70 个样本。 (I'm sure it does not cause by Arduino Part from my experiment over and over again on Desktop it receiving data around 200 samples per second as mention above). (我确信它不是由 Arduino 引起的,我在桌面上一遍又一遍地进行实验,如上所述,它每秒接收大约 200 个样本的数据)。

Can it cause by my CPU?会不会是我的 CPU 造成的? *Laptop CPU: Core-I7-6700 *Desktop CPU: Core-i7-7700 *笔记本电脑 CPU:Core-I7-6700 *台式机 CPU:Core-i7-7700

(I add some codes to original codes writing a data to text file) Here are C# console codes: (我在将数据写入文本文件的原始代码中添加了一些代码)这里是 C# 控制台代码:

using System;
using System.IO.Ports;
using System.Threading;

public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;
    static String myPath;
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        myPath = Mypath();
        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {
            try
            {
                string time = DateTime.Now.ToString("h:mm:ss.ffffff");
                string message = _serialPort.ReadLine();
                string data = time + "," + message.Trim();
                Console.WriteLine(data);
                WriteFile(Path, data);
            }
            catch (TimeoutException) { }
        }
    }

    public static String Mypath()
    {
        string Path;
        Console.WriteLine("-> Logging Data <-");
        Console.Write("-> Input File Name: ");
        Path = Console.ReadLine();

        if(Path == "")
        {
            Path = DateTime.Now.ToString("h:mm:ss.ffffff");
        }

        return Path + ".txt";
    }

    static void WriteFile(String Path, String Data)
    {
        if (!File.Exists(Path))
        {
            using (StreamWriter sw = File.CreateText(Path))
            {
                sw.WriteLine(Data);
            }
        }
        using (StreamWriter sw = File.AppendText(Path))
        {
            sw.WriteLine(Data);
        }
    }

    // Display Port values and prompt user to enter a port.
    public static string SetPortName(string defaultPortName)
    {
        string portName;

        Console.WriteLine("Available Ports:");
        foreach (string s in SerialPort.GetPortNames())
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter COM port value (Default: {0}): ", defaultPortName);
        portName = Console.ReadLine();

        if (portName == "" || !(portName.ToLower()).StartsWith("com"))
        {
            portName = defaultPortName;
        }
        return portName;
    }
    // Display BaudRate values and prompt user to enter a value.
    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        Console.Write("Baud Rate(default:{0}): ", defaultPortBaudRate);
        baudRate = Console.ReadLine();

        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }

        return int.Parse(baudRate);
    }

    // Display PortParity values and prompt user to enter a value.
    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        Console.WriteLine("Available Parity options:");
        foreach (string s in Enum.GetNames(typeof(Parity)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter Parity value (Default: {0}):", defaultPortParity.ToString(), true);
        parity = Console.ReadLine();

        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }

        return (Parity)Enum.Parse(typeof(Parity), parity, true);
    }
    // Display DataBits values and prompt user to enter a value.
    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        Console.Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits);
        dataBits = Console.ReadLine();

        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }

        return int.Parse(dataBits.ToUpperInvariant());
    }

    // Display StopBits values and prompt user to enter a value.
    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        Console.WriteLine("Available StopBits options:");
        foreach (string s in Enum.GetNames(typeof(StopBits)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter StopBits value (None is not supported and \n" +
         "raises an ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
        stopBits = Console.ReadLine();

        if (stopBits == "" )
        {
            stopBits = defaultPortStopBits.ToString();
        }

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits, true);
    }
    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        Console.WriteLine("Available Handshake options:");
        foreach (string s in Enum.GetNames(typeof(Handshake)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString());
        handshake = Console.ReadLine();

        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }

        return (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
    }
}

and Here is Arduino codes:这是 Arduino 代码:

#include <TimerOne.h>
#include <SoftwareSerial.h>
SoftwareSerial HC06(2, 3);

void setup() {
HC06.begin(115200);
Timer1.initialize(5000); // micro second
Timer1.attachInterrupt(printout);
Timer1.start();
}

void printout()
{
  HC06.println(data());
}

String data()
{
  int d1 = analogRead(A0);
  int d2 = analogRead(A1);
  String d = String(d1) +","+ String(d2);
  return d;  
}

void loop() 
{

}

have you tried to use lower bitrate, lets say 9600?您是否尝试过使用较低的比特率,比如说 9600? It might be, that high speed is not working good with Arduino.可能是,Arduino 不能很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM