C++用vs2015控制台实现串口通信可发送指定数据到下位机

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42244181/article/details/88323454

通过一个串口类的编写实现C++用vs2015控制台实现串口通信可发送指定数据到下位机,用52单片机进行过测试,完全没问题。头文件和cpp文件需要自己添加,选择自己需要的串口,暂不支持自动选择串口。

 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "SerialPort.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
	int main()
	{

		CSerialPort mySerialPort;
		mySerialPort.InitPort();

		if (!mySerialPort.InitPort())
		{
			std::cout << "initPort fail !" << std::endl;
		}
		else
		{
			std::cout << "initPort success !" << std::endl;
		}

		if (!mySerialPort.OpenListenThread())
		{
			std::cout << "OpenListenThread fail !" << std::endl;
		}
		else
		{
			std::cout << "OpenListenThread success !" << std::endl;
		}
		unsigned char g_UartRxBuffer[1] = {0xff};//对应要发送的一个字节内容 如果写为2,默认补零造成错误
		unsigned char* pData = g_UartRxBuffer;
	
		mySerialPort.WriteData(pData, 1);//发送一个字节长度
		return 0;
	}


#include "StdAfx.h"  
#include "SerialPort.h"  
#include <process.h>  
#include <iostream>  

/** 线程退出标志 */
bool CSerialPort::s_bExit = false;
/** 当串口无数据时,sleep至下次查询间隔的时间,单位:秒 */
const UINT SLEEP_TIME_INTERVAL = 5;

CSerialPort::CSerialPort(void)
	: m_hListenThread(INVALID_HANDLE_VALUE)
{
	m_hComm = INVALID_HANDLE_VALUE;
	m_hListenThread = INVALID_HANDLE_VALUE;

	InitializeCriticalSection(&m_csCommunicationSync);

}

CSerialPort::~CSerialPort(void)
{
	CloseListenTread();
	ClosePort();
	DeleteCriticalSection(&m_csCommunicationSync);
}

bool CSerialPort::InitPort(UINT portNo /*= 1*/, UINT baud /*= CBR_9600*/, char parity /*= 'N'*/,
	UINT databits /*= 8*/, UINT stopsbits /*= 1*/, DWORD dwCommEvents /*= EV_RXCHAR*/)
{

	/** 临时变量,将制定参数转化为字符串形式,以构造DCB结构 */
	char szDCBparam[50];
	sprintf_s(szDCBparam, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, stopsbits);

	/** 打开指定串口,该函数内部已经有临界区保护,上面请不要加保护 */
	if (!openPort(portNo))
	{
		return false;
	}

	/** 进入临界段 */
	EnterCriticalSection(&m_csCommunicationSync);

	/** 是否有错误发生 */
	BOOL bIsSuccess = TRUE;

	/** 在此可以设置输入输出的缓冲区大小,如果不设置,则系统会设置默认值.
	*  自己设置缓冲区大小时,要注意设置稍大一些,避免缓冲区溢出
	*/
	/*if (bIsSuccess )
	{
	bIsSuccess = SetupComm(m_hComm,10,10);
	}*/

	/** 设置串口的超时时间,均设为0,表示不使用超时限制 */
	COMMTIMEOUTS  CommTimeouts;
	CommTimeouts.ReadIntervalTimeout = 0;
	CommTimeouts.ReadTotalTimeoutMultiplier = 0;
	CommTimeouts.ReadTotalTimeoutConstant = 0;
	CommTimeouts.WriteTotalTimeoutMultiplier = 0;
	CommTimeouts.WriteTotalTimeoutConstant = 0;
	if (bIsSuccess)
	{
		bIsSuccess = SetCommTimeouts(m_hComm, &CommTimeouts);
	}

	DCB  dcb;
	if (bIsSuccess)
	{
		// 将ANSI字符串转换为UNICODE字符串  
		DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, szDCBparam, -1, NULL, 0);
		wchar_t *pwText = new wchar_t[dwNum];
		if (!MultiByteToWideChar(CP_ACP, 0, szDCBparam, -1, pwText, dwNum))
		{
			bIsSuccess = TRUE;
		}

		/** 获取当前串口配置参数,并且构造串口DCB参数 */
		bIsSuccess = GetCommState(m_hComm, &dcb) && BuildCommDCB(pwText, &dcb);
		/** 开启RTS flow控制 */
		dcb.fRtsControl = RTS_CONTROL_ENABLE;

		/** 释放内存空间 */
		delete[] pwText;
	}

	if (bIsSuccess)
	{
		/** 使用DCB参数配置串口状态 */
		bIsSuccess = SetCommState(m_hComm, &dcb);
	}

	/**  清空串口缓冲区 */
	PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);

	/** 离开临界段 */
	LeaveCriticalSection(&m_csCommunicationSync);

	return bIsSuccess == TRUE;
}

