日期:2014-05-18  浏览次数:20948 次

关于VS2005串口检测
我现在要用串口连接一个电台,在同一个串口下通个不同的波特率来判断是否连接到电台,请问这样怎么做

------解决方案--------------------
//最近我也要做有关 串口通信和usb开发 先作个标记
private void button1_Click(object sender, EventArgs e)
{
//实例化串口对象(默认:COMM1,9600,e,8,1)
SerialPort serialPort1 = new SerialPort();
//更改参数
serialPort1.PortName = "COM1 ";
serialPort1.BaudRate = 19200;
serialPort1.Parity = Parity.Odd;
serialPort1.StopBits = StopBits.Two;

//上述步骤可以用在实例化时调用SerialPort类的重载构造函数
//SerialPort serialPort = new SerialPort( "COM1 ", 19200, Parity.Odd, StopBits.Two);

//打开串口(打开串口后不能修改端口名,波特率等参数,修改参数要在串口关闭后修改)
serialPort1.Open();

//发送数据
SendStringData(serialPort1);
//也可用字节的形式发送数据
//SendBytesData(serialPort1);

//开启接收数据线程
ReceiveData(serialPort1);

}



//发送字符串数据
private void SendStringData(SerialPort serialPort)
{
serialPort.Write(txtSend.Text);
}

/// <summary>
/// 开启接收数据线程
/// </summary>
private void ReceiveData(SerialPort serialPort)
{
//同步阻塞接收数据线程
Thread threadReceive=new Thread(new ParameterizedThreadStart(SynReceiveData));
threadReceive.Start(serialPort);

//也可用异步接收数据线程
//Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData));
//threadReceiveSub.Start(serialPort);

}

//发送二进制数据
private void SendBytesData(SerialPort serialPort)
{
byte[] bytesSend=System.Text.Encoding.Default.GetBytes(txtSend.Text );
serialPort.Write(bytesSend, 0, bytesSend.Length);
}

//同步阻塞读取
private void SynReceiveData(object serialPortobj)
{
SerialPort serialPort = (SerialPort)serialPortobj;
System.Threading.Thread.Sleep(0);
serialPort.ReadTimeout = 1000;
try
{
//阻塞到读取数据或超时(这里为2秒)
byte firstByte=Convert.ToByte(serialPort.ReadByte());
int bytesRead=serialPort.BytesToRead ;
byte[] bytesData=new byte[bytesRead+1];
bytesData[0] = firstByte;
for (int i = 1; i <=bytesRead; i++)
bytesData[i] = Convert.ToByte( serialPort.ReadByte());
txtReceive.Text = System.Text.Encoding.Default.GetString(bytesData);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
//处理超时错误
}

serialPort.Close();

}

//异步读取
private void AsyReceiveData(object serialPortobj)
{
SerialPort serialPort = (SerialPort)serialPortobj;
System.Threading.Thread.Sleep(500);
try
{
txtReceive.Text = serialPort.ReadExisting();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
//处理错误