改变串口参数无效

nancliu 2008-03-03 03:54:11
我的串口操作语句如下所示:

-------------------------------
// 打开串口
// pPort: 串口名称或设备路径,可用"COM1"或"\\.\COM1"两种方式,建议用后者
// nBaudRate: 波特率
// nParity: 奇偶校验
// nByteSize: 数据字节宽度
// nStopBits: 停止位
BOOL CSerialDeal::OpenComm(const char *pPort, int nBaudRate, int nParity, int nByteSize, int nStopBits)
{
DCB dcb; // 串口控制块
COMMTIMEOUTS timeouts = { // 串口超时控制参数
100, // 读字符间隔超时时间: 100 ms
1, // 读操作时每字符的时间: 1 ms (n个字符总共为n ms)
500, // 基本的(额外的)读超时时间: 500 ms
1, // 写操作时每字符的时间: 1 ms (n个字符总共为n ms)
100}; // 基本的(额外的)写超时时间: 100 ms

hComm = CreateFile(pPort, // 串口名称或设备路径
GENERIC_READ | GENERIC_WRITE, // 读写方式
0, // 共享方式:独占
NULL, // 默认的安全描述符
OPEN_EXISTING, // 创建方式
0, // 不需设置文件属性
NULL); // 不需参照模板文件

if(hComm == INVALID_HANDLE_VALUE) return FALSE; // 打开串口失败

GetCommState(hComm, &dcb); // 取DCB

dcb.BaudRate = nBaudRate;
dcb.ByteSize = nByteSize;
dcb.Parity = nParity;
dcb.StopBits = nStopBits;

SetCommState(hComm, &dcb); // 设置DCB

SetupComm(hComm, 4096, 1024); // 设置输入输出缓冲区大小

::SetCommTimeouts(hComm, &timeouts); // 设置超时

return TRUE;
}

// 关闭串口
BOOL CSerialDeal::CloseComm()
{
return CloseHandle(hComm);
}

// 写串口
// pData: 待写的数据缓冲区指针
// nLength: 待写的数据长度
void CSerialDeal::WriteComm(void *pData, int nLength)
{
DWORD dwNumWrite; // 串口发出的数据长度

WriteFile(hComm, pData, (DWORD)nLength, &dwNumWrite, NULL);
}


// 读串口
// pData: 待读的数据缓冲区指针
// nLength: 待读的最大数据长度
// 返回: 实际读入的数据长度
int CSerialDeal::ReadComm(void *pData, int nLength)
{
DWORD dwNumRead; // 串口收到的数据长度

ReadFile(hComm, pData, (DWORD)nLength, &dwNumRead, NULL);

return (int)dwNumRead;

}

-------------------------
当我用 OpenComm("COM1",115200,0,8,1);改变Com1参数时,我发现Com1的参数还是使用上次成功打开Com1口时的参数

串口监视结果如下:
Baud rate set to 115200

Baud rate set to 9600

StopBits: 1 stop bit, Parity: No parity, WordLength: 8

Port closed

求解决办法。
...全文
209 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
nancliu 2008-03-07
  • 打赏
  • 举报
回复
确实是参数对应的问题,而且谢谢你的建议。
nscboy 2008-03-06
  • 打赏
  • 举报
回复
你的参数错了.
对应dcb.StopBits
ONESTOPBIT = 0代表停止位为1
ONE5STOPBITS = 1代表1.5位停止位
TWOSTOPBITS = 2 代表2位停止位

1.5位停止位对应高于4800的波特率比较难成功.
设为1位停止位还是比较正常的

观察你的代码,对返回值错误的判断比较少.对于一个健壮的类来讲.返回值判断是非常重要的.这将避免你走很多弯路.
对于你打开串口的函数.
你应该在调用系统的每个返回值后面增加错误判断的代码.这对调试也非常有利.



