2017-01-30 3 views
0

DataReceived 및 처리기 이벤트를 사용하여 mk에서 데이터를 수신하려고 시도 할 때 - 프로그램의 버튼을 누른 다음 mk의 LED가 켜지고, 데이터는 프로그램에 보내 져야합니다 (1, 바이트 값을 기대했지만 문자열 값을 시도해도 작동하지 않음). 송신 측이 작동하지만 수신 중 .... 아니 은 내가 누락 된 것 같습니다. 어떤 도움이라도 감사합니다. Thx in MoreC#, 마이크로 컨트롤러에서 데이터를 수신해야합니다

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.IO.Ports; 

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


     } 
     private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) // As i understood, here we configure where i data will be shown, 
                         // trying to get it on TextBox1 
     { 

      SerialPort sp = (SerialPort)sender; 
      richTextBox1.Text += sp.ReadExisting() + "\n"; 
     } 

     private void button1_Click(object sender, EventArgs e)          // There are a main actions, first i receive data then send data by a click.  
     { 
      serialPort1.Write("\u0001"); 
      serialPort1.Close(); 

      System.ComponentModel.IContainer components = new System.ComponentModel.Container(); // 
      serialPort1 = new System.IO.Ports.SerialPort(components); 
      serialPort1.PortName = "COM4"; 
      serialPort1.BaudRate = 9600; 
      serialPort1.DtrEnable = true; 
      serialPort1.Open(); 
      serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); 


     } 
    } 
} 
+0

작성하기 전에 청취자를 연결해야합니다. 핀이 켜져있는 것처럼 보이지만 정보를 수신하기 위해 수신 대기중인 것은 없습니다. 시간이 지나면 포트 노팅을 듣기 시작합니다. –

+0

직렬 포트 에뮬레이터를 사용하여 문제를 디버그하여 진행 상황을 정확히 파악하고 들어오는 통신이 있는지 확인하는 것이 좋습니다. – FeliceM

+0

Thx 당신을 위해 당신이 의견을 말하지만, 내 장치가 작동하고 데이터를 보낼 수 있고, 또한 콘솔 (C#도 사용)과 데이터를 수신 확인하고, 내가 mk에서 보내는 데이터를 받았습니다. 따라서 위의 코드에서 문제가 발생했습니다. 올바른 내 코드에 도움이 친절하게 그것을 apreciate, –

답변

0

직렬 포트가 UI와 다른 스레드에 있습니다. 따라서 UI를 호출하지 않았으므로 문자를받을 때 예외가 발생하고 UI가 업데이트되지 않습니다. DataReceivedHandler에서 UI를 먼저 호출하십시오. 다음과 같이 할 수 있습니다.

public static class ControlExt 
{ 
    public static void InvokeChecked(this Control control, Action method) 
    { 
     try 
     { 
      if (control.InvokeRequired) 
      { 
       control.Invoke(method); 
      } 
      else 
      { 
       method(); 
      } 
     } 
     catch { } 
    } 
} 


public partial class Form1 : Form 
{ 
    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) 
    { 
     this.InvokeChecked(delegate 
     { 
      richTextBox1.Text += serialPort1.ReadExisting() + "\n"; 

      richTextBox1.SelectionStart = Text.Length; 
      richTextBox1.ScrollToCaret(); 
     }); 
    } 
} 
관련 문제