SerialDataReceivedEventHandler不工作c#

时间:2018-06-09 23:36:11

标签: c#

我试图用Windows窗体中的C#程序连接到arduino。 我可以将数据从c#发送到arduino,但我想从arduino获取数据到C#程序。

我已经尝试过SerialDataReceivedEventHandler,但是在构建表单后我没有得到数据......

我该怎么办?

       public Form1()
    {
        InitializeComponent();
        Init();

    }//end form 1

    private void Init()
    {
        try
        {
            arduinoPort = new SerialPort();
            arduinoPort.BaudRate = 9600;
            arduinoPort.PortName = "COM4";
            arduinoPort.Handshake = Handshake.None;
            arduinoPort.RtsEnable = true;//request to send true
            arduinoPort.DtrEnable = true;//arduino can send messages to the c# program
            arduinoPort.DataReceived += new SerialDataReceivedEventHandler(GetFromArduino);               
            arduinoPort.Open();
        }//end try

        catch (Exception ex) { MessageBox.Show(ex.Message); }

    }//end init


    private void GetFromArduino(object sender, SerialDataReceivedEventArgs e)
    {
        //string arduinoInputString = arduinoPort.ReadLine();
        //Invoke(new Action(() => label1.Text = arduinoInputString));
        MessageBox.Show("does it work?");
    }//end get from arduino

3 个答案:

答案 0 :(得分:1)

MessageBox.Show无法从DataReceived活动

开始工作

SerialPort.DataReceived Event

  

当数据出现时,在辅助线程上引发DataReceived事件   从SerialPort对象接收。因为这个事件是在一个   辅助线程,而不是主线程,试图修改一些   主线程中的元素,如UI元素,可以引发一个   线程异常。如果有必要修改main中的元素   表单或控件,使用Invoke发回更改请求,这样做   关于正确线程的工作

充其量你需要做这样的事情

this.Invoke(new Action(() => { MessageBox.Show(this, "text"); }));

但是,如果您真的想知道该事件是否被触发,那么请使用断点

Using Breakpoints

最后,如果事件未被触发,则您必须查阅设备的文档,以获取设备和串行端口的相应配置。

答案 1 :(得分:0)

制作一些处理程序方法,例如

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
             SerialPort comm = (SerialPort)sender;
             string incoming_Data = comm.ReadExisting();
             this.BeginInvoke((MethodInvoker)delegate()
             {
                Console.WriteLine(incoming_Data + "\n");
             });          
        }

然后,将此方法发送给 DataRecieved 事件的订阅者

arduinoPort.DataReceived += DataReceivedHandler;

来源:https://social.msdn.microsoft.com/Forums/vstudio/en-US/bd8f7ac8-67d5-4eb5-b679-c595f9c7536d/how-to-print-out-text-from-serialport-datareceived-event?forum=netfxbcl

答案 2 :(得分:0)

I don't know if it matters, but this what i did and it solved:
1. in the setup function of the arduino program i had a loop that ran on all the pins, now i specified it to the pins i really use.
2. i don't open the port in the form.cs, but in the program.cs and run a while loop that just check if the port is open. then, it gets the data without disturbing the form to run... 

**in the Program.cs:**


  public static SerialPort arduinoPort { get; set; }
    public static string arduinoInputString { get; set; }
    [STAThread]

    static void Main()
    {
        arduinoPort = new SerialPort();
        try
        {
            arduinoPort = new SerialPort();
            arduinoPort.BaudRate = 250000;
            arduinoPort.PortName = "COM4";
            //arduinoPort.Handshake = Handshake.None;
            //arduinoPort.RtsEnable = true;//request to send true
            //arduinoPort.DtrEnable = true;//arduino can send messages to the c# program
            ////arduinoPort.DataReceived += new SerialDataReceivedEventHandler(GetFromArduino);
            arduinoPort.DataReceived += DataReceivedHandler;
            arduinoPort.Open();
        }//end try
        catch (Exception ex) { Console.WriteLine((ex.Message)); }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

        while (arduinoPort.IsOpen)//read data if the port is open
        {

        }



    }//end main

    static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort comm = (SerialPort)sender;
        arduinoInputString = comm.ReadExisting();
        Form1.label1.Text = arduinoInputString;//label to show the input string from arduino
    }//end get data from arduino