串口写入和读取事件不订阅/不读取串口

时间:2014-09-08 01:50:32

标签: c# serial-port cctalk

我一直在尝试使用已使用此代码配置的串口COM4发送和读取命令,它已连接到纸币接收器设备

即时设备发送答案时我会使用一个事件来控制,但是当我发现它发现它从未实际到达事件或订阅它时,我一直在阅读整个星期如何解决这个问题,没有运气,

即使我碰巧把#34;读端口" "写入端口线"之后的行并且程序进入

 ptSerial.Read(RxMensaje, 0, 5);

排除程序只是频繁,我必须阻止它希望有人在这里可以帮助我oput

public partial class Form1 : Form
{
  public SerialDataReceivedEventHandler DataReceivedDelegate;


    public Form1()
    {
        InitializeComponent();
    }

    private  void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        DataReceivedDelegate = new SerialDataReceivedEventHandler(DataReceivedHandler);
        //SerialPort sp = (SerialPort)sender;
        //string indata = sp.ReadExisting();

        byte[] RxMensaje = new byte[5];
        ptSerial.Read(RxMensaje, 0, 5);
        rtbDevice.Text = Encoding.ASCII.GetString(RxMensaje, 0, 5);

      //  rtbDevice.Text = indata;
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        try
        {
            Open(sender, e);
        }
        catch (Exception ex)
        {
            lblSalida.Text = ex.Message;
        }
    }

    private void Open(object sender, EventArgs e)
    {
        ptSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        ptSerial.Open();
        lblSalida.Text = "Puerto COM4 Abierto";
    }

   private void btnSend_Click(object sender, EventArgs e)
    {
        if (ptSerial.IsOpen)
        {
            byte[] TxMensaje = new byte[5] { 0x02, 0x00, 0x01, 0xFE, 0xFF }; //CCtalk  
            ptSerial.Write(TxMensaje, 0, 5);

            rtbHost.Text = "2 0 1 254 255 Enviado";

            //byte[] RxMensaje = new byte[5];
            //ptSerial.Read(RxMensaje, 0, 5);
            //rtbDevice.Text = Encoding.ASCII.GetString(RxMensaje, 0, 5);


            ptSerial.Close();
            lblSalida.Text = "Bytes Enviados Pto Cerrado";
        }
        else
        {
            lblSalida.Text = "Puerto Cerrado";
        }
    }

    private void btnCerrar_Click(object sender, EventArgs e)
    {
        if (ptSerial.IsOpen)
        {
            ptSerial.Close();
            lblSalida.Text = "Puerto COM4 Cerrado";
        }
        else
        {
            lblSalida.Text = "No ocurrio nada :(";
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我没有看到串口的完整定义(例如,你在哪里绑定到" COM4")。非常重要的是波特率设置正确,否则设备无法与您的应用程序正确同步,也不会产生任何事件。

请参阅http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx

_serialPort = new SerialPort(); // Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);