ab56a9bcf7
SVN-Revision: r240
96 lines
2.6 KiB
C#
96 lines
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO.Ports;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
namespace Lskj.Util
|
|
{
|
|
|
|
|
|
public static class SerialPortProgram
|
|
{
|
|
private static SerialPort port = new SerialPort();
|
|
private static bool isHex = false;
|
|
public static string strReceiveMessage = string.Empty;
|
|
|
|
|
|
//创建串口
|
|
public static void establish(List<string> paramList)
|
|
{
|
|
strReceiveMessage = string.Empty;
|
|
port.BaudRate = Convert.ToInt32(paramList[1]+"");
|
|
port.DataBits = Convert.ToInt32(paramList[2] + "");
|
|
port.StopBits = (StopBits)Convert.ToInt32(paramList[3] + "");
|
|
port.Parity = (Parity)Convert.ToInt32(paramList[4] + "");
|
|
var portName = paramList[5] + "";
|
|
if (null != portName)
|
|
port.PortName = portName;
|
|
|
|
|
|
}
|
|
|
|
//打开串口
|
|
public static void Open()
|
|
{
|
|
try
|
|
{
|
|
port.Open();//打开串口
|
|
port.DtrEnable = true;//设置DTR为高电平
|
|
port.RtsEnable = true;//设置RTS位高电平
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
//打开串口出错
|
|
|
|
}
|
|
port.DataReceived -= new SerialDataReceivedEventHandler(sp1_IsLegal_DataReceived);
|
|
port.DataReceived += new SerialDataReceivedEventHandler(sp1_IsLegal_DataReceived);
|
|
}
|
|
|
|
|
|
//关闭
|
|
public static void Close() {
|
|
strReceiveMessage = string.Empty;
|
|
port.Close();
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// 串口接收数据
|
|
/// </summary>
|
|
/// <param name="sender"></param>
|
|
/// <param name="e"></param>
|
|
private static void sp1_IsLegal_DataReceived(object sender, SerialDataReceivedEventArgs e)
|
|
{
|
|
// Thread.Sleep(500);
|
|
string strReceiveMessage = string.Empty;
|
|
Byte[] receivedData = new Byte[port.BytesToRead]; //创建接收字节数组
|
|
port.Read(receivedData, 0, receivedData.Length); //读取数据
|
|
port.DiscardInBuffer();
|
|
//清空SerialPort控件的Buffer
|
|
|
|
if (isHex)
|
|
{
|
|
for (int i = 0; i < receivedData.Length; i++)
|
|
{
|
|
strReceiveMessage += receivedData[i].ToString("X2"); //16进制显示
|
|
}
|
|
}
|
|
else
|
|
{
|
|
strReceiveMessage = Encoding.ASCII.GetString(receivedData);
|
|
}
|
|
|
|
|
|
//264C1830302E306B670D0A
|
|
//wn000000.0kg
|
|
}
|
|
|
|
|
|
}
|
|
}
|