// 打开串口
// pPort: 串口名称或设备路径,可用"COM1"或"\\.\COM1"两种方式,建议用后者
// nBaudRate: 波特率
// nParity: 奇偶校验
// nByteSize: 数据字节宽度
// nStopBits: 停止位
BOOL OpenComm(const char *pPort, int nBaudRate, int nParity, int nByteSize, int nStopBits)
{
DWORD dwErr(0);
DCB dcb; // 串口控制块
COMMTIMEOUTS timeouts = { // 串口超时控制参数
100, // 读字符间隔超时时间: 100 ms
1, // 读操作时每字符的时间: 1 ms (n个字符总共为n ms)
500, // 基本的(额外的)读超时时间: 500 ms
1, // 写操作时每字符的时间: 1 ms (n个字符总共为n ms)
100}; // 基本的(额外的)写超时时间: 100 ms

hComm = CreateFile( pPort, GENERIC_READ | GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
NULL );

if(hComm == INVALID_HANDLE_VALUE){
dwErr = GetLastError();
return FALSE; // 打开串口失败
}

GetCommState(hComm, &dcb); // 取DCB

dcb.BaudRate = nBaudRate;
dcb.ByteSize = nByteSize;
dcb.Parity = nParity;
dcb.StopBits = nStopBits;

int nRet(0);
nRet = SetCommState(hComm, &dcb); // 设置DCB
if(!nRet){
dwErr =GetLastError();
return FALSE;
}

nRet = SetupComm(hComm, 4096, 1024); // 设置输入输出缓冲区大小
if(!nRet){
dwErr =GetLastError();
return FALSE;
}

nRet = ::SetCommTimeouts(hComm, &timeouts); // 设置超时
if(!nRet){
dwErr =GetLastError();
return FALSE;
}

return TRUE;
}
nancliu 2008-03-06
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 iLdf 的回复:]
检测一下SetCommState的返回值,如果是零则调用GetLastError看一下错误原因
[/Quote]

SetCommState返回值没有问题
Treazy 2008-03-04
  • 打赏
  • 举报
回复

The DCB structure defines the control setting for a serial communications device.


typedef struct _DCB { DWORD DCBlength; DWORD BaudRate; DWORD fBinary :1; DWORD fParity :1; DWORD fOutxCtsFlow :1; DWORD fOutxDsrFlow :1; DWORD fDtrControl :2; DWORD fDsrSensitivity :1; DWORD fTXContinueOnXoff :1; DWORD fOutX :1; DWORD fInX :1; DWORD fErrorChar :1; DWORD fNull :1; DWORD fRtsControl :2; DWORD fAbortOnError :1; DWORD fDummy2 :17; WORD wReserved; WORD XonLim; WORD XoffLim; BYTE ByteSize; BYTE Parity; BYTE StopBits; char XonChar; char XoffChar; char ErrorChar; char EofChar; char EvtChar; WORD wReserved1;
} DCB;
Members
DCBlength
Length of the structure, in bytes.
BaudRate
Baud rate at which the communications device operates. This member can be an actual baud rate value, or one of the following indexes:
CBR_110
CBR_300
CBR_600
CBR_1200
CBR_2400
CBR_4800
CBR_9600
CBR_14400
CBR_19200
CBR_38400
CBR_57600
CBR_115200
CBR_128000
CBR_256000


fBinary
If this member is TRUE, binary mode is enabled. Windows does not support nonbinary mode transfers, so this member must be TRUE.
fParity
If this member is TRUE, parity checking is performed and errors are reported.
fOutxCtsFlow
If this member is TRUE, the CTS (clear-to-send) signal is monitored for output flow control. If this member is TRUE and CTS is turned off, output is suspended until CTS is sent again.
fOutxDsrFlow
If this member is TRUE, the DSR (data-set-ready) signal is monitored for output flow control. If this member is TRUE and DSR is turned off, output is suspended until DSR is sent again.
fDtrControl
DTR (data-terminal-ready) flow control. This member can be one of the following values. Value Meaning
DTR_CONTROL_DISABLE Disables the DTR line when the device is opened and leaves it disabled.
DTR_CONTROL_ENABLE Enables the DTR line when the device is opened and leaves it on.
DTR_CONTROL_HANDSHAKE Enables DTR handshaking. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.