bool CSerialPort::InitPort(UINT portNo, const LPDCB& plDCB)
{
	/** 打开指定串口,该函数内部已经有临界区保护,上面请不要加保护 */
	if (!openPort(portNo))
	{
		return false;
	}

	/** 进入临界段 */
	EnterCriticalSection(&m_csCommunicationSync);

	/** 配置串口参数 */
	if (!SetCommState(m_hComm, plDCB))
	{
		return false;
	}

	/**  清空串口缓冲区 */
	PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);

	/** 离开临界段 */
	LeaveCriticalSection(&m_csCommunicationSync);

	return true;
}

void CSerialPort::ClosePort()
{
	/** 如果有串口被打开,关闭它 */
	if (m_hComm != INVALID_HANDLE_VALUE)
	{
		CloseHandle(m_hComm);
		m_hComm = INVALID_HANDLE_VALUE;
	}
}

bool CSerialPort::openPort(UINT portNo)
{
	/** 进入临界段 */
	EnterCriticalSection(&m_csCommunicationSync);

	/** 把串口的编号转换为设备名 */
	char szPort[50];
	sprintf_s(szPort, "COM%d", portNo);

	/** 打开指定的串口 */
	m_hComm = CreateFileA(szPort,  /** 设备名,COM1,COM2等 */
		GENERIC_READ | GENERIC_WRITE, /** 访问模式,可同时读写 */
		0,                            /** 共享模式,0表示不共享 */
		NULL,                         /** 安全性设置,一般使用NULL */
		OPEN_EXISTING,                /** 该参数表示设备必须存在,否则创建失败 */
		0,
		0);

	/** 如果打开失败,释放资源并返回 */
	if (m_hComm == INVALID_HANDLE_VALUE)
	{
		LeaveCriticalSection(&m_csCommunicationSync);
		return false;
	}

	/** 退出临界区 */
	LeaveCriticalSection(&m_csCommunicationSync);

	return true;
}

bool CSerialPort::OpenListenThread()
{
	/** 检测线程是否已经开启了 */
	if (m_hListenThread != INVALID_HANDLE_VALUE)
	{
		/** 线程已经开启 */
		return false;
	}

	s_bExit = false;
	/** 线程ID */
	UINT threadId;
	/** 开启串口数据监听线程 */
	m_hListenThread = (HANDLE)_beginthreadex(NULL, 0, ListenThread, this, 0, &threadId);
	if (!m_hListenThread)
	{
		return false;
	}
	/** 设置线程的优先级,高于普通线程 */
	if (!SetThreadPriority(m_hListenThread, THREAD_PRIORITY_ABOVE_NORMAL))
	{
		return false;
	}

	return true;
}

bool CSerialPort::CloseListenTread()
{
	if (m_hListenThread != INVALID_HANDLE_VALUE)
	{
		/** 通知线程退出 */
		s_bExit = true;

		/** 等待线程退出 */
		Sleep(10);

		/** 置线程句柄无效 */
		CloseHandle(m_hListenThread);
		m_hListenThread = INVALID_HANDLE_VALUE;
	}
	return true;
}

