c# 串口编程

http://news.ccidnet.com/art/32859/20100524/2067861_4.html

字节缓冲器处理类:

 /// <summary>
/// 字节缓冲器
/// </summary>
public class ByteQueue
{
private List<byte> m_buffer = new List<byte>();
public bool Find()
{
if (m_buffer.Count == )
return false;
int HeadIndex = m_buffer.FindIndex(o => o == 0xAA); if (HeadIndex == -)
{
m_buffer.Clear();
return false; //没找到AA
} else if (HeadIndex != ) //不为开头移掉之前的字节
{
if (HeadIndex > )
m_buffer.RemoveRange(, HeadIndex);
} int length= GetLength(); if (m_buffer.Count <length)
{
return false;
} int TailIndex = m_buffer.FindIndex(o => o == 0x55); //查找55的位置 if (TailIndex == -)
{
//这一步为防止连发一个AA开头的包后,没发55,而又发了一个AA
int head = m_buffer.FindLastIndex(o => o == 0xAA);
if (head > -)
{
m_buffer.RemoveRange(, head);
}
return false;
}
else if (TailIndex + != length) //计算包尾是否与包长度相等
{
m_buffer.RemoveRange(, TailIndex);
return false;
} return true;
} /// <summary>
/// 命令类型
/// </summary>
/// <returns></returns>
public byte Cmd()
{
if (m_buffer.Count >= )
{
return m_buffer[];
}
return ;
} /// <summary>
/// 序号
/// </summary>
/// <returns></returns>
public byte Number()
{
if (m_buffer.Count >= )
{
return m_buffer[];
}
return ;
} /// <summary>
/// 包长度
/// </summary>
/// <returns></returns>
public int GetLength()
{
int len = ;//AA 命令类型 序号 校验和 55
if (m_buffer.Count >= )
{
switch (m_buffer[]) //第三字节为序号
{
case 0x00: //序号
return len + ;
case 0x01: //序号
return len + ;
case 0x02: //序号
return len + ;
}
}
return ;
}
/// <summary>
/// 提取数据
/// </summary>
public void Dequeue(byte[] buffer, int offset,int size)
{
m_buffer.CopyTo(,buffer,offset,size);
m_buffer.RemoveRange(, size);
} /// <summary>
/// 队列数据
/// </summary>
/// <param name="buffer"></param>
public void Enqueue(byte[] buffer)
{
m_buffer.AddRange(buffer);
}
}

调用示例:

 private ByteQueue queue = new ByteQueue();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int len = serialPort1.BytesToRead;
if (len > )
{
byte[] temp = new byte[len];
serialPort1.Read(temp, , len);
queue.Enqueue(temp);
while (queue.Find()) //while可处理同时接收到多个AA ... 55 ,AA...55的包
{
int length = queue.GetLength();
byte[] readBuffer = new byte[len];
queue.Dequeue(readBuffer, , length);
OnReceiveData(readBuffer); //<这里自己写一个委托吧就OK了
} } }
上一篇:Delphi识别读取验证码


下一篇:python知识合集