SerialPort.BaseStream.BeginWrite &开始阅读问题

发布于 2024-09-17 05:55:30 字数 3448 浏览 2 评论 0原文

我在尝试找出串行端口对象上的异步通信时遇到一些问题,希望得到一些帮助。我还在学习异步的东西所以要温柔:) 

 

我基本上需要确保在写入串行端口之前缓冲区未满,并且在写入更多数据之前已读取所有数据以避免数据包冲突。不幸的是,我正在写入的微控制器没有任何握手或 CTSEnabled,因此我必须在代码中模仿它。

 

 

public partial class Form2 : Form
{
    System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
    System.Timers.Timer tmrPolling = new System.Timers.Timer(200);
    static byte [] inputPacket = new byte[2] { (byte)255, (byte)0 }; // Byte to send to SerialPort when input polling timer is activated.

    AsyncCallback callback;
    IAsyncResult result;

    Form2()
    {
        InitializeComponent();
        port.PortName = "COM9";
        port.BaudRate = 38400;
        port.DataBits = 8;
        port.StopBits = System.IO.Ports.StopBits.One;
        port.Parity = System.IO.Ports.Parity.None;
        port.ReadTimeout = 1;
        port.ReceivedBytesThreshold = 5;
        port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
        callback = new AsyncCallback(ReadComplete);  
        port.ReadBufferSize = (byte)60;
        port.WriteBufferSize = (byte)60;
        port.Open();  
        tmrPolling.Elapsed += new System.Timers.ElapsedEventHandler(tmrPolling_Elapsed);
    }

    void WritePacket(byte[] packet)
    {
        result = port.BaseStream.BeginWrite(packet, 0, packet.Count(), callback, port); // writes the input packet to the SerialPort - needed to read the IO values
    }

    void ReadComplete(IAsyncResult result)
    {

    }


    void tmrPolling_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  
        WritePacket(inputPacket); // writes the input packet to the SerialPort - needed to read the IO values
    }

    void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        port.BaseStream.EndWrite(result);
        // Reads the data coming in from the serial port and calls the thread safe delegate to update the values on the form.
        byte [] received = new byte[port.BytesToRead];
        result = port.BaseStream.BeginRead(received, 0, received.Count(), callback, port);
        port.BaseStream.EndRead(result);  
    }

    private void UpdateValues()
    {
        byte[] b = new byte[] { (byte)255, (byte)6, (byte)hsbPan.Value, (byte)vsbTilt.Value, (byte)0,  
        (byte)0, (byte)0, (byte)0, (byte)13, (byte)10 };
        WritePacket(b);
    }

    private void chkEnablePolling_CheckedChanged(object sender, EventArgs e)
    {  
        tmrPolling.Enabled = chkEnablePolling.Checked;
        test.Enabled = chkEnablePolling.Checked;
        vsbInputInterval.Enabled = chkEnablePolling.Checked;
        vsbInputInterval.Value = Convert.ToInt32(tmrPolling.Interval);
        txtInputInterval.Enabled = chkEnablePolling.Checked;
        txtInputInterval.Text = ((float)tmrPolling.Interval / ( float)1000).ToString() + " sec";
    }

    private void vsbInputInterval_Scroll(object sender, ScrollEventArgs e)
    {
        // adjusts the tick frequency of the Timer for input polling. 
        txtInputInterval.Text = ((float)tmrPolling.Interval / (float)1000).ToString() + " sec";
        tmrPolling.Interval = vsbInputInterval.Value;
    } 

    private void vsbTilt_Scroll(object sender, ScrollEventArgs e)
    {  
        UpdateValues();
    }

    private void hsbPan_Scroll(object sender, ScrollEventArgs e)
    {
        UpdateValues();
    }
}

I'm having some issues trying to figure out Async communication on a serialport object and was hoping to get some help. I'm still learning Async stuff so be gentle:) 

 

I basically need to make sure that the buffer isn't full prior to writing to the serial port and also all data has been read before any more data gets written to avoid packet collision. Unfortunately the microcontroller that I am writing to does not have any handshaking or CTSEnabled so I have to mimic it in code. 

 

 

public partial class Form2 : Form
{
    System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
    System.Timers.Timer tmrPolling = new System.Timers.Timer(200);
    static byte [] inputPacket = new byte[2] { (byte)255, (byte)0 }; // Byte to send to SerialPort when input polling timer is activated.

    AsyncCallback callback;
    IAsyncResult result;

    Form2()
    {
        InitializeComponent();
        port.PortName = "COM9";
        port.BaudRate = 38400;
        port.DataBits = 8;
        port.StopBits = System.IO.Ports.StopBits.One;
        port.Parity = System.IO.Ports.Parity.None;
        port.ReadTimeout = 1;
        port.ReceivedBytesThreshold = 5;
        port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
        callback = new AsyncCallback(ReadComplete);  
        port.ReadBufferSize = (byte)60;
        port.WriteBufferSize = (byte)60;
        port.Open();  
        tmrPolling.Elapsed += new System.Timers.ElapsedEventHandler(tmrPolling_Elapsed);
    }

    void WritePacket(byte[] packet)
    {
        result = port.BaseStream.BeginWrite(packet, 0, packet.Count(), callback, port); // writes the input packet to the SerialPort - needed to read the IO values
    }

    void ReadComplete(IAsyncResult result)
    {

    }


    void tmrPolling_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  
        WritePacket(inputPacket); // writes the input packet to the SerialPort - needed to read the IO values
    }

    void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        port.BaseStream.EndWrite(result);
        // Reads the data coming in from the serial port and calls the thread safe delegate to update the values on the form.
        byte [] received = new byte[port.BytesToRead];
        result = port.BaseStream.BeginRead(received, 0, received.Count(), callback, port);
        port.BaseStream.EndRead(result);  
    }

    private void UpdateValues()
    {
        byte[] b = new byte[] { (byte)255, (byte)6, (byte)hsbPan.Value, (byte)vsbTilt.Value, (byte)0,  
        (byte)0, (byte)0, (byte)0, (byte)13, (byte)10 };
        WritePacket(b);
    }

    private void chkEnablePolling_CheckedChanged(object sender, EventArgs e)
    {  
        tmrPolling.Enabled = chkEnablePolling.Checked;
        test.Enabled = chkEnablePolling.Checked;
        vsbInputInterval.Enabled = chkEnablePolling.Checked;
        vsbInputInterval.Value = Convert.ToInt32(tmrPolling.Interval);
        txtInputInterval.Enabled = chkEnablePolling.Checked;
        txtInputInterval.Text = ((float)tmrPolling.Interval / ( float)1000).ToString() + " sec";
    }

    private void vsbInputInterval_Scroll(object sender, ScrollEventArgs e)
    {
        // adjusts the tick frequency of the Timer for input polling. 
        txtInputInterval.Text = ((float)tmrPolling.Interval / (float)1000).ToString() + " sec";
        tmrPolling.Interval = vsbInputInterval.Value;
    } 

    private void vsbTilt_Scroll(object sender, ScrollEventArgs e)
    {  
        UpdateValues();
    }

    private void hsbPan_Scroll(object sender, ScrollEventArgs e)
    {
        UpdateValues();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文