UINT CSerialPort::GetBytesInCOM()
{
	DWORD dwError = 0;  /** 错误码 */
	COMSTAT  comstat;   /** COMSTAT结构体,记录通信设备的状态信息 */
	memset(&comstat, 0, sizeof(COMSTAT));

	UINT BytesInQue = 0;
	/** 在调用ReadFile和WriteFile之前,通过本函数清除以前遗留的错误标志 */
	if (ClearCommError(m_hComm, &dwError, &comstat))
	{
		BytesInQue = comstat.cbInQue; /** 获取在输入缓冲区中的字节数 */
	}

	return BytesInQue;
}

UINT WINAPI CSerialPort::ListenThread(void* pParam)
{
	/** 得到本类的指针 */
	CSerialPort *pSerialPort = reinterpret_cast<CSerialPort*>(pParam);

	// 线程循环,轮询方式读取串口数据  
	while (!pSerialPort->s_bExit)
	{
		UINT BytesInQue = pSerialPort->GetBytesInCOM();
		/** 如果串口输入缓冲区中无数据,则休息一会再查询 */
		if (BytesInQue == 0)
		{
			Sleep(SLEEP_TIME_INTERVAL);
			continue;
		}

		/** 读取输入缓冲区中的数据并输出显示 */
		char cRecved = 0x00;
		do
		{
			cRecved = 0x00;
			if (pSerialPort->ReadChar(cRecved) == true)
			{
				std::cout << cRecved;
				continue;
			}
		} while (--BytesInQue);
	}

	return 0;
}

bool CSerialPort::ReadChar(char &cRecved)
{
	BOOL  bResult = TRUE;
	DWORD BytesRead = 0;
	if (m_hComm == INVALID_HANDLE_VALUE)
	{
		return false;
	}

	/** 临界区保护 */
	EnterCriticalSection(&m_csCommunicationSync);

	/** 从缓冲区读取一个字节的数据 */
	bResult = ReadFile(m_hComm, &cRecved, 1, &BytesRead, NULL);
	if ((!bResult))
	{
		/** 获取错误码,可以根据该错误码查出错误原因 */
		DWORD dwError = GetLastError();

		/** 清空串口缓冲区 */
		PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_RXABORT);
		LeaveCriticalSection(&m_csCommunicationSync);

		return false;
	}

	/** 离开临界区 */
	LeaveCriticalSection(&m_csCommunicationSync);

	return (BytesRead == 1);

}

bool CSerialPort::WriteData(unsigned char* pData, unsigned int length)
{
	BOOL   bResult = TRUE;
	DWORD  BytesToSend = 0;
	if (m_hComm == INVALID_HANDLE_VALUE)
	{
		return false;
	}

	/** 临界区保护 */
	EnterCriticalSection(&m_csCommunicationSync);

	/** 向缓冲区写入指定量的数据 */
	bResult = WriteFile(m_hComm, pData, length, &BytesToSend, NULL);
	if (!bResult)
	{
		DWORD dwError = GetLastError();
		/** 清空串口缓冲区 */
		PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_RXABORT);
		LeaveCriticalSection(&m_csCommunicationSync);

		return false;
	}

	/** 离开临界区 */
	LeaveCriticalSection(&m_csCommunicationSync);

	return true;

}
#pragma once

#ifndef SERIALPORT_H_  
#define SERIALPORT_H_  

#include <Windows.h>  

/** 串口通信类
*
*  本类实现了对串口的基本操作
*  例如监听发到指定串口的数据、发送指定数据到串口
*/
class CSerialPort
{
public:
	CSerialPort(void);
	~CSerialPort(void);

public:

