繁体   English   中英

如何在C程序中进行串行通讯?

[英]How to do serial communication in c program?

使用vc ++编译器如何可以访问串行端口。 Bioscom()函数可在Turbo C中使用。

您必须像这样用CreateFile打开相应的通讯设备。 适应您的需求。

// 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条目以了解各种功能。 另外,出于简洁的原因,我省略了断开连接的方法。

他们是Code Project中有关与C ++进行串行通信的许多文章。 这是第一返回的文章 您基本上可以通过文件I / O操作访问端口。 这有点复杂,我建议为该任务找到合适的库。

Microsoft开发人员网络上的此页面介绍了如何在Windows中使用串行端口,根据您选择的编译器,我假设这是您要定位的环境。

仅当您使用MSDOS或Windows的非常旧的版本(特定于Turbo C)时,BIOS功能才可用。 对于现代版本的Windows,您将需要使用OS API来执行串行I / O。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM