using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace SerialPortTest
{
public delegate void ReceiveMsgFromSerialPort(string s);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SerialPort _sp;
#region 相关方法
//实例化一个串口serialport
public bool Initialize()
{
try
{
if (_sp != null)
{
//_sp.Open();
return true;
}
_sp = new SerialPort();
_sp.Parity = Parity.None;
_sp.PortName = "COM1";
_sp.BaudRate = 115200;
_sp.DataBits = 8;
_sp.StopBits = StopBits.One;
_sp.Handshake = Handshake.None;
_sp.DataReceived += new SerialDataReceivedEventHandler(_sp_DataReceived);
//_sp.Open();
return true;
}
catch(Exception ex)
{
MessageBox.Show("初始化出错"+ex.ToString());
return false;
}
}
//换行
public void StringTest(string s)
{
rtb_ReceiveMsg.Text += s;
//rtb_ReceiveMsg.Text += Environment.NewLine;
}
void _sp_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
string s = "";
byte[] APICmd=new byte[34];
Thread.Sleep(300);
_sp.Read(APICmd, 0, APICmd.Length);
for (int i = 0; i < APICmd.Length; i++)
{
if(int.Parse(APICmd[i].ToString())<16)
{
s += APICmd[i].ToString();
//s += "0" + DToX(int.Parse(APICmd[i].ToString()));
}
else
{
s += APICmd[i].ToString();
//s += "" + DToX(int.Parse(APICmd[i].ToString()));
}
}
rtb_ReceiveMsg.Invoke(new ReceiveMsgFromSerialPort(StringTest),new object[] {s});
s = "";
}
//10进制转换为16进制
public string DToX(int d)
{
string x = "";
if (d < 16)
{
x = change(d);
}
else
{
int c, s = 0, n = d, t = d;
while (n >= 16)
{
s++;
n = n / 16;
}
string[] m=new string[s];
int i=0;
do
{
c = d / 16;
m[i++] = change(d % 16);
d = c;
} while (c >= 16);
x = change(d);
for(int j=m.Length-1;j>=0;j--)
{
x += m[j];
}
return x;
}
return x;
}
private string change(int d)
{
string x = "";
switch (d)
{
case 10:
x = "A";
break;
case 11:
x = "B";
break;
case 12:
x = "C";
break;
case 13:
x = "D";
break;
case 14:
x = "E";
break;
case 15:
x = "F";
break;
default:
x = d.ToString();
break;
}
return x;
}
#endregion
#region 按钮事件
private void btn_Connect_Click(object sender, EventArgs e)
{
if (Initialize())
{
MessageBox.Show("已打开连接");
_sp.Open();
btn_Connect.Enabled = false;
btn_Close.Enabled = true;
}
else
{
MessageBox.Show("连接出错");
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
_sp.Close();
MessageBox.Show("已断开连接");
btn_Close.Enabled = false;
btn_Connect.Enabled = true;
}
private void btn_Clear_Click(object sender, EventArgs e)
{
this.rtb_ReceiveMsg.Clear();
}
private void btn_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
}
}