程序如下:
#include "stdafx.h"
#include
#include
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char Ipbuffer[]="Hello world!";
HANDLE hComm;
LPCSTR portName = "COM2";
hComm = CreateFile(TEXT(portName), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hComm == INVALID_HANDLE_VALUE)
cout << "Error: Unable to open " << portName << " port." << endl;
else
cout << "Successfully connected to " << portName << " port." << endl;
Sleep(1000);
DCB PortDCB;
PortDCB.DCBlength = sizeof (DCB);
GetCommState (hComm, &PortDCB); // Get the default serial port settings DCB information. .
PortDCB.BaudRate = 230400;
PortDCB.fBinary = TRUE; // Binary mode; no EOF check
PortDCB.fParity = FALSE; // Disable parity checking
PortDCB.fOutxCtsFlow = FALSE; // No CTS output flow control
PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control
PortDCB.fDtrControl = DTR_CONTROL_DISABLE; // DT flow control tRype
PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity //
PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx
PortDCB.fOutX = FALSE; // No XON/XOFF out flow control
PortDCB.fInX = FALSE; // No XON/XOFF in flow control
PortDCB.fErrorChar = FALSE; // Disable error replacement
PortDCB.fNull = FALSE; // Disable null stripping
PortDCB.fRtsControl = RTS_CONTROL_DISABLE; // Disable RTS flow control
PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes onerror
PortDCB.ByteSize = 8; // Number of bits/byte, 4-8
PortDCB.Parity = NOPARITY; // 0-4=no,odd,even,mark,space
PortDCB.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2 // set serial port settings
if(!SetCommState(hComm,&PortDCB))
{
cout<< "Error: Unable to set comm state." << endl;
}
else
{
cout << "Comm state configured. Baud rate = " << PortDCB.BaudRate << "." << endl;
}
Sleep(1000);
if (!WriteFile(hComm, Ipbuffer, strlen(Ipbuffer), NULL, NULL))
std::cout<<"serial write errors"<<std::endl;
return 0;
}