保存和编辑串口数据c#

时间:2017-05-15 11:52:26

标签: c# arrays serial-port

对于我们的学校项目,我们必须在c#中编写代码,以便从气象站读取和可视化串行数据。

我现在的代码:

public partial class MainWindow : Window
{
    private SerialPort port;
    DispatcherTimer timer = new DispatcherTimer();
    private string buff;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnPort_Click(object sender, RoutedEventArgs e)
    {
        timer.Tick += timer_Tick;
        timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
        timer.Start();

        try
        {
            port = new SerialPort();                     // Create a new SerialPort object with default settings.
            port.PortName = "COM4";
            port.BaudRate = 115200;                        //  Opent de seriele poort, zet data snelheid op 9600 bps.
            port.StopBits = StopBits.One;                // One Stop bit is used. Stop bits separate each unit of data on an asynchronous serial connection. They are also sent continuously when no data is available for transmission.
            port.Parity = Parity.None;                   // No parity check occurs. 
            port.DataReceived += Port_DataReceived;
            port.Open();                                 // Opens a new serial port connection.
            buff = "";
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

    private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        byte[] buffer = new byte[128];
        int len = port.Read(buffer, 0, buffer.Length); // .Read --> Reads a number of characters from the SerialPort input buffer and writes them into an array of characters at a given offset.

        if (len > 0)
        {
            string str = "";
            for (int i = 0; i < len; i++)
            {
                if (buffer[i] != 0)
                {
                    str = str + ((char)buffer[i]).ToString();
                }
            }
            buff += str;
        }
        // throw new NotImplementedException();
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        try
        {
            if (buff != "")
            {
                textSerial.Text += buff;
                buff = "";
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

此代码具有以下输出:

  • 湿度:33%
  • 温度:25.7℃
  • 可见光:112 lx
  • 红外辐射:1802.5mW / m 2
  • UV指数:0.12
  • CO2:404 ppm CO2
  • 压力:102126 Pa

我必须将所有数字存储在变量中,因为我需要在GUI中使用它们。

从输出中获取所有数字:

public string[] convertNumbers(string inp)
    {
        string pattern = "[+-] ?\\b\\d + (\\.\\d +)?\\b";
        Regex rgx = new Regex(pattern);
        string input = inp;

        string[] result = rgx.Split(input, 3);



        return result;

    }

正则表达式表达正常,并给出了确切的数字。 我想将它们保存到一个包含7个双打的阵列中。 将串行输出转换为变量的最有效方法是什么?

有人可以帮帮我吗?

0 个答案:

没有答案