|
//#include "stdafx.h"
#include
#include "resource.h"
#include "MainDlg.h"
#include
#include
#include
HANDLE hComm;//用于获取串口打开函数的返回值(句柄或错误值)
OVERLAPPED m_ov;
COMSTAT comstat;
DWORD m_dwCommEvents;
TCHAR cRecs[200],cSends[100]; //接收字符串 发送字符串
char j=0,*cCom; //接收用统计数据大小变量 端口选择
BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);
HANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand);
HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);
}
return FALSE;
}
/*系统初始化函数*/
BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
HWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);
ComboBox_InsertString(hwndCombo1,-1,TEXT("COM1"));
ComboBox_InsertString(hwndCombo1,-1,TEXT("COM2"));
ComboBox_InsertString(hwndCombo1,-1,TEXT("COM3"));
ComboBox_InsertString(hwndCombo1,-1,TEXT("COM4"));
ComboBox_InsertString(hwndCombo1,-1,TEXT("COM5"));
ComboBox_SetCurSel(hwndCombo1,0);
void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime);
SetTimer(hwnd,1,1000,TimerProc);
return TRUE;
}
/*监视串口错误时使用的函数*/
bool ProcessErrorMessage(char* ErrorText)
{
char *Temp = new char[200];
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
sprintf(Temp, "WARNING: %s Failed with the following error: \n%s\nPort: %d\n", (char*)ErrorText, lpMsgBuf, "com2");
MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);
LocalFree(lpMsgBuf);
delete[] Temp;
return true;
}
bool openport(char *portname)//打开串口
{
hComm = CreateFile(portname, //串口号 "com1""com2" 调用方法:bool open; open=openport("com2");
GENERIC_READ | GENERIC_WRITE, //允许读写
0, //通讯设备必须以独占方式打开
0, //无安全属性
OPEN_EXISTING, //通讯设备已存在
FILE_FLAG_OVERLAPPED, //异步I/O
0); //通讯设备不能用模板打开
if (hComm == INVALID_HANDLE_VALUE) //如果被占用或是没有打开时返回的是这个错误代码
{
CloseHandle(hComm);
return FALSE;
}
else
return true;
}
bool setupdcb(int rate_arg)//设置port的属性
{
DCB dcb;
int rate= rate_arg;
memset(&dcb,0,sizeof(dcb));
if(!GetCommState(hComm,&dcb))//获取当前DCB配置
return FALSE;
// set DCB to configure the serial port
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = rate;
dcb.Parity = NOPARITY; //奇偶校验值0~4分别对应无校验、奇校验、偶校验、校验置位、校验清零
dcb.fParity = 0; //为1的话激活奇偶校验检查
dcb.StopBits = ONESTOPBIT;//停止位个数,0~2分别对应1位、1.5位、2位停止位
dcb.ByteSize = 8; //数据位数
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = 0;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fErrorChar = 0;
dcb.fBinary = 1;
dcb.fNull = 0;
dcb.fAbortOnError = 0;
dcb.wReserved = 0;
dcb.XonLim = 2;
dcb.XoffLim = 4;
dcb.XonChar = 0x13;
dcb.XoffChar = 0x19;
dcb.EvtChar = 0;
// set DCB
if(!SetCommState(hComm,&dcb))
return false;
else
return true;
}
/*串口读取相关时间设置*/
bool setuptimeout(DWORD ReadInterval,DWORD ReadTotalMultiplier,DWORD ReadTotalconstant,DWORD WriteTotalMultiplier,DWORD WriteTotalconstant)
{
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout=ReadInterval; //读取两个字节间隔最大值mS如超过立即返回不再读取
timeouts.ReadTotalTimeoutConstant=ReadTotalconstant; //如果同下面一个都为0 则无论是否读到数据都返回
// 可以毫秒为单位指定一个乘数,该乘数用来计算读操作的总限时时间
timeouts.ReadTotalTimeoutMultiplier=ReadTotalMultiplier; // 以毫秒为单位指定一个常数,用于计算读操作的总限时时间 0表示不限时
timeouts.WriteTotalTimeoutConstant=WriteTotalconstant;// 写操作延时 同上
timeouts.WriteTotalTimeoutMultiplier=WriteTotalMultiplier;
if(!SetCommTimeouts(hComm, &timeouts))
return false;
else
return true;
}
int Clearn() //清除buff中的内容并返回buff中现有数据量的大小并读取错误原因
{
DWORD dwError = 0;
DWORD BytesRead = 0;
ClearCommError(hComm, &dwError, &comstat);
return comstat.cbInQue; //返回buff中数据量
}
/*串口数据接收 读取函数*/
void ReceiveChar()
{
BOOL bRead = TRUE;
BOOL bResult = TRUE;
DWORD dwError = 0;
DWORD BytesRead = 0;
char i=0,n;
char RXBuff;
j=0;
while (i-n)
{
n=i;
Sleep(10);
bResult = ClearCommError(hComm, &dwError, &comstat);
i=(char)comstat.cbInQue;
}
for (;i>0;i--)
{
if (bRead)
bResult = ReadFile(hComm, // Handle to COMM port
&RXBuff, // RX Buffer Pointer
1, // Read one byte
&BytesRead, // Stores number of bytes read
&m_ov); // pointer to the m_ov structure
// printf("%c",RXBuff);
cRecs[j++]=(char)RXBuff;
if (!bResult)
{
switch (dwError = GetLastError())
{
case ERROR_IO_PENDING:
{
bRead = FALSE;
break;
}
default: break;
}
}
else
bRead = TRUE; // close if (bRead)
if (!bRead)
{
bRead = TRUE;
bResult = GetOverlappedResult(hComm, // Handle to COMM port
&m_ov, // Overlapped structure
&BytesRead, // Stores number of bytes read
TRUE); // Wait flag
}
}
}
bool WriteChar(char* m_szWriteBuffer,DWORD m_nToSend) //写字符的函数
{
BOOL bWrite = TRUE;
BOOL bResult = TRUE;
DWORD BytesSent = 0;
HANDLE m_hWriteEvent;
ResetEvent(m_hWriteEvent);
if (bWrite)
{
m_ov.Offset = 0;
m_ov.OffsetHigh = 0;// Clear buffer
bResult = WriteFile(hComm, // Handle to COMM Port
m_szWriteBuffer, // Pointer to message buffer in calling finction
m_nToSend, // Length of message to send
&BytesSent, // Where to store the number of bytes sent
&m_ov ); // Overlapped structure
if (!bResult)
{
DWORD dwError = GetLastError();
switch (dwError)
{
case ERROR_IO_PENDING:
{
// continue to GetOverlappedResults()
BytesSent = 0;
bWrite = FALSE;
break;
}
default:
// all other error codes
break;
}
}
} // end if(bWrite)
if (!bWrite)
{
bWrite = TRUE;
bResult = GetOverlappedResult(hComm, // Handle to COMM port
&m_ov, // Overlapped structure
&BytesSent, // Stores number of bytes sent
TRUE); // Wait flag
// deal with the error code
if (!bResult)
{
printf("GetOverlappedResults() in WriteFile()");
}
} // end if (!bWrite)
// Verify that the data size send equals what we tried to send
if (BytesSent != m_nToSend)
{
printf("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)m_szWriteBuffer));
}
return true;
}
/*window时间函数 回调*/
void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
SYSTEMTIME time; //定义机构体变量time
GetLocalTime(&time); //取系统时间以指针方式
TCHAR strTime[256]; //程序只有一个作用
wsprintf(strTime,"%04d-%02d-%02d %02d:%02d:%02d",time.wYear, //就是读取系统时间
time.wMonth,time.wDay,time.wHour,time.wMinute,time.wSecond);//然后写进strTime
SetDlgItemText(hwnd,IDC_TIME,strTime); //这个字符串
}
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch(id)
{
case IDC_SEND:
{
GetDlgItemText (hwnd,IDC_EDIT2,cSends,sizeof(cSends));
unsigned n=sizeof(cSends); //n是通知串口将发送字节的长度
char send[100];
wsprintf (send,"%s",cSends);
WriteChar(send,n-1);
SetCommMask(hComm, EV_RXCHAR); //监视串口是否接收有数据
ReceiveChar(); //读取串口sbuff中数据
cRecs[j]='\0'; //将cRecs转为字符串
SetDlgItemText(hwnd,IDC_EDIT1,cRecs);
} break;
/*
case IDC_RECEIVE: //暂时未用 采用直接显示的方式
{
}
break;*/
case IDC_CHECK:
{
int ctr;
HWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);
ctr = ComboBox_GetCurSel(hwndCombo1);
switch (ctr)
{
case 0:cCom="com1";break;
case 1:cCom="com2";break;
case 2:cCom="com3";break;
case 3:cCom="com4";break;
case 4:cCom="com5";break;
default: cCom="com1";
break;
}
if (openport(cCom))
{ SetDlgItemText(hwnd,IDC_EDIT3,"OK !");
MessageBox(hwnd,"串口打开成功!","",0); }
else
SetDlgItemText(hwnd,IDC_EDIT3,"FAIL");
if(setupdcb(9600)&&setuptimeout(1024,0,0,20,1000)) //初始化串口属性 波特率9600
SetDlgItemText(hwnd,IDC_EDIT4,"串口属性设置成功");
else
SetDlgItemText(hwnd,IDC_EDIT4,"串口初始化失败!");
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
}
default:
break;
}
}
void Main_OnClose(HWND hwnd)
{
EndDialog(hwnd, 0);
}
|
|