求教一个串口类的问题

nuaa140 2004-11-23 10:00:42
我现在在写一个通过COM口发送手机的程序,里面需要打开和读写串口,我用了网上下的一个类,主要如下:
class CommPort {
public string PortNum;
public int BaudRate;
public byte ByteSize;
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout;

private int hComm = -1;
private bool m_bOpened = false;
public bool Opened
{
get { return m_bOpened;}
}

//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;

[StructLayout(LayoutKind.Sequential)]
public struct DCB {
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate;
public int fParity;
public int fOutxCtsFlow;
public int fOutxDsrFlow;
public int fDtrControl;
public int fDsrSensitivity;
public int fTXContinueOnXoff;
public int fOutX;
public int fInX;
public int fErrorChar;
public int fNull;
public int fRtsControl;
public int fAbortOnError;
public int fDummy2;
public uint flags;
public ushort wReserved;
public ushort XonLim;
public ushort XoffLim;
public byte ByteSize;
public byte Parity;
public byte StopBits;
public char XonChar;
public char XoffChar;
public char ErrorChar;
public char EofChar;
public char EvtChar;
public ushort wReserved1;
}

[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS {
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}

[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED {
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}

[DllImport("kernel32.dll")]
private static extern int CreateFile(
string lpFileName, // 要打开的串口名称
uint dwDesiredAccess, // 指定串口的访问方式,一般设置为可读可写方式
int dwShareMode, // 指定串口的共享模式,串口不能共享,所以设置为0
int lpSecurityAttributes, // 设置串口的安全属性,WIN9X下不支持,应设为NULL
int dwCreationDisposition, // 对于串口通信,创建方式只能为OPEN_EXISTING
int dwFlagsAndAttributes, // 指定串口属性与标志,设置为FILE_FLAG_OVERLAPPED(重叠I/O操作),指定串口以异步方式通信
int hTemplateFile // 对于串口通信必须设置为NULL
);
[DllImport("kernel32.dll")]
private static extern bool GetCommState(
int hFile, //通信设备句柄
ref DCB lpDCB // 设备控制块DCB
);
[DllImport("kernel32.dll")]
private static extern bool BuildCommDCB(
string lpDef, // 设备控制字符串
ref DCB lpDCB // 设备控制块
);
[DllImport("kernel32.dll")]
private static extern bool SetCommState(
int hFile, // 通信设备句柄
ref DCB lpDCB // 设备控制块
);
[DllImport("kernel32.dll")]
private static extern bool GetCommTimeouts(
int hFile, // 通信设备句柄 handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // 超时时间 time-out values
);
[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(
int hFile, // 通信设备句柄 handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // 超时时间 time-out values
);
[DllImport("kernel32.dll")]
private static extern bool ReadFile(
int hFile, // 通信设备句柄 handle to file
byte[] lpBuffer, // 数据缓冲区 data buffer
int nNumberOfBytesToRead, // 多少字节等待读取 number of bytes to read
ref int lpNumberOfBytesRead, // 读取多少字节 number of bytes read
ref OVERLAPPED lpOverlapped // 溢出缓冲区 overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(
int hFile, // 通信设备句柄 handle to file
byte[] lpBuffer, // 数据缓冲区 data buffer
int nNumberOfBytesToWrite, // 多少字节等待写入 number of bytes to write
ref int lpNumberOfBytesWritten, // 已经写入多少字节 number of bytes written
ref OVERLAPPED lpOverlapped // 溢出缓冲区 overlapped buffer
);
public bool Open()
{

DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
hComm = CreateFile(PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);

if(hComm == INVALID_HANDLE_VALUE)
{
m_bOpened = false;
return false;
}

// 设置通信超时时间 SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm,ref ctoCommPort);

// 设置串口 SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate=BaudRate;

dcbCommPort.flags=0;
//dcb.fBinary=1;
dcbCommPort.flags|=1;
if (Parity>0)
{
//dcb.fParity=1
dcbCommPort.flags|=2;
}
dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits;
if (!SetCommState(hComm, ref dcbCommPort))
{
m_bOpened = false;
return false;
}
m_bOpened = true;
return true;
}
public byte[] Read(int NumBytes) {
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE) {
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else {
m_bOpened = false;
OutBytes = new byte[0];
}
return OutBytes;
}

public void Write(byte[] WriteBytes) {
if (hComm!=INVALID_HANDLE_VALUE) {
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
}
else {
m_bOpened = false;
}
}
}

class HexCon {
public static string ByteToString(byte[] InBytes) {
string StringOut="";
foreach (byte InByte in InBytes) {
StringOut=StringOut + String.Format("{0:X2} ",InByte);
}
return StringOut;
}
public static byte[] StringToByte(string InString) {
string[] ByteStrings;
ByteStrings = InString.Split(" ".ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length-1];
for (int i = 0;i==ByteStrings.Length-1;i++) {
ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
}
return ByteOut;
}
}
}

可是当我用这个类Open()函数打开串口COM1后,用Write()函数写AT命令给串口,用Read()函数读串口却收不到任何东西(OK或者ERROR)。但是我用超级终端打开COM1口后(关闭超级终端),再用类中的Open()函数去打开串口COM1,这个时候写AT命令,就能收到回复了,就可以发短消息了。
我不知道是不是这个类写的有问题,还望各位大虾帮帮忙啊,解决一下。
...全文
218 22 打赏 收藏 转发到动态 举报
写回复
用AI写文章
22 条回复
切换为时间正序
请发表友善的回复…
发表回复
nuaa140 2004-12-07
  • 打赏
  • 举报
回复
兄弟不好意思了。本来是给你50分的。看错了。。对不起啊。。
sky 2004-11-28
  • 打赏
  • 举报
回复
啊,我说了这么多,原来1分都没有的呀???

呵呵,算了,我本来就是个“白天傻子”。呵呵。
nuaa140 2004-11-27
  • 打赏
  • 举报
回复
谢谢pantian(白天傻子)。跟打开超级终端后一比,给DCB中的两个字段赋值就可以了。
51106354 2004-11-26
  • 打赏
  • 举报
回复
帮你顶
elusion 2004-11-26
  • 打赏
  • 举报
回复
嗯...打开关闭终端就可以了...是不是前一次用的时候 串口没正确关闭...可以调用一次关闭 然后再打开 试试
另外 这个类也太简单了吧 不好用是一定的
sky 2004-11-25
  • 打赏
  • 举报
回复
这个类其实基本上是正确的,应该是可以用的。

其实你要DEBUG一下也是很容易的,你出现这个错误,很明显是在OPEN里的一些设置有问题,这样,才使得必须借助超级终端先打开串口,然后才能通信。

所以,你只需要在DEBUG你的这个程序时,记下进行设置后,所有的参数值。然后与用超级终端打开后,记下的参数值对比一下,应该很快就能知道错在什么地方了。
nuaa140 2004-11-24
  • 打赏
  • 举报
回复
艾。整了一整天了,就不知道错误在哪里。我就想不通,网上别人用这个类的时候怎么会没有碰到错误呢?真是越想越郁闷啊。。。
nuaa140 2004-11-24
  • 打赏
  • 举报
回复
可是我对这个不是太了解,我也不知道DCB结构在哪里有问题?MSDN上的DCB结构好象都是很早的。。
sky 2004-11-24
  • 打赏
  • 举报
回复
你把

dcbCommPort.StopBits = 1;
改为
dcbCommPort.StopBits = 0;

应该就可以了。
nuaa140 2004-11-24
  • 打赏
  • 举报
回复
哦,我的参数是:
dcbCommPort.Parity =0;
dcbCommPort.ByteSize = 8;
dcbCommPort.StopBits = 1;
不知道有没有问题?
sky 2004-11-24
  • 打赏
  • 举报
回复
是的,这个程序并不是很完善的,没有异步通信,也没有事件机制。

在某些特殊情况下,有可能会因为无限制在等待,而造成死机。

但如果能看懂上面那个程序,自己再完善一下,也是很快的。

我估计是你输入的那个StopBits有问题
wanliguout 2004-11-24
  • 打赏
  • 举报
回复
自己跟一下程序吧,看看是不是每一步返回结果都正常
不过这个类很不完善,没有形成机制来处理接收事件和发送完毕事件,如果你在这方面没经验,最好使用mscomm那个控件算了
sky 2004-11-24
  • 打赏
  • 举报
回复
应该是你的参数有问题,下面这几条语句,你的输入参数是什么?

dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits

也就是Parity\ByteSize\StopBits具体各是什么?
xiaoslong 2004-11-24
  • 打赏
  • 举报
回复
帮你顶
cxyPioneer 2004-11-24
  • 打赏
  • 举报
回复
up
sky 2004-11-24
  • 打赏
  • 举报
回复
如果还不行,估计是那个DCB结构有问题了,这个DCB结构好像在不同版本的windows上,结构好像有点区别的,你看看那个DCB的大小应该可以测试是否与你的机器一致的。你自己跟踪一下吧。
jimh 2004-11-24
  • 打赏
  • 举报
回复
打开端口时好像有些东西没有设置
sky 2004-11-24
  • 打赏
  • 举报
回复
public byte StopBits; // 0,1,2 = 1, 1.5, 2

=============================================================
上面那个StopBits的设置,其实在你自己的程序里就有注释的。
sky 2004-11-24
  • 打赏
  • 举报
回复
我们一般用的停止位是=1。

但因为你调用的是API函数,而在API函数里,
StopBits = 0 --->1个停止位
StopBits = 1 --->1.5个停止位
StopBits = 2 --->2个停止位
这个你可以看看MSDN里的参数说明。

如果这样还不行的话,那就只能你自己debug了,看看每走一步,是否与应得结果一致了。
nuaa140 2004-11-24
  • 打赏
  • 举报
回复
还是不行,写AT命令后还是什么都没有收到。好象超级终端里StopBits 是设成 1吧
加载更多回复(2)

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