C# 读阿杜伊诺

C# 读阿杜伊诺,c#,serial-port,arduino,C#,Serial Port,Arduino,我正在尝试制作一个应用程序来读取Arduino发出的信号,但我无法让它在C#中工作,只能在控制台中工作。我的C#Windows窗体代码是否错误?调试时我没有收到任何错误,但这并不意味着我没有忘记什么 这是我的密码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using

我正在尝试制作一个应用程序来读取Arduino发出的信号,但我无法让它在C#中工作,只能在控制台中工作。我的C#Windows窗体代码是否错误?调试时我没有收到任何错误,但这并不意味着我没有忘记什么

这是我的密码:

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;
using System.Threading;

namespace CommunicateWithArduino
{
    public partial class Form1 : Form
    {
        public static System.IO.Ports.SerialPort port;

        delegate void SetTextCallback(string text);

        private BackgroundWorker hardWorker;

        private Thread readThread = null;


        public Form1()
        {
            InitializeComponent();

            hardWorker = new BackgroundWorker();
            sendBtn.Enabled = false;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            System.ComponentModel.IContainer components =
                new System.ComponentModel.Container();
            port = new System.IO.Ports.SerialPort(components);
            port.PortName = comPort.SelectedItem.ToString();
            port.BaudRate = Int32.Parse(baudRate.SelectedItem.ToString());
            port.DtrEnable = true;
            port.ReadTimeout = 5000;
            port.WriteTimeout = 500;
            port.Open();

            readThread = new Thread(new ThreadStart(this.Read));
            readThread.Start();
            this.hardWorker.RunWorkerAsync();

            btnConnect.Text = "<Connected>";

            btnConnect.Enabled = false;
            comPort.Enabled = false;
            sendBtn.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (string s in SerialPort.GetPortNames())
            {
                comPort.Items.Add(s);
            }
            if (comPort.Items.Count > 0)
                comPort.SelectedIndex = comPort.Items.Count-1;
            else
                comPort.SelectedIndex = 0;

            baudRate.Items.Add("2400");
            baudRate.Items.Add("4800");
            baudRate.Items.Add("9600");
            baudRate.Items.Add("14400");
            baudRate.Items.Add("19200");
            baudRate.Items.Add("28800");
            baudRate.Items.Add("38400");
            baudRate.Items.Add("57600");
            baudRate.Items.Add("115200");

            baudRate.SelectedIndex = 2;
        }

        private void sendBtn_Click(object sender, EventArgs e)
        {
            if (port.IsOpen)
            {
                port.Write(sendText.Text);
            }
        }

        private void SetText(string text)
        {

            if (this.receiveText.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.receiveText.Text += "Text: ";
                this.receiveText.Text += text;
                this.receiveText.Text += Environment.NewLine;
            }
        }

        public void Read()
        {
            while (port.IsOpen)
            {
                try
                {
                    if (port.BytesToRead > 0)
                    {
                        string message = port.ReadLine();
                        this.SetText(message);
                    }
                }
                catch (TimeoutException) { }
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if(!(readThread == null))
                    readThread.Abort();
            }
            catch (NullReferenceException)
            {
            }

            try
            {
                port.Close();
            }
            catch (NullReferenceException)
            {
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Windows.Forms;
使用System.IO.Ports;
使用系统线程;
命名空间与Arduino通信
{
公共部分类Form1:Form
{
公共静态系统.IO.Ports.SerialPort端口;
委托无效SetTextCallback(字符串文本);
私人背景工人;
私有线程readThread=null;
公共表格1()
{
初始化组件();
Hardwarker=新的后台工作人员();
sendBtn.Enabled=false;
}
私有void btnConnect_单击(对象发送者,事件参数e)
{
System.ComponentModel.i容器组件=
新的System.ComponentModel.Container();
端口=新系统.IO.Ports.SerialPort(组件);
port.PortName=comPort.SelectedItem.ToString();
port.BaudRate=Int32.Parse(BaudRate.SelectedItem.ToString());
port.DtrEnable=true;
port.ReadTimeout=5000;
port.WriteTimeout=500;
port.Open();
readThread=newthread(newthreadstart(this.Read));
readThread.Start();
this.hardwarker.RunWorkerAsync();
btnConnect.Text=“”;
btnConnect.Enabled=false;
comPort.Enabled=false;
sendBtn.Enabled=true;
}
私有void Form1\u加载(对象发送方、事件参数e)
{
foreach(SerialPort.GetPortNames()中的字符串s)
{
组成项目。添加;
}
如果(comPort.Items.Count>0)
comPort.SelectedIndex=comPort.Items.Count-1;
其他的
comPort.SelectedIndex=0;
波特率。项目。添加(“2400”);
波特率。项目。添加(“4800”);
波特率。项目。添加(“9600”);
波特率。项目。添加(“14400”);
波特率。项目。添加(“19200”);
波特率。项目。添加(“28800”);
波特率。项目。添加(“38400”);
波特率。项目。添加(“57600”);
波特率。项目。添加(“115200”);
波特率.SelectedIndex=2;
}
私有void sendBtn_单击(对象发送者,事件参数e)
{
if(端口等参线)
{
port.Write(sendText.Text);
}
}
私有void SetText(字符串文本)
{
if(this.receiveText.invokererequired)
{
SetTextCallback d=新的SetTextCallback(SetText);
调用(d,新对象[]{text});
}
其他的
{
this.receiveText.Text+=“Text:”;
this.receiveText.Text+=文本;
this.receiveText.Text+=Environment.NewLine;
}
}
公共无效读取()
{
while(等参端口)
{
尝试
{
如果(port.BytesToRead>0)
{
字符串消息=port.ReadLine();
this.SetText(message);
}
}
捕获(TimeoutException){}
}
}
私有void Form1\u FormClosed(对象发送方,FormClosedEventArgs e)
{
尝试
{
如果(!(readThread==null))
readThread.Abort();
}
捕获(NullReferenceException)
{
}
尝试
{
port.Close();
}
捕获(NullReferenceException)
{
}
}
}
}

默认情况下,ReadLine方法将阻塞,直到收到一行。你的Arduino程序发送了一条线路吗?运行程序时是否关闭了Arduino串行监视器程序


我将更改为port.ReadChar,直到您确认接收到字符。

什么不起作用?你是否收到串行端口上的数据,或者你不能将数据从线程获取到gui?如果你不知道,你可以:1,将串行数据记录到文件中,2,创建一个线程,每隔5秒钟左右调用
SetText
。我无法在c#winform应用程序中获取串行端口上的数据。但是在arduino程序串行监视器中,我可以在我的c#console应用程序上获取数据,这样arduino就没有问题了。但是我无法在我的winform中获取数据,这让我发疯,因为我不认为我发布的winform代码有任何错误。我编写应用程序,以便在文本框中发送数据和接收数据。是的,它发送一行。我正在使用arduino程序员应用程序附带的示例草图“串行调用和响应”。当我运行我的程序时,我不能运行Arduino串行监视器程序。我需要关闭一个来运行另一个。我不明白出了什么问题,因为它在c#consloe和arduino串行监视器中工作,而不是在c#winform中。我发布的代码。你能调试吗。打印你收到的任何字符以验证程序是否正确配置了端口?我刚才看到的串行调用和响应示例没有发送一行代码。它正在发送一个字符“a”(Serial.print('a');)并等待您的响应。杰夫,您的权利!!我更改了Serial.print('A');到Serial.println('A');然后它开始起作用了。