1).開發環境VS12,語言C#windows
2).掃描槍品牌:datalogic 4470緩存
3).通信協議:串口工具
1.首先,第一步建立一個新工程,windows窗體應用程序,命名爲TestScanner,以下:this
2.選擇 「工具」-「選擇工具箱」,以下:調試
3.選擇"microsoft communication control version 6.0",經過此路徑可知其位於64位SysWow64下的ocx控件mscomm32.ocx;orm
4.從右側工具箱「組件」中找到串口控件,拖入窗體Form1中,命名爲MD_MSComm,並在界面初始化中填入相關參數:blog
MD_MSComm.CommPort = 11;接口
MD_MSComm.InputMode = MSCommLib.InputModeConstants.comInputModeText;
MD_MSComm.InBufferSize = 1024;
MD_MSComm.OutBufferSize = 512;
MD_MSComm.Settings = "9600,n,8,1";事件
MD_MSComm.SThreshold = 0;
MD_MSComm.RThreshold = 1;//first byte trigger oncomm event
MD_MSComm.InBufferCount = 0;
MD_MSComm.OutBufferCount = 0;
MD_MSComm.PortOpen = true;開發
5.在控件MD_MSComm的事件中添加「OnComm」事件,並讀取掃碼槍數據代碼以下:
string str="";
if (MD_MSComm.CommEvent > 1000) //CommEvent屬性值,不一樣值表明不一樣的串口狀態,若爲2,表明有數據,可供讀取;
{
Log4netHelper.Error(this.GetType(), "communication error, the value is:" + MD_MSComm.CommEvent.ToString());
return;
}
if (MD_MSComm.CommEvent == 2)
{
if (MD_MSComm.InBufferCount > 0)//串口緩存區的數據長度
{
str = ((string)MD_MSComm.Input).Trim();//input方法 來讀取串口槍緩衝區的數據
if (str.Length == 14)
{
AvailablePublicHelper.CurScanner = str;
Log4netHelper.Info(this.GetType(), "get the content of the scanner is:" + str);
}
else
{
Log4netHelper.Warn(this.GetType(), "get the content of the scanner is not normal:" + str);
}
}
}
6.配置硬件掃碼槍的讀取方式,爲了調試方便,本文選擇的持續讀取模式,若但願選擇命令觸發讀取形式,需每次發送讀取命令「02」至串口,讀取命令,可在串口配置中進行設置,具體品牌可根據掃碼槍供應商來協商;
命令寫入數據到掃碼槍的方式爲MD_MSComm.output;
7.將掃碼槍串口插入到工控機硬件接口,並和程序中的comport值匹配,本文選擇的comm口爲11;
8.結束。