自己动手编写串口动态库超详细.docx
文本预览下载声明
自己动手编写串口动态库
手把手教你编写串口调试助手,单片机串口程序
一、串口库源码: 自行在vc6中建立动态库工程
#include stdafx.h
#include stdio.h
#include stdlib.h
#include windows.h
#include conio.h
#includeresource.h
/*导出函数*/
//函数参数:串口名:com1 波特率:9600 用于显示接收数据的文本框的句柄
extern C _declspec(dllexport) void Entry(char *comname, int BaudRate, HWND rhbox);
extern C _declspec(dllexport) bool openport(char *portname);
extern C _declspec(dllexport) bool setupdcb(int rate_arg);
extern C _declspec(dllexport) void SetTimeOut(int a, int b, int c, int d, int e);
//发送字符或16进制数
extern C _declspec(dllexport) void SendChar(unsigned char ch);
//显示方式:1:hex 0:char
extern C _declspec(dllexport) void DisplayHex(int flag);
extern C _declspec(dllexport) void Close();
//只使用上面有注释的三个函数即可
HANDLE hComm;//串口的句柄
OVERLAPPED m_ov;//是一个包含了用于异步输入输出的信息的结构体
COMSTAT comstat;//包含串口结构信息
HANDLE hThread1; //读线程句柄
HANDLE hThread2; //写线程句柄
HWND hRbox;
bool sendflag = false;
unsigned char sendchar, receivechar;
bool DisplayHEX = false;
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,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
if (hComm == INVALID_HANDLE_VALUE)
return FALSE;
else
return true;
}
/****************设备控制块的设置*********************/
//参数 波特率rate_arg: 9600
bool setupdcb(int rate_arg)
{
DCB dcb;
int rate = rate_arg;
memset(dcb, 0, sizeof(dcb)); //申请一个DCB结构体空间
if (!GetCommState(hComm, dcb))//获取当前DCB配置
{
Proce
显示全部