定义:
-
using System.IO.Ports;
-
- SerialPort myPort = new SerialPort()
-
//port初始化
-
public void _port_Init(string comName)
-
{
-
myPort.PortName = comName;
-
myPort.BaudRate = 9600;
-
myPort.DataBits = 8;
-
myPort.Parity = Parity.None;
-
-
myPort.ReadTimeout = 1000;
-
-
myPort.Open();
-
myPort.DataReceived += new SerialDataReceivedEventHandler(myPort_DataReceived);
-
- }
二、串口接收事件
-
//接收事件
-
void myPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
-
{
-
if (myPort.IsOpen)
-
{
-
try
-
{
- byte[] receiveData = new byte[myPort.BytesToRead];//用receiveData数组读取
- myPort.Read(receiveData, 0, receiveData.Length);//读取数据
-
- //myPort.DiscardInBuffer();
- for (int i = 0; i < receiveData.Length; i++)
- {
- check[i] = receiveData[i]; //简单的定义了一个byte check[1000]接收数据
- Console.Write(check[i]);
- }
-
- string strRcv = null;
- for (int i = 0; i < receiveData.Length; i++)
- {
- strRcv += receiveData[i].ToString("X2");//十六进制显示
- }
- /*使用委托,如果需要修改控件*/
-
-
}
-
catch (System.Exception ex)
-
{
-
MessageBox.Show(ex.Message, "出错提示");
-
}
-
}
- }
三、串口发送
对应单片机里的串口中断
-
cmd = "55";
-
bytCmd[0] = Convert.ToByte(cmd.Substring(0, 2), 16);
- myPort.Write(bytCmd, 0, 1);
存留备份
-
//port发送
-
public void _port_DataSend(string strCommand)
-
{
-
//处理数字转换
-
string sendBuf = strCommand;
-
string sendnoNull = sendBuf.Trim();
-
string sendNOComma = sendnoNull.Replace(',', ' '); //去掉英文逗号
-
string sendNOComma1 = sendNOComma.Replace(',', ' '); //去掉中文逗号
-
string strSendNoComma2 = sendNOComma1.Replace("0x", ""); //去掉0x
-
strSendNoComma2.Replace("0X", ""); //去掉0X
-
//用' '分开成多个字符串,用strArray装
-
string[] strArray = strSendNoComma2.Split(' ');
-
-
int byteBufferLength = strArray.Length;//获取strArray个数
-
for (int i = 0; i < strArray.Length; i++)//排除空格数字
-
{
-
if (strArray[i] == "")
-
{
-
byteBufferLength--;
-
}
-
}
-
// int temp = 0;
-
byte[] byteBuffer = new byte[byteBufferLength];
-
int ii = 0;
-
for (int i = 0; i < strArray.Length; i++) //对获取的字符做相加运算
-
{
-
int decNum = 0;
-
decNum = Convert.ToInt32(strArray[i], 16); //atrArray[i] == 12时,temp == 18
-
-
try //防止输错,使其只能输入一个字节的字符
-
{
-
byteBuffer[ii] = Convert.ToByte(decNum);
-
}
-
catch (System.Exception ex)
-
{
-
MessageBox.Show("字节越界,请逐个字节输入!", "Error");
-
//tmSend.Enabled = false;
-
return;
-
}
-
-
ii++;
-
}
-
myPort.Write(byteBuffer, 0, byteBuffer.Length);
-
- }
四、一些参考目录:
http://blog.csdn.net/lllljz/article/details/7603400
http://www.cnblogs.com/elaron/archive/2011/03/15/1985378.html
http://blog.csdn.net/geekwangminli/article/details/7851673
http://blog.csdn.net/cy757/article/details/4474930
http://www.cnblogs.com/screes/p/5633383.html