2009-05-05 84 views

回答

1

This page在Microsoft Developer Network上介紹瞭如何使用Windows中的串行端口,根據您選擇的編譯器,我假定它是您想要定位的環境。

0

只有當您使用MSDOS或Windows的非常舊版本(並且特定於Turbo C)時,bios功能纔可用。對於現代版本的Windows,您需要使用OS API來執行串行I/O。

+0

要訪問Windows XP中的串行端口,什麼是OS API? – Shashikiran 2009-05-05 09:28:12

2

你必須像CreateFile那樣打開相應的com-device。適應您的需求。

// Handle of the communication connection 
void *comHandle; 

// Port parameters, set to your own needs 
unsigned portIndex; 
unsigned baudRate; 
unsigned dataBits; 
Parity parity; 
unsigned stopBits; 
bool  handShake; 
int  readIntervalTimeout; 
int  readTotalTimeoutMultiplier; 
int  readTotalTimeoutConstant; 
int  writeTotalTimeoutMultiplier; 
int  writeTotalTimeoutConstant; 
DCB dcb; 
COMMTIMEOUTS ct; 

// Create COM-device name string 
char comDevice[20]; 
sprintf(comDevice, "\\\\.\\COM%d", portIndex); 

// Open serial port 
_comHandle = CreateFile(comDevice, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); 
if (comHandle == INVALID_HANDLE_VALUE) 
{ 
    return false; 
} 


ct.ReadIntervalTimeout   = readIntervalTimeout;   
ct.ReadTotalTimeoutMultiplier = readTotalTimeoutMultiplier; 
ct.ReadTotalTimeoutConstant = readTotalTimeoutConstant; 
ct.WriteTotalTimeoutMultiplier = writeTotalTimeoutMultiplier; 
ct.WriteTotalTimeoutConstant = writeTotalTimeoutConstant; 

if (!GetCommState(_comHandle,&dcb)) 
{ 
    disconnect(); 
    return false; 
} 

dcb.BaudRate  = baudRate; 
dcb.ByteSize  = (BYTE)dataBits; 
dcb.Parity   = (parity == None) ? NOPARITY : ((parity == Even) ? EVENPARITY : ODDPARITY); 
dcb.StopBits  = (stopBits > 1) ? TWOSTOPBITS : ONESTOPBIT; 
dcb.fRtsControl  = handShake ? RTS_CONTROL_HANDSHAKE : RTS_CONTROL_ENABLE; 
dcb.fOutxCtsFlow = handShake; 
dcb.fOutxDsrFlow = handShake; 
dcb.fDtrControl  = handShake ? DTR_CONTROL_HANDSHAKE : DTR_CONTROL_ENABLE; 
dcb.fDsrSensitivity = handShake; 
dcb.fOutX   = FALSE; 
dcb.fInX   = FALSE; 
dcb.fErrorChar  = FALSE; 
dcb.fNull   = FALSE; 
dcb.fAbortOnError = TRUE; 

// Set port state 
if(!SetCommState(_omHandle, &dcb) || 
    !SetCommTimeouts(comHandle, &ct) || 
    !SetupComm(comHandle, 64, 64) || 
    !PurgeComm(comHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR)) 
{ 
    disconnect(); 
    return false; 
} 

請閱讀適用於各種調用函數的相應MSDN條目。另外,出於簡潔的原因,我省略了斷開連接方法。