fDsrSensitivity
If this member is TRUE, the communications driver is sensitive to the state of the DSR signal. The driver ignores any bytes received, unless the DSR modem input line is high.
fTXContinueOnXoff
If this member is TRUE, transmission continues after the input buffer has come within XoffLim bytes of being full and the driver has transmitted the XoffChar character to stop receiving bytes. If this member is FALSE, transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has transmitted the XonChar character to resume reception.
fOutX
Indicates whether XON/XOFF flow control is used during transmission. If this member is TRUE, transmission stops when the XoffChar character is received and starts again when the XonChar character is received.
fInX
Indicates whether XON/XOFF flow control is used during reception. If this member is TRUE, the XoffChar character is sent when the input buffer comes within XoffLim bytes of being full, and the XonChar character is sent when the input buffer comes within XonLim bytes of being empty.
fErrorChar
Indicates whether bytes received with parity errors are replaced with the character specified by the ErrorChar member. If this member is TRUE and the fParity member is TRUE, replacement occurs.
fNull
If this member is TRUE, null bytes are discarded when received.
fRtsControl
RTS (request-to-send) flow control. This member can be one of the following values. Value Meaning
RTS_CONTROL_DISABLE Disables the RTS line when the device is opened and leaves it disabled.
RTS_CONTROL_ENABLE Enables the RTS line when the device is opened and leaves it on.
RTS_CONTROL_HANDSHAKE Enables RTS handshaking. The driver raises the RTS line when the "type-ahead" (input) buffer is less than one-half full and lowers the RTS line when the buffer is more than three-quarters full. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.
RTS_CONTROL_TOGGLE Specifies that the RTS line will be high if bytes are available for transmission. After all buffered bytes have been sent, the RTS line will be low.
Windows Me/98/95: This value is not supported.

fAbortOnError
If this member is TRUE, the driver terminates all read and write operations with an error status if an error occurs. The driver will not accept any further communications operations until the application has acknowledged the error by calling the ClearCommError function.
fDummy2
Reserved; do not use.
wReserved
Reserved; must be zero.
XonLim
Minimum number of bytes allowed in the input buffer before flow control is activated to inhibit the sender. Note that the sender may transmit characters after the flow control signal has been activated, so this value should never be zero. This assumes that either XON/XOFF, RTS, or DTR input flow control is specified in fInX, fRtsControl, or fDtrControl.
XoffLim
Maximum number of bytes allowed in the input buffer before flow control is activated to allow transmission by the sender. This assumes that either XON/XOFF, RTS, or DTR input flow control is specified in fInX, fRtsControl, or fDtrControl. The maximum number of bytes allowed is calculated by subtracting this value from the size, in bytes, of the input buffer.
ByteSize
Number of bits in the bytes transmitted and received.
Parity
Parity scheme to be used. This member can be one of the following values. Value Meaning
EVENPARITY Even
MARKPARITY Mark
NOPARITY No parity
ODDPARITY Odd
SPACEPARITY Space

StopBits
Number of stop bits to be used. This member can be one of the following values. Value Meaning
ONESTOPBIT 1 stop bit
ONE5STOPBITS 1.5 stop bits
TWOSTOPBITS 2 stop bits

XonChar
Value of the XON character for both transmission and reception.
XoffChar
Value of the XOFF character for both transmission and reception.
ErrorChar
Value of the character used to replace bytes received with a parity error.
EofChar
Value of the character used to signal the end of data.
EvtChar
Value of the character used to signal an event.
wReserved1
Reserved; do not use.
Remarks
When a DCB structure is used to configure the 8250, the following restrictions apply to the values specified for the ByteSize and StopBits members:



The number of data bits must be 5 to 8 bits.
The use of 5 data bits with 2 stop bits is an invalid combination, as is 6, 7, or 8 data bits with 1.5 stop bits.

Requirements
Client Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header Declared in Winbase.h; include Windows.h.



nancliu 2008-03-04
  • 打赏
  • 举报
回复
不是,改成别的也不行
七伤拳 2008-03-04
  • 打赏
  • 举报
回复
检测一下SetCommState的返回值,如果是零则调用GetLastError看一下错误原因
天亮后说晚安 2008-03-04
  • 打赏
  • 举报
回复
不知所云 2
nancliu 2008-03-04
  • 打赏
  • 举报
回复
不知所云
ltc_mouse 2008-03-03
  • 打赏
  • 举报
回复
9600是串口的默认波特率?

有没可能因为串口不支持115200,所以无法设置成功?

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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