Windows下基于API的串口程序
用WINAPI实现的同步串口,封装了个类,下面放出源代码,用的CPP.哪位同好说下如何挂代码片…现在还是不太会…
用WINAPI实现的同步串口,封装了个类,下面放出源代码,用的CPP.哪位同好说下如何挂代码片…现在还是不太会…
//stdafx.h
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
extern wchar_t *String_T_LPCWSTR(string temp);
// TODO: 在此处引用程序需要的其他头文件
class SerialPort
{
public:
SerialPort(LPCWSTR C_Name,DWORD tsize,DWORD rsize,DWORD B_Rate,BYTE B_Size)
{
while(!OpenCom(C_Name))
{
string Command;
cout<<"Serial Port:";
cin>>Command;
C_Name=String_T_LPCWSTR(Command);
}
SetupComm(hCom,tsize,rsize);//设置缓冲区大小,都为32字节
Baud_Rate=B_Rate;
Byte_Size=B_Size;
init();
}
~SerialPort()
{
CloseHandle(hCom);
}
void ReadBuf(string &RxBuf);
void WriteBuf(string &Txbuf);
bool OpenCom(LPCWSTR p);
void init();
HANDLE hCom;
private:
DWORD Baud_Rate;
BYTE Byte_Size;
DCB dcb;
COMMTIMEOUTS TimeOuts;
};
ReadBuf():读数据
WriteBuf():写数据。
OpenCom():打开串口,初始化函数看下面的例程就可以,为了省事很多都设置的默认
//stdafx.cpp,具体函数,WCharToMByte()这个转自网络,原作者记不太清了,原作者看到了私信我我加来源
#include "stdafx.h"
bool WCharToMByte(LPCWSTR lpcwszStr, string &str)
{
DWORD dwMinSize = 0;
LPSTR lpszStr = NULL;
dwMinSize = WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
if(0 == dwMinSize)
{
return FALSE;
}
lpszStr = new char [dwMinSize];
WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwMinSize,NULL,FALSE);
str = lpszStr;
delete [] lpszStr;
lpszStr = NULL;
return TRUE;
}
wchar_t *String_T_LPCWSTR(string temp)
{
size_t size = temp.length();
wchar_t *buffer = new wchar_t[size+1];
MultiByteToWideChar( CP_ACP, 0, temp.c_str(), size, buffer, size * sizeof(wchar_t) );
buffer[size] = 0;
return buffer;
}
bool SerialPort::OpenCom(LPCWSTR p)
{
hCom=CreateFile(p,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if(hCom==(HANDLE)-1)
{
string a;
WCharToMByte(p,a);
cout<<">>Serial Port "<<a<<" Failed,Maybe It Doesn't Exists.\n>>";
return 0;
}
cout<<">>Succeed"<<endl;
return 1;
}
void SerialPort::init()
{
//设定读超时
TimeOuts.ReadIntervalTimeout=10;
TimeOuts.ReadTotalTimeoutMultiplier=15;
TimeOuts.ReadTotalTimeoutConstant=200;
//设定写超时
TimeOuts.WriteTotalTimeoutMultiplier=2;
TimeOuts.WriteTotalTimeoutConstant=10;
SetCommTimeouts(hCom,&TimeOuts);
//设置超时
GetCommState(hCom,&dcb);
dcb.BaudRate=Baud_Rate; //波特率为9600
dcb.ByteSize=Byte_Size; //每个字节有x位
dcb.Parity=NOPARITY; //无奇偶校验位
dcb.StopBits=ONESTOPBIT; //一个停止位
SetCommState(hCom,&dcb);
}
void SerialPort::ReadBuf(string &RxBuf)//一次读取32字节,number返回读到的字数
{
DWORD Number;
char _RxBuf[32];
if(ReadFile(hCom,_RxBuf,32,&Number,NULL))
{
static int continues=1;
while(1)
{
continues++;
if(!(continues==2))
{
ReadFile(hCom,_RxBuf,32,&Number,NULL);
}
if(Number)
{
RxBuf.append((const char*)_RxBuf);
for(int i=0;i<32;i++)
{
_RxBuf[i]='\0';
}
RxBuf.erase(Number,RxBuf.length()-1);
cout<<"->"<<RxBuf<<"\n";
}
else
{
if(continues==2)
{
//cout<<"->No Data Recieved"<<endl;
continues=1;
}
else
{
wcout<<"->Data Is All Recieved"<<endl;
continues=1;
}
break;
}
}
}
RxBuf.clear();
}
void SerialPort::WriteBuf(string &TxBuf)//一次写入32字节
{
char _TxBuf[32];
for(int i=0;i<=(TxBuf.length()-1);i++)
{
_TxBuf[i]=TxBuf[i];
}
COMSTAT ComStat;
DWORD dwErrorFlags;
DWORD dwBytesWrite=TxBuf.length();
ClearCommError(hCom,&dwErrorFlags,&ComStat);
if(!WriteFile(hCom,_TxBuf,dwBytesWrite,&dwBytesWrite,NULL))
{
wcout<<"Transmit Failed"<<endl;
}
PurgeComm(hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR); //清除缓冲区
}
主程序:
#include "stdafx.h"
string Command,RxBuf;
void GetSystemCommand(string &t,SerialPort &p)
/*这个是自己编写的命令,如果输入的命令里面有则执行,否则就直接串口发送,空格是两个命令的分隔,最后发出去的最后都会有'\n'结尾*/
{
transform(t.begin(),t.end(),t.begin(),tolower);
if(t=="exit")
{
exit(0);
}
else if(t=="cls")
{
system("cls");
}
else if(!(t.find("clisten",0)==-1))
{
t.erase(0,8);
if (t.length())
{
int _Temp(0);
_Temp=atoi(&(t[0]));
while (_Temp) // 消息循环
{
for(int i=1;i<=_Temp;i++)
{
p.ReadBuf(RxBuf);
}
wcout<<"->Enter Waiting Times:";
cin>>_Temp;
}
}
else
{
wcout<<"->Please Enter Waiting Times\n";
}
}
else
{
for(int i=0;i<=(t.length()-1);i++)
{
if(isspace(t[i]))
{
t[i]='\n';
}
}
t.append("\n");
if(t.length()>32)
{
cout<<">>Command is Too Long"<<endl;
}
else
{
p.WriteBuf(t);
p.ReadBuf(RxBuf);
}
}
}
int main()
{
cout<<">>Software Starting....\n>>Ver 1.0\n>>Welcome To This Program.This Program Is A Demo.\n>>Serial Port:";
cin>>Command;
wchar_t *temp_p=String_T_LPCWSTR(Command);//转成wchar
SerialPort Port1(String_T_LPCWSTR(Command),32,32,9600,8);//名字,接受缓冲,发送缓冲,波特率,一字节大小
delete temp_p;temp_p=0;//释放临时指针,指针为零
while(1)
{
wcout<<">>";
cin.sync();
getline(cin,Command);
GetSystemCommand(Command,Port1);
}
}
给我很大帮助的贴子:http://blog.csdn.net/zhongguoren666/article/details/7195498
原帖没给实用的完整代码,我随便贴一个…写的不好不要喷…
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)