110,533
社区成员
发帖
与我相关
我的任务
分享
class Serial
{
private SerialPort _com = new SerialPort();//串口对象
public Serial(string strcom,int nbot)
{
OpenPort(strcom, nbot);
_com.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceivedAddress);
}
/// <summary>
/// 打开串口
/// </summary>
/// <param name="strCom">串口名“COM1” </param>
/// <param name="nBot">波特率 </param>
/// <param name="nThreshold">引发消息事件的字节数 </param>
public void OpenPort(string strCom, int nBot)
{
try
{
//串口设置与打开
//_com.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceivedAddress);
_com.PortName = strCom;
_com.BaudRate = nBot;
_com.DataBits = 8;
_com.StopBits = StopBits.One;
_com.Parity = Parity.Even;
_com.Open();
}
catch (Exception ex)
{
//Application.Exit();//退出应用程序
//System.Diagnostics.Process.Start("JT.exe");//启动程序
MessageBox.Show("“" + ex.Message + "”设置硬件功能将不可用,如要使用该功能,请到主窗体的系统设置中选择正确的串口信息,并重新打开该模块!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
public void DataReceivedAddress(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[_com.BytesToRead];
_com.Read(data, 0, data.Length);
if (data.Length != 0)
{
DisposeRecvDataAddress(data);
}
}
public void DisposeRecvDataAddress(byte[] data)
{
string strReceive = "";
//MessageBox.Show("进来了");
try
{
for (int i = 0; i < data.Length; i++)
{
strReceive += TenToHex(data[i].ToString());
//strReceive += data[i].ToString();
}
}
catch
{
}
}
private string TenToHex(string p)
{
throw new NotImplementedException();
}
}
Serial _com = new Serial("com4", 9600);