C#串行通信无法接收文本

时间:2018-09-02 00:36:48

标签: c# serial-port serial-communication

我确实知道还有其他有关C#串行通信的线程,但是我确实找不到我的问题的答案。所以我的Arduino仅打印1

Arduino代码:

void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.print('1');
    delay(200);
}

我无法正确接收消息(我得到了正确的波特宽度和其他所有内容),但我什至都没有收到Arduino正在打印的文本,并且led甚至不闪烁以发送文本。但是,如果我连接到 COM端口

C#代码:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            getPorts();
        }

        void getPorts()
        {
            String[] ports = SerialPort.GetPortNames();
            cBPort.Items.AddRange(ports);
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (cBPort.Text == "" || cBPort.Text == "")
                {
                    MessageBox.Show("pls select stuff", "");
                }
                else
                {
                    SerialPort1.PortName = cBPort.Text;
                    SerialPort1.BaudRate = Convert.ToInt32(cbRate.Text);
                    SerialPort1.Open();
                    btnRead.Enabled = true;
                    btnSend.Enabled = true;
                    btnOpen.Enabled = false;
                    btnClose.Enabled = true;
                    txtBSend.Enabled = true;
                }
            }
            catch(UnauthorizedAccessException)
            {
                MessageBox.Show("UnauthorizedAccessException", "idk");
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            SerialPort1.Close();
            btnRead.Enabled = false;
            btnSend.Enabled = false;
            btnOpen.Enabled = true;
            btnClose.Enabled = false;
            txtBSend.Enabled = false;

            timer1.Stop();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            SerialPort1.WriteLine(txtBSend.Text);
            txtBSend.Text = "";
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (SerialPort1.IsOpen)
            {
                string R = SerialPort1.ReadExisting();
                txtBRead.Text = R;
            }
        }
    }
}

0 个答案:

没有答案