⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rs485commdlg.cpp

📁 串口的异步通信,指定的数据写到数组中,完成命令的查询
💻 CPP
字号:
// RS485CommDlg.cpp : implementation file
//

#include "stdafx.h"
#include "RS485Comm.h"
#include "RS485CommDlg.h"
#include "opc\opcda.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

HANDLE hCom;		//全局变量串口句柄

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRS485CommDlg dialog

CRS485CommDlg::CRS485CommDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CRS485CommDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CRS485CommDlg)
	m_disp = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CRS485CommDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CRS485CommDlg)
	DDX_Text(pDX, IDC_DISP, m_disp);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CRS485CommDlg, CDialog)
	//{{AFX_MSG_MAP(CRS485CommDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_SEND, OnSend)
	ON_BN_CLICKED(IDC_RECEIVE, OnReceive)
	ON_WM_CLOSE()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRS485CommDlg message handlers

BOOL CRS485CommDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	hCom = CreateFile("COM1",
					GENERIC_READ | GENERIC_WRITE,
					0,
					NULL,
					OPEN_EXISTING,//打开而不是创建
					FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,	//异步方式或重叠方式
					NULL);
	if (!hCom)		//if(hCom == (HANDLE)-1)
	if (hCom == INVALID_HANDLE_VALUE)
	{
		AfxMessageBox("打开COM失败");
		return FALSE;
	}

	SetupComm(hCom, 100, 100);	//输入输出缓冲区大小为1024

	COMMTIMEOUTS TimeOuts;	//定义一个超时结构体,用于超时
	TimeOuts.ReadIntervalTimeout = MAXDWORD;
	//读延时
	TimeOuts.ReadTotalTimeoutConstant = 0;		//而不管是否读入了要求的字符
	TimeOuts.ReadTotalTimeoutMultiplier = 0;	//在读一次输入缓冲区的内容后读操作就立即返回
	
	//写延时
	TimeOuts.WriteTotalTimeoutConstant = 500;
	TimeOuts.WriteTotalTimeoutMultiplier = 100;
	SetCommTimeouts(hCom, &TimeOuts);	//设置超时

	DCB dcb;
	GetCommState(hCom, &dcb);
	dcb.BaudRate = 9600;	 //波特率
	dcb.ByteSize = 8;		//字节大小为8位
	dcb.Parity = NOPARITY;	//无奇偶校验位
	dcb.StopBits = ONESTOPBIT;	//一个停止位

	PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CRS485CommDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRS485CommDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRS485CommDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CRS485CommDlg::OnSend() 
{
	// TODO: Add your control notification handler code here
	
	OVERLAPPED m_osWrite;
	memset(&m_osWrite, 0, sizeof(OVERLAPPED));
	m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	

	char lpOutBuffer[11];
	memset(lpOutBuffer, 0, 11);
	lpOutBuffer[0] = 0x7E;	//SOI 起始位标志(START OF INFORMATION): 7EH
	lpOutBuffer[1] = 0x20;	//VER 版本号 : 20H
	lpOutBuffer[2] = 'f';	//ADR : 备地址描述(1-32)
	lpOutBuffer[3] = 0x60;	//CID1 控制标识码(设备类型描述): 60H
	lpOutBuffer[4] = 'f';	//CID2
	lpOutBuffer[5] = 'f';	//LENGTH
	lpOutBuffer[6] = 'f';	//
	lpOutBuffer[7] = 'f';	//INFO
	lpOutBuffer[8] = 'f';	//CHKSUM 校验和码
	lpOutBuffer[9] = 0x0D;	//EOI 结束码 :CR(0DH)

	DWORD dwByteWrite = 11;
	COMSTAT ComStat;
	DWORD dwErrorFlags;
	BOOL bWriteStat;
	ClearCommError(hCom, &dwErrorFlags, &ComStat);
	bWriteStat = WriteFile(hCom, &lpOutBuffer,
					dwByteWrite, &dwByteWrite, &m_osWrite);

	if (!bWriteStat)
	{
		if (GetLastError() == ERROR_IO_PENDING)
		WaitForSingleObject(hCom, 1000);
	}
}

void CRS485CommDlg::OnReceive() 
{
	// TODO: Add your control notification handler code here
	OVERLAPPED m_osRead;
	memset(&m_osRead, 0, sizeof(OVERLAPPED));
	m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	COMSTAT ComStat;
	DWORD dwErrorFlags;

	char str[100];
	memset(str, 0, 100);
	DWORD dwBytesRead = 100;		//读取字节数
	BOOL bReadStat;

	ClearCommError(hCom, &dwErrorFlags, &ComStat);
	dwBytesRead = min(dwBytesRead, (DWORD)ComStat.cbInQue);
	bReadStat = ReadFile(hCom, str, dwBytesRead, &dwBytesRead, &m_osRead);

	if (!bReadStat)
	{
		if (GetLastError() == ERROR_IO_PENDING)	//函数返回ERROR_IO_PENDING,表明串口正在进行读操作
		{
			WaitForSingleObject(m_osRead.hEvent, 2000);
			//使用WaitForSingleObject函数等待,直到读操作完成或延时已达到2秒钟
			//当串口读操作进行完毕后,m_osRead的hEvent事件变为有信号
		}
	}

	PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT
					| PURGE_TXCLEAR | PURGE_RXCLEAR);

	m_disp = str;	
//	opc.UpdateItem
	UpdateData(FALSE);
}

void CRS485CommDlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	CloseHandle(hCom);	//程序退出时关闭串口 when the program exit, shutdown the serial port
	CDialog::OnClose();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -