当前位置:编程学习 > C#/ASP.NET >>

请问前辈SerialPort类或者控件怎么使用的?

我做一个程序通过串口发送和接收数据(字符串即可)发送的代码如下:
            serialPort1.Open();

            string sPortName = textBox5.Text;
            int nBaudRates = Convert.ToInt32(textBox6.Text);
            int nDataBits = Convert.ToInt32(textBox7.Text);
            Parity pParity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
            StopBits sStopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox4.SelectedItem.ToString());

            string sTxt = textBox8.Text;

            serialPort1.PortName = sPortName;
            serialPort1.BaudRate = nBaudRates;
            serialPort1.DataBits = nDataBits;
            serialPort1.Parity = pParity;
            serialPort1.StopBits = sStopBits;

            serialPort1.WriteLine(sTxt);
            serialPort1.Close();

接收的代码如下:
        string sPortName = textBox5.Text;
            int nBaudRates = Convert.ToInt32(textBox6.Text);
            int nDataBits = Convert.ToInt32(textBox7.Text);
            Parity pParity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
            StopBits sStopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox4.SelectedItem.ToString());

            string sTxt = textBox8.Text;

            serialPort1.PortName = sPortName;
            serialPort1.BaudRate = nBaudRates;
            serialPort1.DataBits = nDataBits;
            serialPort1.Parity = pParity;
            serialPort1.StopBits = sStopBits;

            serialPort1.Open();
            MessageBox.Show(serialPort1.ReadLine());
            serialPort1.Close();
但都没能正确接收和发送,只是为什么呢? --------------------编程问答-------------------- 第一个只写了还没有发送的指令,第二个只读了没有读出的指令~
--------------------编程问答-------------------- 那怎么发送和读出呢? --------------------编程问答-------------------- private SerialPort  m_SerialPort    = null;        
private string      m_strPortName   = "Com1";
        private StopBits    m_StopBits      = StopBits.Two;
        private Parity      m_Parity        = Parity.Even;
        private int         m_iDataBits     = 8;
        private int         m_iBaudRate     = 57600;
        private int m_iCurrentRecieveByteCount = 0;

--打开端口
 public bool OpenCOM()
        {
            bool bResult = true;
            try
            {
                if (m_SerialPort == null)
                {
                    m_SerialPort    = new SerialPort();
                    
                        m_SerialPort.DataReceived += new SerialDataReceivedEventHandler(CpmPort_DataReceivedHandler);
                    }
                    else
                    {
                        m_SerialPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceivedHandler);
                    }

                }

                if (m_SerialPort.IsOpen)
                {
                    m_SerialPort.Close();
                    m_SendQueue.Clear();
                }

                m_SerialPort.PortName   = m_strPortName;
                m_SerialPort.BaudRate   = m_iBaudRate;
                m_SerialPort.DataBits   = m_iDataBits;
                m_SerialPort.StopBits   = m_StopBits;
                m_SerialPort.Parity     = m_Parity;

                m_SerialPort.Open();
            }
            catch (Exception ex)
            {
                // Throw open comport failed message
            }
           
            return bResult;
        }

--关闭端口
/// <summary>
        /// close com port
        /// </summary>
        /// <returns></returns>
        public bool CloseCOM()
        {
            bool bResult = true;
            try
            {
                if (m_SerialPort.IsOpen)
                {
                    m_SerialPort.Close();
                    m_SerialPort = null;
                }
            }
            catch (Exception)
            {
                bResult = false;
            }
            return bResult;
        }


---发送数据用
  private void SendToCom(byte[] rabyteSentData)
        {
 int iSize = rabyteSentData.Length;
 m_SerialPort.Write(rabyteSentData, 0, iSize);
}

--接受com数据
   /// <summary>
        /// Received data event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComPort_DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {

          //Setting timeout
            m_SerialPort.ReadTimeout = 100;

            // Obtain the number of bytes waiting in the port's buffer
            int bytes = m_SerialPort.BytesToRead;

            // Create a byte array buffer to hold the incoming data
            byte[] buffer = new byte[bytes];

            // Read the data from the port and store it in our buffer
            m_SerialPort.Read(buffer, 0, bytes);
          

        } --------------------编程问答-------------------- 原来问题点数: 2,早知道就不回了,呵呵 --------------------编程问答-------------------- 打开端口段中
m_SerialPort.DataReceived += new SerialDataReceivedEventHandler(CpmPort_DataReceivedHandler);
}
else
{
m_SerialPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceivedHandler);
}

}

这里copy错了

如下:
m_SerialPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceivedHandler);
--------------------编程问答-------------------- 学习 --------------------编程问答-------------------- studying --------------------编程问答-------------------- 发送代码中,应该先设置端口/波特率/校验等 再 open. --------------------编程问答--------------------                         //serialPort1.Open(); 

                        string   sPortName   =   textBox5.Text; 
                        int   nBaudRates   =   Convert.ToInt32(textBox6.Text); 
                        int   nDataBits   =   Convert.ToInt32(textBox7.Text); 
                        Parity   pParity   =   (Parity)Enum.Parse(typeof(Parity),   comboBox3.SelectedItem.ToString()); 
                        StopBits   sStopBits   =   (StopBits)Enum.Parse(typeof(StopBits),   comboBox4.SelectedItem.ToString()); 

                        string   sTxt   =   textBox8.Text; 

                        serialPort1.PortName   =   sPortName; 
                        serialPort1.BaudRate   =   nBaudRates; 
                        serialPort1.DataBits   =   nDataBits; 
                        serialPort1.Parity   =   pParity; 
                        serialPort1.StopBits   =   sStopBits; 

                        serialPort1.Open(); 

                        serialPort1.WriteLine(sTxt); 
                        serialPort1.Close();  --------------------编程问答-------------------- 我是在VS2005上用C#写的,代码如下:
 try
                {
                    serialPort1.Parity = System.IO.Ports.Parity.None;
                    serialPort1.StopBits = System.IO.Ports.StopBits.One;
                    serialPort1.BaudRate = 9600;
                    serialPort1 .DataBits =8;
                    serialPort1.PortName = "COM2";
                    serialPort1.ReadBufferSize = 1024;
                    serialPort1.WriteBufferSize = 1024;
                    serialPort1.WriteTimeout = 200;
                    serialPort1.Open();
                    serialPort1.ReadExisting();//设置Input从接收缓冲读取全部数据
                    serialPort1.ReceivedBytesThreshold = 1;//设置引发OnComm事件的字节长度
                    serialPort1.DiscardInBuffer();//清除接收缓冲区
                    serialPort1.DiscardOutBuffer(); //清除发送缓冲区
                }
                catch (System .Exception ex)
                {
                    labState.Text = "请重新配置串口!请检查"+ex.Message;
                }

但在打开的串口的时候报错?在模拟器PPC2003,WM5/6都可以打开并正常收发? --------------------编程问答-------------------- 有来电显示的 源码吗 --------------------编程问答-------------------- --------------------编程问答-------------------- 发送前先设置参数,再open.
接收:控件的话在接收事件中处理
若是类对象的话,用timer或线程读该对象的接收缓冲区
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,