	/** 初始化串口函数
	*
	*  @param:  UINT portNo 串口编号,默认值为1,即COM1,注意,尽量不要大于9
	*  @param:  UINT baud   波特率,默认为9600
	*  @param:  char parity 是否进行奇偶校验,'Y'表示需要奇偶校验,'N'表示不需要奇偶校验
	*  @param:  UINT databits 数据位的个数,默认值为8个数据位
	*  @param:  UINT stopsbits 停止位使用格式,默认值为1
	*  @param:  DWORD dwCommEvents 默认为EV_RXCHAR,即只要收发任意一个字符,则产生一个事件
	*  @return: bool  初始化是否成功
	*  @note:   在使用其他本类提供的函数前,请先调用本函数进行串口的初始化
	*        /n本函数提供了一些常用的串口参数设置,若需要自行设置详细的DCB参数,可使用重载函数
	*           /n本串口类析构时会自动关闭串口,无需额外执行关闭串口
	*  @see:
	*/
	bool InitPort(UINT  portNo =6, UINT  baud = CBR_4800, char  parity = 'N', UINT  databits = 8, UINT  stopsbits = 1, DWORD dwCommEvents = EV_RXCHAR);

	/** 串口初始化函数
	*
	*  本函数提供直接根据DCB参数设置串口参数
	*  @param:  UINT portNo
	*  @param:  const LPDCB & plDCB
	*  @return: bool  初始化是否成功
	*  @note:   本函数提供用户自定义地串口初始化参数
	*  @see:
	*/
	bool InitPort(UINT  portNo, const LPDCB& plDCB);

	/** 开启监听线程
	*
	*  本监听线程完成对串口数据的监听,并将接收到的数据打印到屏幕输出
	*  @return: bool  操作是否成功
	*  @note:   当线程已经处于开启状态时,返回flase
	*  @see:
	*/
	bool OpenListenThread();

	/** 关闭监听线程
	*
	*
	*  @return: bool  操作是否成功
	*  @note:   调用本函数后,监听串口的线程将会被关闭
	*  @see:
	*/
	bool CloseListenTread();

	/** 向串口写数据
	*
	*  将缓冲区中的数据写入到串口
	*  @param:  unsigned char * pData 指向需要写入串口的数据缓冲区
	*  @param:  unsigned int length 需要写入的数据长度
	*  @return: bool  操作是否成功
	*  @note:   length不要大于pData所指向缓冲区的大小
	*  @see:
	*/
	bool WriteData(unsigned char* pData, unsigned int length);

	/** 获取串口缓冲区中的字节数
	*
	*
	*  @return: UINT  操作是否成功
	*  @note:   当串口缓冲区中无数据时,返回0
	*  @see:
	*/
	UINT GetBytesInCOM();

	/** 读取串口接收缓冲区中一个字节的数据
	*
	*
	*  @param:  char & cRecved 存放读取数据的字符变量
	*  @return: bool  读取是否成功
	*  @note:
	*  @see:
	*/
	bool ReadChar(char &cRecved);

private:

	/** 打开串口
	*
	*
	*  @param:  UINT portNo 串口设备号
	*  @return: bool  打开是否成功
	*  @note:
	*  @see:
	*/
	bool openPort(UINT  portNo);

	/** 关闭串口
	*
	*
	*  @return: void  操作是否成功
	*  @note:
	*  @see:
	*/
	void ClosePort();

	/** 串口监听线程
	*
	*  监听来自串口的数据和信息
	*  @param:  void * pParam 线程参数
	*  @return: UINT WINAPI 线程返回值
	*  @note:
	*  @see:
	*/
	static UINT WINAPI ListenThread(void* pParam);

private:

	/** 串口句柄 */
	HANDLE  m_hComm;

	/** 线程退出标志变量 */
	static bool s_bExit;

	/** 线程句柄 */
	volatile HANDLE    m_hListenThread;

	/** 同步互斥,临界区保护 */
	CRITICAL_SECTION   m_csCommunicationSync;       //!< 互斥操作串口  

};

