C# serialPort的DataReceived事件無法觸發 ,用的霍尼韋爾的掃碼槍並且裝了相應的USB轉串口驅動。


昨天想試試霍尼韋爾的掃碼槍,掃碼槍有兩種模式,鍵盤模式和串口模式,

1、鍵盤模式直接插上就行了,就像一個鍵盤一樣不需要任何驅動,掃出來的數據直接落到PC的輸入焦點上。就像一個鍵盤一樣,只能輸入字符。

2、而串口模式,則是安裝驅動以后,能夠虛擬成一個COM口,

如果我們用掃碼槍給應用程序輸入數據的時候肯定是不行的,因為程序需要能夠在后台運行的時候也能用掃碼槍作為數據輸入的。這就需要用串口模式了。

今天我寫程序的時候,問題是怎么也不能觸發,DataReceived事件,最后發現問題所在,幾個要點

1、串口必須New新實例,必須和能夠正確獲取硬件串口的名稱。

2、sp.ReceivedBytesThreshold = 1; 這個是默認值就是1,就是有一個字節的數據就觸發事件。

3、sp.RtsEnable = true;sp.DtrEnable = true;這兩個屬性必須得正確設置,哈

我就是因為第3個原因一直不不能正確觸發事件。記得添加事件綁定代碼啊。

 

public partial class Form1 : Form
{
SerialPort sp;
bool bIsReading = false;
// Dynamic d = new Dynamic();

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
bool b = false;
try
{
sp = new SerialPort();
sp.BaudRate = 115200;
sp.DataBits = 8;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.PortName = System.IO.Ports.SerialPort.GetPortNames()[0];

sp.RtsEnable = true;
sp.DtrEnable = true;
sp.ReadTimeout = 3000;
sp.ReceivedBytesThreshold = 1;
sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.sp_DataReceived_1);
// sp.DataReceived += Sp_DataReceived;
// sp.DataReceived -= Sp_DataReceived;
sp.Open();


}
catch (Exception xe)
{
b = true;
MessageBox.Show("異常:" + xe.Message);

}
finally {
if (sp != null && b == true)
{
if (sp.IsOpen)
{
sp.Close();

} else
{
sp = null;
}

}

b = false;
}

}

 

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

//sp.DiscardInBuffer();
if (sp != null)
{
sp.Close();
sp.Dispose();
}
}

private void sp_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{


if (bIsReading == true)
return;
bIsReading = true;
try
{
StringBuilder currentline = new StringBuilder();
//循環接收數據
while (sp.BytesToRead > 0)
{
char ch = (char)sp.ReadByte();
currentline.Append(ch);
}
//在這里對接收到的數據進行處理
MessageBox.Show("數據為:" + currentline.ToString());

//GlobalPublic.BasePublic.ShowMessage("數據為:" + currentline.ToString(), (BaseFrm as BaseForm.FrmBaseDoc).MTC_oGlobal);
//InvokeDelegate del = new InvokeDelegate(setItem);
//this.BeginInvoke(del, currentline.ToString());
//setItem(currentline.ToString());
// currentline = new StringBuilder();
}
catch (Exception ex)
{
MessageBox.Show("異常:" + ex.Message);
}
finally
{
bIsReading = false;
}
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM