this.baudRate = 9600; //波特率
this.dataBits = 8; //数据位
this.stopBits = StopBits.One; //停止位
this.portName = "COM1";//串口号
this.readTimeout = -1; //读超时
this.writeTimeout = -1; //写超时
this.receivedBytesThreshold = 1; //触发事件前接收缓冲区的数据个数
this.parityReplace = 0x3f; //数据校验失败,该数据的替换字符
this.newLine = "/n"; //换行符
this.readBufferSize = 4096; //读缓冲区大小
this.writeBufferSize = 2048; //写缓冲区大小
2、看看微软的代码如何枚举本机串口号(也是通过注册表方式)
public static string[] GetPortNames()
{
RegistryKey localMachine = null;
RegistryKey key2 = null;
string[] textArray = null;
//这里有个断言,判断该注册表项是否存在
new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE/HARDWARE/DEVICEMAP/SERIALCOMM").Assert();
try
{
localMachine = Registry.LocalMachine;
key2 = localMachine.OpenSubKey(@"HARDWARE/DEVICEMAP/SERIALCOMM", false);
if (key2 != null)
{
string[] valueNames = key2.GetValueNames();
textArray = new string[valueNames.Length];
for (int i = 0; i < valueNames.Length; i++)
{
textArray[i] = (string) key2.GetValue(valueNames[i]);
}
}
}
finally
{
if (localMachine != null)
{
localMachine.Close();
}
if (key2 != null)
{
key2.Close();
}
CodeAccessPermission.RevertAssert();
}
if (textArray == null)
{
textArray = new string[0];
}
return textArray;
}
private int InternalRead(char[] buffer, int offset, int count, int timeout, bool countMultiByteCharsAsOne)
{
if (count == 0)
{
return 0;
}
int tickCount = Environment.TickCount;
int additionalByteLength = this.internalSerialStream.BytesToRead;
this.MaybeResizeBuffer(additionalByteLength);
//用到了流的串口读写,看来还需要继续跟踪
this.readLen += this.internalSerialStream.Read(this.inBuffer, this.readLen, additionalByteLength);
if (this.decoder.GetCharCount(this.inBuffer, this.readPos, this.CachedBytesToRead) > 0)
{
return this.ReadBufferIntoChars(buffer, offset, count, countMultiByteCharsAsOne);
}
if (timeout == 0)
{
throw new TimeoutException();
}
int maxByteCount = this.Encoding.GetMaxByteCount(count);
while (true)
{
this.MaybeResizeBuffer(maxByteCount);
this.readLen += this.internalSerialStream.Read(this.inBuffer, this.readLen, maxByteCount);
int num4 = this.ReadBufferIntoChars(buffer, offset, count, countMultiByteCharsAsOne);
//只要获取了数据,就返回数据接收的个数
if (num4 > 0)
{
return num4;
}
//这里可以看出timeout设为-1的用意了
if ((timeout != -1) && ((timeout - (Environment.TickCount - tickCount)) <= 0))
{
throw new TimeoutException();
}
}
SafeFileHandle hFile = UnsafeNativeMethods.CreateFile(@"//./" + portName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero);
if (readTimeout == 0)
{
this.commTimeouts.ReadTotalTimeoutConstant = 0;
this.commTimeouts.ReadTotalTimeoutMultiplier = 0;
this.commTimeouts.ReadIntervalTimeout = -1;
}
else if (readTimeout == -1)
{
this.commTimeouts.ReadTotalTimeoutConstant = -2;
this.commTimeouts.ReadTotalTimeoutMultiplier = -1;
this.commTimeouts.ReadIntervalTimeout = -1;
}
else
{
this.commTimeouts.ReadTotalTimeoutConstant = readTimeout;
this.commTimeouts.ReadTotalTimeoutMultiplier = -1;
this.commTimeouts.ReadIntervalTimeout = -1;
}
从以上代码可以看出,它的超时仅仅是总超时时间,不能设置单个字节之间的超时时间。
这是读操作中的一段代码:
int num = 0;
if (this.isAsync)
{
IAsyncResult asyncResult = this.BeginReadCore(array, offset, count, null, null);
num = this.EndRead(asyncResult);
}
Else //对我们来说,仅关心同步操作即可
{
int hr;
num = this.ReadFileNative(array, offset, count, null, out hr);
if (num == -1)
{
InternalResources.WinIOError();
}
}
if (num == 0)
{
throw new TimeoutException();
}
这是读写操作的函数,看给直接用API读没有什么区别:
fixed (byte* numRef = bytes)//用到了指针
{
if (this.isAsync)
{
num = UnsafeNativeMethods.ReadFile(this._handle, numRef + offset, count, IntPtr.Zero, overlapped);
}
else
{
num = UnsafeNativeMethods.ReadFile(this._handle, numRef + offset, count, out numBytesRead, IntPtr.Zero);
}
}
注:写代码与上面的类似
从以上代码可以粗浅的看出(SerialPort类->SerialStream类->UnsafeNativeMethods类->API函数),采用SerialPort读写串口是很繁琐的,并且效率较低,有时间可以根据这写代码写一个紧凑有效的串口读写类(有兴趣的朋友也可以实现,到时候可别忘了发给我一份:)。