#endif //SERIALPORT_H_ 


展开阅读全文

用C语言实现串口通信

10-20

我想用C语言做一个串口通信的程序,网上找到不少代码,但是我直接复制粘贴到WINTC实现不了,说有问题,这是为什么,是不是需要用一些其他的软件?rn原来代码的网址http://wenku.baidu.com/view/4924fc03b52acfc789ebc9e2.htmlrn代码如下:rn[code=c]#include "stdafx.h"rn#include rn#include "resource.h"rn#include "MainDlg.h"rn#include rn#include rn#include rnHANDLE hComm;//用于获取串口打开函数的返回值(句柄或错误值)rnOVERLAPPED m_ov;rnCOMSTAT comstat;rnDWORD m_dwCommEvents;rnTCHAR cRecs[200],cSends[100]; //接收字符串 发送字符串 rnchar j=0,*cCom; //接收用统计数据大小变量 端口选择rnrnBOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)rnrnrnswitch(uMsg)rnrnHANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);rnHANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand);rnHANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);rnrnreturn FALSE;rnrn/*系统初始化函数*/rnBOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)rn rnrnHWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);rnComboBox_InsertString(hwndCombo1,-1,TEXT("COM1"));rnComboBox_InsertString(hwndCombo1,-1,TEXT("COM2"));rnComboBox_InsertString(hwndCombo1,-1,TEXT("COM3"));rnComboBox_InsertString(hwndCombo1,-1,TEXT("COM4"));rnComboBox_InsertString(hwndCombo1,-1,TEXT("COM5"));rnComboBox_SetCurSel(hwndCombo1,0);rnvoid CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime);rnSetTimer(hwnd,1,1000,TimerProc);rnreturn TRUE;rnrn/*监视串口错误时使用的函数*/rnbool ProcessErrorMessage(char* ErrorText)rnrnchar *Temp = new char[200];rnLPVOID lpMsgBuf;rnFormatMessage(rnFORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,rnNULL,rnGetLastError(),rnMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default languagern(LPTSTR) &lpMsgBuf,rn0,rnNULLrn);rnsprintf(Temp, "WARNING: %s Failed with the following error: \n%s\nPort: %d\n", (char*)ErrorText, lpMsgBuf, "com2");rnMessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);rnLocalFree(lpMsgBuf);rndelete[] Temp;rnreturn true;rnrnbool openport(char *portname)//打开串口rnrnhComm = CreateFile(portname, //串口号 “com1”“com2” 调用方法:bool open; open=openport("com2");rnGENERIC_READ | GENERIC_WRITE, //允许读写rn0, //通讯设备必须以独占方式打开rn0, //无安全属性rnOPEN_EXISTING, //通讯设备已存在rnFILE_FLAG_OVERLAPPED, //异步I/Orn0); //通讯设备不能用模板打开rnif (hComm == INVALID_HANDLE_VALUE) //如果被占用或是没有打开时返回的是这个错误代码rnrnCloseHandle(hComm);rnreturn FALSE;rnrnelsernreturn true;rnrnbool setupdcb(int rate_arg)//设置port的属性rnrnDCB dcb;rnint rate= rate_arg;rnmemset(&dcb,0,sizeof(dcb));rnif(!GetCommState(hComm,&dcb))//获取当前DCB配置rnreturn FALSE;rn// set DCB to configure the serial portrndcb.DCBlength = sizeof(dcb);rndcb.BaudRate = rate;rndcb.Parity = NOPARITY; //奇偶校验值0~4分别对应无校验、奇校验、偶校验、校验置位、校验清零rndcb.fParity = 0; //为1的话激活奇偶校验检查rndcb.StopBits = ONESTOPBIT;//停止位个数,0~2分别对应1位、1.5位、2位停止位rndcb.ByteSize = 8; //数据位数rndcb.fOutxCtsFlow = 0;rndcb.fOutxDsrFlow = 0;rndcb.fDtrControl = DTR_CONTROL_DISABLE;rndcb.fDsrSensitivity = 0;rndcb.fRtsControl = RTS_CONTROL_DISABLE;rndcb.fOutX = 0;rndcb.fInX = 0;rndcb.fErrorChar = 0;rndcb.fBinary = 1;rndcb.fNull = 0;rndcb.fAbortOnError = 0;rndcb.wReserved = 0;rndcb.XonLim = 2;rndcb.XoffLim = 4;rndcb.XonChar = 0x13;rndcb.XoffChar = 0x19;rndcb.EvtChar = 0;rn// set DCBrnif(!SetCommState(hComm,&dcb))rnreturn false;rnelsernreturn true;rnrn/*串口读取相关时间设置*/rnbool setuptimeout(DWORD ReadInterval,DWORD ReadTotalMultiplier,DWORD ReadTotalconstant,DWORD WriteTotalMultiplier,DWORD WriteTotalconstant)rnrnCOMMTIMEOUTS timeouts;rntimeouts.ReadIntervalTimeout=ReadInterval; //读取两个字节间隔最大值mS如超过立即返回不再读取rntimeouts.ReadTotalTimeoutConstant=ReadTotalconstant; //如果同下面一个都为0 则无论是否读到数据都返回rn// 可以毫秒为单位指定一个乘数,该乘数用来计算读操作的总限时时间rntimeouts.ReadTotalTimeoutMultiplier=ReadTotalMultiplier; // 以毫秒为单位指定一个常数,用于计算读操作的总限时时间 0表示不限时rntimeouts.WriteTotalTimeoutConstant=WriteTotalconstant;// 写操作延时 同上rntimeouts.WriteTotalTimeoutMultiplier=WriteTotalMultiplier;rnif(!SetCommTimeouts(hComm, &timeouts))rnreturn false;rnelsernreturn true;rnrnint Clearn() //清除buff中的内容并返回buff中现有数据量的大小并读取错误原因rnrnDWORD dwError = 0;rnDWORD BytesRead = 0;rnClearCommError(hComm, &dwError, &comstat);rnreturn comstat.cbInQue; //返回buff中数据量rnrn/*串口数据接收 读取函数*/rnvoid ReceiveChar()rnrnBOOL bRead = TRUE;rnBOOL bResult = TRUE;rnDWORD dwError = 0;rnDWORD BytesRead = 0;rnchar i=0,n;rnchar RXBuff;rnj=0;rnwhile (i-n)rnrnn=i;rnSleep(10);rnbResult = ClearCommError(hComm, &dwError, &comstat);rni=(char)comstat.cbInQue; rn rnfor (;i>0;i--)rnrnif (bRead)rnbResult = ReadFile(hComm, // Handle to COMM portrn&RXBuff, // RX Buffer Pointerrn1, // Read one bytern&BytesRead, // Stores number of bytes readrn&m_ov); // pointer to the m_ov structurern// printf("%c",RXBuff);rncRecs[j++]=(char)RXBuff;rnif (!bResult)rnrnswitch (dwError = GetLastError())rnrncase ERROR_IO_PENDING:rnrnbRead = FALSE;rnbreak;rnrndefault: break;rnrnrnelsernbRead = TRUE; // close if (bRead)rnif (!bRead)rnrnbRead = TRUE;rnbResult = GetOverlappedResult(hComm, // Handle to COMM portrn&m_ov, // Overlapped structurern&BytesRead, // Stores number of bytes readrnTRUE); // Wait flagrnrnrnrnrnbool WriteChar(char* m_szWriteBuffer,DWORD m_nToSend) //写字符的函数rnrnBOOL bWrite = TRUE;rnBOOL bResult = TRUE;rnDWORD BytesSent = 0;rnHANDLE m_hWriteEvent;rnResetEvent(m_hWriteEvent);rnif (bWrite)rnrnm_ov.Offset = 0;rnm_ov.OffsetHigh = 0;// Clear bufferrnbResult = WriteFile(hComm, // Handle to COMM Portrnm_szWriteBuffer, // Pointer to message buffer in calling finctionrnm_nToSend, // Length of message to sendrn&BytesSent, // Where to store the number of bytes sentrn&m_ov ); // Overlapped structurernif (!bResult)rnrnDWORD dwError = GetLastError();rnswitch (dwError)rnrncase ERROR_IO_PENDING:rnrn// continue to GetOverlappedResults()rnBytesSent = 0;rnbWrite = FALSE;rnbreak;rnrndefault:rn// all other error codesrnbreak;rnrnrn // end if(bWrite)rnif (!bWrite)rnrnbWrite = TRUE;rnbResult = GetOverlappedResult(hComm, // Handle to COMM portrn&m_ov, // Overlapped structurern&BytesSent, // Stores number of bytes sentrnTRUE); // Wait flagrn// deal with the error codernif (!bResult)rnrnprintf("GetOverlappedResults() in WriteFile()");rnrn // end if (!bWrite)rn// Verify that the data size send equals what we tried to sendrnif (BytesSent != m_nToSend)rnrnprintf("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)m_szWriteBuffer));rnrnreturn true;rnrn/*window时间函数 回调*/rnvoid CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)rnrnSYSTEMTIME time; //定义机构体变量time rnGetLocalTime(&time); //取系统时间以指针方式rnTCHAR strTime[256]; //程序只有一个作用rnwsprintf(strTime,"%04d-%02d-%02d %02d:%02d:%02d",time.wYear, //就是读取系统时间rntime.wMonth,time.wDay,time.wHour,time.wMinute,time.wSecond);//然后写进strTimernSetDlgItemText(hwnd,IDC_TIME,strTime); //这个字符串rnrnvoid Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)rnrnswitch(id)rnrncase IDC_SEND:rn rnGetDlgItemText (hwnd,IDC_EDIT2,cSends,sizeof(cSends));rnunsigned n=sizeof(cSends); //n是通知串口将发送字节的长度rnchar send[100];rnwsprintf (send,"%s",cSends);rnWriteChar(send,n-1);rnSetCommMask(hComm, EV_RXCHAR); //监视串口是否接收有数据rnReceiveChar(); //读取串口sbuff中数据rncRecs[j]='\0'; //将cRecs转为字符串rnSetDlgItemText(hwnd,IDC_EDIT1,cRecs); rn break;rn/*rncase IDC_RECEIVE: //暂时未用 采用直接显示的方式rn rnrnrnbreak;*/rncase IDC_CHECK:rnrnint ctr;rnHWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);rnctr = ComboBox_GetCurSel(hwndCombo1);rnswitch (ctr)rnrncase 0:cCom="com1";break;rncase 1:cCom="com2";break;rncase 2:cCom="com3";break;rncase 3:cCom="com4";break;rncase 4:cCom="com5";break;rndefault: cCom="com1";rnbreak;rnrnif (openport(cCom))rn SetDlgItemText(hwnd,IDC_EDIT3,"OK !"); rnMessageBox(hwnd,"串口打开成功!","",0); rnelsernSetDlgItemText(hwnd,IDC_EDIT3,"FAIL");rnif(setupdcb(9600)&&setuptimeout(1024,0,0,20,1000)) //初始化串口属性 波特率9600rnSetDlgItemText(hwnd,IDC_EDIT4,"串口属性设置成功"); rnelsernSetDlgItemText(hwnd,IDC_EDIT4,"串口初始化失败!");rnPurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);rnrndefault:rnbreak;rnrnrnvoid Main_OnClose(HWND hwnd)rnrnEndDialog(hwnd, 0);rnrnrn[/code] 论坛

没有更多推荐了,返回首页