如何实现两台pc机间的零modem链接,对串口和编码毫无头绪的我去找代码发现能用的没几个,绝望之下看到
https://blog.csdn.net/jc83278/article/details/78951313?spm=1001.2014.3001.5506 这篇博文,很感谢博主虽然也经历一番波折最终还是实现了收发。 如果你想有进步就看上面这篇按他的步骤先建立个虚拟的串口(听其他码友说如果直接进行两台pc机间的收发不调好波特率和比特率会烧坏串口,怕怕的就先建个模拟的吧),然后再琢磨他的代码,看如何改进,你如果想完成个任务就看我下面这个代码。
接收方:
#include<windows.h>
#include<stdio.h>
#include<stdint.h>
#include<iostream>
using namespace std;
typedef struct {
HANDLE hCom;
uint32_t baudrate;
uint32_t bytesize;
char parity;
uint32_t stopbit;
} rs232_device;
int set_opt(HANDLE hFile, int nSpeed, int nBits, char nEvent, int nStop)
{
DCB dcb;
COMMTIMEOUTS timeouts;
SetupComm(hFile, 512, 512);
timeouts.ReadIntervalTimeout = 1000;
timeouts.ReadTotalTimeoutMultiplier = 500;
timeouts.ReadTotalTimeoutConstant = 5000;
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(hFile, &timeouts);
if (0 == GetCommState(hFile, &dcb)){
return -1;
}
switch(nSpeed){
case 2400:
dcb.BaudRate = CBR_2400;
break;
case 4800:
dcb.BaudRate = CBR_4800;
break;
case 115200:
dcb.BaudRate = CBR_115200;
break;
default:
dcb.BaudRate = CBR_9600;
break;
}
switch(nBits){
case 7:
dcb.ByteSize = 7;
break;
case 8:
dcb.ByteSize = 8;
break;
default:
dcb.ByteSize = 8;
break;
}
switch(nEvent){
case 'N':
dcb.Parity = NOPARITY;
break;
case 'O':
dcb.Parity = ODDPARITY;
break;
case 'E':
dcb.Parity = EVENPARITY;
break;
}
switch(nStop){
case 1:
dcb.StopBits = ONESTOPBIT;
break;
case 2:
dcb.StopBits = TWOSTOPBITS;
break;
}
if(0 == SetCommState(hFile, &dcb)){
return -1;
}
return 0;
}
int main()
{
rs232_device rs232_dev;
rs232_dev.baudrate = 119200;
rs232_dev.bytesize = 8;
rs232_dev.parity = 'N';
rs232_dev.stopbit = 1;
rs232_dev.hCom = CreateFile("COM3",GENERIC_READ |GENERIC_WRITE, 0,NULL,OPEN_EXISTING,0,NULL);
if (rs232_dev.hCom !=INVALID_HANDLE_VALUE)
{
printf("Open COM3 OK!\n");
}else
printf("Open COM3 Fail!\n");
if(-1 == set_opt(rs232_dev.hCom,
rs232_dev.baudrate,
rs232_dev.bytesize,
rs232_dev.parity,
rs232_dev.stopbit))
{
if(INVALID_HANDLE_VALUE != rs232_dev.hCom)
CloseHandle(rs232_dev.hCom);
}
unsigned char readBuf[1024];
char writeBuf[1024];
int count = 100;
DWORD readsize = 0;
DWORD writesize = 0;
int i;
while(1){
if(INVALID_HANDLE_VALUE != rs232_dev.hCom)
{
printf("Start Read!\n");
ReadFile(rs232_dev.hCom, readBuf, count, &readsize, NULL);
printf("Read Buf=");
for(i=0;i<readsize;i++)
{
printf("%c", readBuf[i]);
}
printf("\n");
}
}
return 0;
}
本人也较懒,发送方的代码也就不打了,传个图片 就是把main里的改一下就可,想怎么收发随你,提示最好使用c++中的cin和cout,我也不清楚scanf到底比他差在哪,哪天有时间学学。下面是发送方:
|