使用C#打开串行端口后获取不正确的数据

时间:2018-07-06 10:21:18

标签: c# arduino

我是第一次使用C#访问arduino。

我正在使用Arduino Uno开发板通过C#代码进行串行通信。但是,当我打开串行端口并等待一段时间以准备好串行端口时,我在串行端口上收到问号(????)。我不知道为什么会这样。

打开端口后,我正在使用“ Threading.Sleep”。如果我将其删除,则可以正常工作。打开端口后如何等待?我想在打开串行端口后再等待一段时间。

谢谢。

Arduino代码:

void setup() 
{
    Serial.begin(115200);
    pinMode(13, OUTPUT);
}

void loop() 
{
    if (Serial.available() > 0)
    {
        String data = Serial.readString();
        Serial.print(data);

        if (data == "Ping")
        {
            Serial.write("OK");
        }

        if (data == "ON") 
        {
            digitalWrite(13, HIGH);
        }
        else
        {
            digitalWrite(13, LOW);
        }
    }           
}

C#代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;

namespace Form1.cs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            comboBox1.Items.Clear();

            foreach (string port in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(port);
                Console.WriteLine("Port Added.");
            }
        }

        private void ConBtn_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = comboBox1.SelectedItem.ToString();


            if (serialPort1.IsOpen == false)
            {
                serialPort1.Open();

                if (serialPort1.BytesToRead > 0)
                {
                    Console.WriteLine("value in buffer");
                    string val = serialPort1.ReadExisting();
                    Console.WriteLine(val);
                }
            }
            Thread.Sleep(1000);

            Console.WriteLine("#####");
            string bufferval3 = serialPort1.ReadExisting();   //Question Mark displaying between this.
            Console.WriteLine(bufferval3);
            Console.WriteLine("#####");

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                Console.WriteLine("Port Closed.");
            }
        }

        private void DisConBtn_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
            Status.Text = "Disconnected";
            Status.ForeColor = Color.DarkRed;
        }

        private void OnBtn_Click(object sender, EventArgs e)
        {
            serialPort1.Write("ON");
        }

        private void OffBtn_Click(object sender, EventArgs e)
        {
            serialPort1.Write("OFF");
        }
    }
}

0 个答案:

没有答案